diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..61afe2b115f89db61395447d2edc7ca535bf9c8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.pb.h @@ -0,0 +1,126 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tsl/protobuf/error_codes.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2ferror_5fcodes_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tsl_2fprotobuf_2ferror_5fcodes_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2ferror_5fcodes_2eproto; +PROTOBUF_NAMESPACE_OPEN +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace error { + +enum Code : int { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + UNAUTHENTICATED = 16, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_ = 20, + Code_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + Code_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool Code_IsValid(int value); +constexpr Code Code_MIN = OK; +constexpr Code Code_MAX = DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_; +constexpr int Code_ARRAYSIZE = Code_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Code_descriptor(); +template +inline const std::string& Code_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Code_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + Code_descriptor(), enum_t_value); +} +inline bool Code_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Code* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + Code_descriptor(), name, value); +} +// =================================================================== + + +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace error +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::error::Code> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::error::Code>() { + return ::tensorflow::error::Code_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ferror_5fcodes_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.proto new file mode 100644 index 0000000000000000000000000000000000000000..c873d55887f1ddba8d38b6bc95fbe94f5cd34855 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/error_codes.proto @@ -0,0 +1,155 @@ +syntax = "proto3"; + +// TODO(b/247876220): Change package and java_package once we figure out how to +// migrate. + +package tensorflow.error; + +option cc_enable_arenas = true; +option java_outer_classname = "ErrorCodesProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto"; + +// The canonical error codes for TensorFlow APIs. +// +// Warnings: +// +// - Do not change any numeric assignments. +// - Changes to this list should only be made if there is a compelling +// need that can't be satisfied in another way. Such changes +// must be approved by at least two OWNERS. +// - These error codes must match gRPC and protobuf error codes (except for +// DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_). +// +// Sometimes multiple error codes may apply. Services should return +// the most specific error code that applies. For example, prefer +// OUT_OF_RANGE over FAILED_PRECONDITION if both codes apply. +// Similarly prefer NOT_FOUND or ALREADY_EXISTS over FAILED_PRECONDITION. +enum Code { + // Not an error; returned on success + OK = 0; + + // The operation was cancelled (typically by the caller). + CANCELLED = 1; + + // Unknown error. An example of where this error may be returned is + // if a Status value received from another address space belongs to + // an error-space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + UNKNOWN = 2; + + // Client specified an invalid argument. Note that this differs + // from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + INVALID_ARGUMENT = 3; + + // Deadline expired before operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + DEADLINE_EXCEEDED = 4; + + // Some requested entity (e.g., file or directory) was not found. + // For privacy reasons, this code *may* be returned when the client + // does not have the access right to the entity. + NOT_FOUND = 5; + + // Some entity that we attempted to create (e.g., file or directory) + // already exists. + ALREADY_EXISTS = 6; + + // The caller does not have permission to execute the specified + // operation. PERMISSION_DENIED must not be used for rejections + // caused by exhausting some resource (use RESOURCE_EXHAUSTED + // instead for those errors). PERMISSION_DENIED must not be + // used if the caller can not be identified (use UNAUTHENTICATED + // instead for those errors). + PERMISSION_DENIED = 7; + + // The request does not have valid authentication credentials for the + // operation. + UNAUTHENTICATED = 16; + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + RESOURCE_EXHAUSTED = 8; + + // Operation was rejected because the system is not in a state + // required for the operation's execution. For example, directory + // to be deleted may be non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // A litmus test that may help a service implementor in deciding + // between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + // (a) Use UNAVAILABLE if the client can retry just the failing call. + // (b) Use ABORTED if the client should retry at a higher-level + // (e.g., restarting a read-modify-write sequence). + // (c) Use FAILED_PRECONDITION if the client should not retry until + // the system state has been explicitly fixed. E.g., if an "rmdir" + // fails because the directory is non-empty, FAILED_PRECONDITION + // should be returned since the client should not retry unless + // they have first fixed up the directory by deleting files from it. + // (d) Use FAILED_PRECONDITION if the client performs conditional + // REST Get/Update/Delete on a resource and the resource on the + // server does not match the condition. E.g., conflicting + // read-modify-write on the same resource. + FAILED_PRECONDITION = 9; + + // The operation was aborted, typically due to a concurrency issue + // like sequencer check failures, transaction aborts, etc. + // + // See litmus test above for deciding between FAILED_PRECONDITION, + // ABORTED, and UNAVAILABLE. + ABORTED = 10; + + // Operation tried to iterate past the valid input range. E.g., seeking or + // reading past end of file. + // + // Unlike INVALID_ARGUMENT, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate INVALID_ARGUMENT if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // OUT_OF_RANGE if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between FAILED_PRECONDITION and + // OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an OUT_OF_RANGE error to detect when + // they are done. + OUT_OF_RANGE = 11; + + // Operation is not implemented or not supported/enabled in this service. + UNIMPLEMENTED = 12; + + // Internal errors. Means some invariant expected by the underlying + // system has been broken. If you see one of these errors, + // something is very broken. + INTERNAL = 13; + + // The service is currently unavailable. This is a most likely a + // transient condition and may be corrected by retrying with + // a backoff. + // + // See litmus test above for deciding between FAILED_PRECONDITION, + // ABORTED, and UNAVAILABLE. + UNAVAILABLE = 14; + + // Unrecoverable data loss or corruption. + DATA_LOSS = 15; + + // An extra enum entry to prevent people from writing code that + // fails to compile when a new code is added. + // + // Nobody should ever reference this enumeration entry. In particular, + // if you write C++ code that switches on this enumeration, add a default: + // case instead of a case that mentions this enumeration entry. + // + // Nobody should rely on the value (currently 20) listed here. It + // may change in the future. + DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_ = 20; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..412dcbb1a817dbf0a28ec3ab8968378f0565871a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.pb.h @@ -0,0 +1,513 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tsl/protobuf/histogram.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2fhistogram_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tsl_2fprotobuf_2fhistogram_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2fhistogram_2eproto; +namespace tensorflow { +class HistogramProto; +struct HistogramProtoDefaultTypeInternal; +extern HistogramProtoDefaultTypeInternal _HistogramProto_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::HistogramProto* Arena::CreateMaybeMessage<::tensorflow::HistogramProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class HistogramProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.HistogramProto) */ { + public: + inline HistogramProto() : HistogramProto(nullptr) {} + ~HistogramProto() override; + explicit PROTOBUF_CONSTEXPR HistogramProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HistogramProto(const HistogramProto& from); + HistogramProto(HistogramProto&& from) noexcept + : HistogramProto() { + *this = ::std::move(from); + } + + inline HistogramProto& operator=(const HistogramProto& from) { + CopyFrom(from); + return *this; + } + inline HistogramProto& operator=(HistogramProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const HistogramProto& default_instance() { + return *internal_default_instance(); + } + static inline const HistogramProto* internal_default_instance() { + return reinterpret_cast( + &_HistogramProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HistogramProto& a, HistogramProto& b) { + a.Swap(&b); + } + inline void Swap(HistogramProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(HistogramProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HistogramProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HistogramProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HistogramProto& from) { + HistogramProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(HistogramProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.HistogramProto"; + } + protected: + explicit HistogramProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kBucketLimitFieldNumber = 6, + kBucketFieldNumber = 7, + kMinFieldNumber = 1, + kMaxFieldNumber = 2, + kNumFieldNumber = 3, + kSumFieldNumber = 4, + kSumSquaresFieldNumber = 5, + }; + // repeated double bucket_limit = 6 [packed = true]; + int bucket_limit_size() const; + private: + int _internal_bucket_limit_size() const; + public: + void clear_bucket_limit(); + private: + double _internal_bucket_limit(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& + _internal_bucket_limit() const; + void _internal_add_bucket_limit(double value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* + _internal_mutable_bucket_limit(); + public: + double bucket_limit(int index) const; + void set_bucket_limit(int index, double value); + void add_bucket_limit(double value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& + bucket_limit() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* + mutable_bucket_limit(); + + // repeated double bucket = 7 [packed = true]; + int bucket_size() const; + private: + int _internal_bucket_size() const; + public: + void clear_bucket(); + private: + double _internal_bucket(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& + _internal_bucket() const; + void _internal_add_bucket(double value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* + _internal_mutable_bucket(); + public: + double bucket(int index) const; + void set_bucket(int index, double value); + void add_bucket(double value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& + bucket() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* + mutable_bucket(); + + // double min = 1; + void clear_min(); + double min() const; + void set_min(double value); + private: + double _internal_min() const; + void _internal_set_min(double value); + public: + + // double max = 2; + void clear_max(); + double max() const; + void set_max(double value); + private: + double _internal_max() const; + void _internal_set_max(double value); + public: + + // double num = 3; + void clear_num(); + double num() const; + void set_num(double value); + private: + double _internal_num() const; + void _internal_set_num(double value); + public: + + // double sum = 4; + void clear_sum(); + double sum() const; + void set_sum(double value); + private: + double _internal_sum() const; + void _internal_set_sum(double value); + public: + + // double sum_squares = 5; + void clear_sum_squares(); + double sum_squares() const; + void set_sum_squares(double value); + private: + double _internal_sum_squares() const; + void _internal_set_sum_squares(double value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.HistogramProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double > bucket_limit_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< double > bucket_; + double min_; + double max_; + double num_; + double sum_; + double sum_squares_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2fhistogram_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HistogramProto + +// double min = 1; +inline void HistogramProto::clear_min() { + _impl_.min_ = 0; +} +inline double HistogramProto::_internal_min() const { + return _impl_.min_; +} +inline double HistogramProto::min() const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.min) + return _internal_min(); +} +inline void HistogramProto::_internal_set_min(double value) { + + _impl_.min_ = value; +} +inline void HistogramProto::set_min(double value) { + _internal_set_min(value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.min) +} + +// double max = 2; +inline void HistogramProto::clear_max() { + _impl_.max_ = 0; +} +inline double HistogramProto::_internal_max() const { + return _impl_.max_; +} +inline double HistogramProto::max() const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.max) + return _internal_max(); +} +inline void HistogramProto::_internal_set_max(double value) { + + _impl_.max_ = value; +} +inline void HistogramProto::set_max(double value) { + _internal_set_max(value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.max) +} + +// double num = 3; +inline void HistogramProto::clear_num() { + _impl_.num_ = 0; +} +inline double HistogramProto::_internal_num() const { + return _impl_.num_; +} +inline double HistogramProto::num() const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.num) + return _internal_num(); +} +inline void HistogramProto::_internal_set_num(double value) { + + _impl_.num_ = value; +} +inline void HistogramProto::set_num(double value) { + _internal_set_num(value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.num) +} + +// double sum = 4; +inline void HistogramProto::clear_sum() { + _impl_.sum_ = 0; +} +inline double HistogramProto::_internal_sum() const { + return _impl_.sum_; +} +inline double HistogramProto::sum() const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.sum) + return _internal_sum(); +} +inline void HistogramProto::_internal_set_sum(double value) { + + _impl_.sum_ = value; +} +inline void HistogramProto::set_sum(double value) { + _internal_set_sum(value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.sum) +} + +// double sum_squares = 5; +inline void HistogramProto::clear_sum_squares() { + _impl_.sum_squares_ = 0; +} +inline double HistogramProto::_internal_sum_squares() const { + return _impl_.sum_squares_; +} +inline double HistogramProto::sum_squares() const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.sum_squares) + return _internal_sum_squares(); +} +inline void HistogramProto::_internal_set_sum_squares(double value) { + + _impl_.sum_squares_ = value; +} +inline void HistogramProto::set_sum_squares(double value) { + _internal_set_sum_squares(value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.sum_squares) +} + +// repeated double bucket_limit = 6 [packed = true]; +inline int HistogramProto::_internal_bucket_limit_size() const { + return _impl_.bucket_limit_.size(); +} +inline int HistogramProto::bucket_limit_size() const { + return _internal_bucket_limit_size(); +} +inline void HistogramProto::clear_bucket_limit() { + _impl_.bucket_limit_.Clear(); +} +inline double HistogramProto::_internal_bucket_limit(int index) const { + return _impl_.bucket_limit_.Get(index); +} +inline double HistogramProto::bucket_limit(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.bucket_limit) + return _internal_bucket_limit(index); +} +inline void HistogramProto::set_bucket_limit(int index, double value) { + _impl_.bucket_limit_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.bucket_limit) +} +inline void HistogramProto::_internal_add_bucket_limit(double value) { + _impl_.bucket_limit_.Add(value); +} +inline void HistogramProto::add_bucket_limit(double value) { + _internal_add_bucket_limit(value); + // @@protoc_insertion_point(field_add:tensorflow.HistogramProto.bucket_limit) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& +HistogramProto::_internal_bucket_limit() const { + return _impl_.bucket_limit_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& +HistogramProto::bucket_limit() const { + // @@protoc_insertion_point(field_list:tensorflow.HistogramProto.bucket_limit) + return _internal_bucket_limit(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* +HistogramProto::_internal_mutable_bucket_limit() { + return &_impl_.bucket_limit_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* +HistogramProto::mutable_bucket_limit() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.HistogramProto.bucket_limit) + return _internal_mutable_bucket_limit(); +} + +// repeated double bucket = 7 [packed = true]; +inline int HistogramProto::_internal_bucket_size() const { + return _impl_.bucket_.size(); +} +inline int HistogramProto::bucket_size() const { + return _internal_bucket_size(); +} +inline void HistogramProto::clear_bucket() { + _impl_.bucket_.Clear(); +} +inline double HistogramProto::_internal_bucket(int index) const { + return _impl_.bucket_.Get(index); +} +inline double HistogramProto::bucket(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.HistogramProto.bucket) + return _internal_bucket(index); +} +inline void HistogramProto::set_bucket(int index, double value) { + _impl_.bucket_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.HistogramProto.bucket) +} +inline void HistogramProto::_internal_add_bucket(double value) { + _impl_.bucket_.Add(value); +} +inline void HistogramProto::add_bucket(double value) { + _internal_add_bucket(value); + // @@protoc_insertion_point(field_add:tensorflow.HistogramProto.bucket) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& +HistogramProto::_internal_bucket() const { + return _impl_.bucket_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >& +HistogramProto::bucket() const { + // @@protoc_insertion_point(field_list:tensorflow.HistogramProto.bucket) + return _internal_bucket(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* +HistogramProto::_internal_mutable_bucket() { + return &_impl_.bucket_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< double >* +HistogramProto::mutable_bucket() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.HistogramProto.bucket) + return _internal_mutable_bucket(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fhistogram_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.proto new file mode 100644 index 0000000000000000000000000000000000000000..2a5f6d9362a63b7254ed54bd150092cca0a65605 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/histogram.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package tensorflow; + +option cc_enable_arenas = true; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/google/tsl/tsl/go/core/protobuf/summary_go_proto"; + +// Serialization format for histogram module in +// tsl/lib/histogram/histogram.h +message HistogramProto { + double min = 1; + double max = 2; + double num = 3; + double sum = 4; + double sum_squares = 5; + + // Parallel arrays encoding the bucket boundaries and the bucket values. + // bucket(i) is the count for the bucket i. The range for + // a bucket is: + // i == 0: -DBL_MAX .. bucket_limit(0) + // i != 0: bucket_limit(i-1) .. bucket_limit(i) + repeated double bucket_limit = 6 [packed = true]; + repeated double bucket = 7 [packed = true]; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..c8f1bcc71c8952b915800383aabc398be74d6d12 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.pb.h @@ -0,0 +1,437 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tsl/protobuf/rpc_options.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2frpc_5foptions_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tsl_2fprotobuf_2frpc_5foptions_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2frpc_5foptions_2eproto; +namespace tensorflow { +class RPCOptions; +struct RPCOptionsDefaultTypeInternal; +extern RPCOptionsDefaultTypeInternal _RPCOptions_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::RPCOptions* Arena::CreateMaybeMessage<::tensorflow::RPCOptions>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class RPCOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.RPCOptions) */ { + public: + inline RPCOptions() : RPCOptions(nullptr) {} + ~RPCOptions() override; + explicit PROTOBUF_CONSTEXPR RPCOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + RPCOptions(const RPCOptions& from); + RPCOptions(RPCOptions&& from) noexcept + : RPCOptions() { + *this = ::std::move(from); + } + + inline RPCOptions& operator=(const RPCOptions& from) { + CopyFrom(from); + return *this; + } + inline RPCOptions& operator=(RPCOptions&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const RPCOptions& default_instance() { + return *internal_default_instance(); + } + static inline const RPCOptions* internal_default_instance() { + return reinterpret_cast( + &_RPCOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(RPCOptions& a, RPCOptions& b) { + a.Swap(&b); + } + inline void Swap(RPCOptions* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(RPCOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + RPCOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const RPCOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const RPCOptions& from) { + RPCOptions::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(RPCOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.RPCOptions"; + } + protected: + explicit RPCOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kCompressionAlgorithmFieldNumber = 2, + kCompressionLevelFieldNumber = 3, + kUseRpcForInprocessMasterFieldNumber = 1, + kCacheRpcResponseFieldNumber = 4, + kDisableSessionConnectionSharingFieldNumber = 5, + kNumChannelsPerTargetFieldNumber = 6, + }; + // string compression_algorithm = 2; + void clear_compression_algorithm(); + const std::string& compression_algorithm() const; + template + void set_compression_algorithm(ArgT0&& arg0, ArgT... args); + std::string* mutable_compression_algorithm(); + PROTOBUF_NODISCARD std::string* release_compression_algorithm(); + void set_allocated_compression_algorithm(std::string* compression_algorithm); + private: + const std::string& _internal_compression_algorithm() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_compression_algorithm(const std::string& value); + std::string* _internal_mutable_compression_algorithm(); + public: + + // int32 compression_level = 3; + void clear_compression_level(); + int32_t compression_level() const; + void set_compression_level(int32_t value); + private: + int32_t _internal_compression_level() const; + void _internal_set_compression_level(int32_t value); + public: + + // bool use_rpc_for_inprocess_master = 1; + void clear_use_rpc_for_inprocess_master(); + bool use_rpc_for_inprocess_master() const; + void set_use_rpc_for_inprocess_master(bool value); + private: + bool _internal_use_rpc_for_inprocess_master() const; + void _internal_set_use_rpc_for_inprocess_master(bool value); + public: + + // bool cache_rpc_response = 4; + void clear_cache_rpc_response(); + bool cache_rpc_response() const; + void set_cache_rpc_response(bool value); + private: + bool _internal_cache_rpc_response() const; + void _internal_set_cache_rpc_response(bool value); + public: + + // bool disable_session_connection_sharing = 5; + void clear_disable_session_connection_sharing(); + bool disable_session_connection_sharing() const; + void set_disable_session_connection_sharing(bool value); + private: + bool _internal_disable_session_connection_sharing() const; + void _internal_set_disable_session_connection_sharing(bool value); + public: + + // int32 num_channels_per_target = 6; + void clear_num_channels_per_target(); + int32_t num_channels_per_target() const; + void set_num_channels_per_target(int32_t value); + private: + int32_t _internal_num_channels_per_target() const; + void _internal_set_num_channels_per_target(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.RPCOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr compression_algorithm_; + int32_t compression_level_; + bool use_rpc_for_inprocess_master_; + bool cache_rpc_response_; + bool disable_session_connection_sharing_; + int32_t num_channels_per_target_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2frpc_5foptions_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// RPCOptions + +// bool use_rpc_for_inprocess_master = 1; +inline void RPCOptions::clear_use_rpc_for_inprocess_master() { + _impl_.use_rpc_for_inprocess_master_ = false; +} +inline bool RPCOptions::_internal_use_rpc_for_inprocess_master() const { + return _impl_.use_rpc_for_inprocess_master_; +} +inline bool RPCOptions::use_rpc_for_inprocess_master() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.use_rpc_for_inprocess_master) + return _internal_use_rpc_for_inprocess_master(); +} +inline void RPCOptions::_internal_set_use_rpc_for_inprocess_master(bool value) { + + _impl_.use_rpc_for_inprocess_master_ = value; +} +inline void RPCOptions::set_use_rpc_for_inprocess_master(bool value) { + _internal_set_use_rpc_for_inprocess_master(value); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.use_rpc_for_inprocess_master) +} + +// string compression_algorithm = 2; +inline void RPCOptions::clear_compression_algorithm() { + _impl_.compression_algorithm_.ClearToEmpty(); +} +inline const std::string& RPCOptions::compression_algorithm() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.compression_algorithm) + return _internal_compression_algorithm(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void RPCOptions::set_compression_algorithm(ArgT0&& arg0, ArgT... args) { + + _impl_.compression_algorithm_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.compression_algorithm) +} +inline std::string* RPCOptions::mutable_compression_algorithm() { + std::string* _s = _internal_mutable_compression_algorithm(); + // @@protoc_insertion_point(field_mutable:tensorflow.RPCOptions.compression_algorithm) + return _s; +} +inline const std::string& RPCOptions::_internal_compression_algorithm() const { + return _impl_.compression_algorithm_.Get(); +} +inline void RPCOptions::_internal_set_compression_algorithm(const std::string& value) { + + _impl_.compression_algorithm_.Set(value, GetArenaForAllocation()); +} +inline std::string* RPCOptions::_internal_mutable_compression_algorithm() { + + return _impl_.compression_algorithm_.Mutable(GetArenaForAllocation()); +} +inline std::string* RPCOptions::release_compression_algorithm() { + // @@protoc_insertion_point(field_release:tensorflow.RPCOptions.compression_algorithm) + return _impl_.compression_algorithm_.Release(); +} +inline void RPCOptions::set_allocated_compression_algorithm(std::string* compression_algorithm) { + if (compression_algorithm != nullptr) { + + } else { + + } + _impl_.compression_algorithm_.SetAllocated(compression_algorithm, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.compression_algorithm_.IsDefault()) { + _impl_.compression_algorithm_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.RPCOptions.compression_algorithm) +} + +// int32 compression_level = 3; +inline void RPCOptions::clear_compression_level() { + _impl_.compression_level_ = 0; +} +inline int32_t RPCOptions::_internal_compression_level() const { + return _impl_.compression_level_; +} +inline int32_t RPCOptions::compression_level() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.compression_level) + return _internal_compression_level(); +} +inline void RPCOptions::_internal_set_compression_level(int32_t value) { + + _impl_.compression_level_ = value; +} +inline void RPCOptions::set_compression_level(int32_t value) { + _internal_set_compression_level(value); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.compression_level) +} + +// bool cache_rpc_response = 4; +inline void RPCOptions::clear_cache_rpc_response() { + _impl_.cache_rpc_response_ = false; +} +inline bool RPCOptions::_internal_cache_rpc_response() const { + return _impl_.cache_rpc_response_; +} +inline bool RPCOptions::cache_rpc_response() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.cache_rpc_response) + return _internal_cache_rpc_response(); +} +inline void RPCOptions::_internal_set_cache_rpc_response(bool value) { + + _impl_.cache_rpc_response_ = value; +} +inline void RPCOptions::set_cache_rpc_response(bool value) { + _internal_set_cache_rpc_response(value); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.cache_rpc_response) +} + +// bool disable_session_connection_sharing = 5; +inline void RPCOptions::clear_disable_session_connection_sharing() { + _impl_.disable_session_connection_sharing_ = false; +} +inline bool RPCOptions::_internal_disable_session_connection_sharing() const { + return _impl_.disable_session_connection_sharing_; +} +inline bool RPCOptions::disable_session_connection_sharing() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.disable_session_connection_sharing) + return _internal_disable_session_connection_sharing(); +} +inline void RPCOptions::_internal_set_disable_session_connection_sharing(bool value) { + + _impl_.disable_session_connection_sharing_ = value; +} +inline void RPCOptions::set_disable_session_connection_sharing(bool value) { + _internal_set_disable_session_connection_sharing(value); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.disable_session_connection_sharing) +} + +// int32 num_channels_per_target = 6; +inline void RPCOptions::clear_num_channels_per_target() { + _impl_.num_channels_per_target_ = 0; +} +inline int32_t RPCOptions::_internal_num_channels_per_target() const { + return _impl_.num_channels_per_target_; +} +inline int32_t RPCOptions::num_channels_per_target() const { + // @@protoc_insertion_point(field_get:tensorflow.RPCOptions.num_channels_per_target) + return _internal_num_channels_per_target(); +} +inline void RPCOptions::_internal_set_num_channels_per_target(int32_t value) { + + _impl_.num_channels_per_target_ = value; +} +inline void RPCOptions::set_num_channels_per_target(int32_t value) { + _internal_set_num_channels_per_target(value); + // @@protoc_insertion_point(field_set:tensorflow.RPCOptions.num_channels_per_target) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2frpc_5foptions_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.proto new file mode 100644 index 0000000000000000000000000000000000000000..35c5dbe3b1bf4eccd581fe1ae6c5b66a657f6ecd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/rpc_options.proto @@ -0,0 +1,41 @@ +syntax = "proto3"; + +package tensorflow; + +option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto"; + +// RPC options for distributed runtime. +message RPCOptions { + // If true, always use RPC to contact the session target. + // + // If false (the default option), TensorFlow may use an optimized + // transport for client-master communication that avoids the RPC + // stack. This option is primarily for used testing the RPC stack. + bool use_rpc_for_inprocess_master = 1; + + // The compression algorithm to be used. One of "deflate", "gzip". + string compression_algorithm = 2; + + // If compression_algorithm is set, the compression level to be used. + // From 0 (no compression), up to 3. + int32 compression_level = 3; + + // Setting cache_rpc_response to true will enable sender side caching of + // response for RecvTensorAsync and RecvBufAsync to allow receiver to retry + // requests . This is only necessary when the network fabric is experiencing a + // significant error rate. Without it we'll fail a step on an network error, + // while with it we'll be able to complete long steps (like complex + // initializations) in the face of some network errors during RecvTensor. + bool cache_rpc_response = 4; + + // Disables TCP connection sharing when opening a new RPC channel. + bool disable_session_connection_sharing = 5; + + // Setting num_channels_per_target > 0 allows uses of multiple channels to + // communicate to the same target. This can be used to improve the aggregate + // throughput on high speed links (e.g 100G) where single connection is not + // sufficient to maximize link utilization. Note that a single RPC only goes + // on a single channel, this only helps in situations where there are multiple + // transfers to the same target overlapping in time. + int32 num_channels_per_target = 6; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..da97ca3fd192ce05b6218001988e87ea25a9945e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.pb.h @@ -0,0 +1,314 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tsl/protobuf/status.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include "tsl/protobuf/error_codes.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2fstatus_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tsl_2fprotobuf_2fstatus_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2fstatus_2eproto; +namespace tensorflow { +class StatusProto; +struct StatusProtoDefaultTypeInternal; +extern StatusProtoDefaultTypeInternal _StatusProto_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::StatusProto* Arena::CreateMaybeMessage<::tensorflow::StatusProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class StatusProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.StatusProto) */ { + public: + inline StatusProto() : StatusProto(nullptr) {} + ~StatusProto() override; + explicit PROTOBUF_CONSTEXPR StatusProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + StatusProto(const StatusProto& from); + StatusProto(StatusProto&& from) noexcept + : StatusProto() { + *this = ::std::move(from); + } + + inline StatusProto& operator=(const StatusProto& from) { + CopyFrom(from); + return *this; + } + inline StatusProto& operator=(StatusProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const StatusProto& default_instance() { + return *internal_default_instance(); + } + static inline const StatusProto* internal_default_instance() { + return reinterpret_cast( + &_StatusProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(StatusProto& a, StatusProto& b) { + a.Swap(&b); + } + inline void Swap(StatusProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(StatusProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + StatusProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const StatusProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const StatusProto& from) { + StatusProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(StatusProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.StatusProto"; + } + protected: + explicit StatusProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMessageFieldNumber = 2, + kCodeFieldNumber = 1, + }; + // string message = 2; + void clear_message(); + const std::string& message() const; + template + void set_message(ArgT0&& arg0, ArgT... args); + std::string* mutable_message(); + PROTOBUF_NODISCARD std::string* release_message(); + void set_allocated_message(std::string* message); + private: + const std::string& _internal_message() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_message(const std::string& value); + std::string* _internal_mutable_message(); + public: + + // .tensorflow.error.Code code = 1; + void clear_code(); + ::tensorflow::error::Code code() const; + void set_code(::tensorflow::error::Code value); + private: + ::tensorflow::error::Code _internal_code() const; + void _internal_set_code(::tensorflow::error::Code value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.StatusProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr message_; + int code_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2fstatus_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// StatusProto + +// .tensorflow.error.Code code = 1; +inline void StatusProto::clear_code() { + _impl_.code_ = 0; +} +inline ::tensorflow::error::Code StatusProto::_internal_code() const { + return static_cast< ::tensorflow::error::Code >(_impl_.code_); +} +inline ::tensorflow::error::Code StatusProto::code() const { + // @@protoc_insertion_point(field_get:tensorflow.StatusProto.code) + return _internal_code(); +} +inline void StatusProto::_internal_set_code(::tensorflow::error::Code value) { + + _impl_.code_ = value; +} +inline void StatusProto::set_code(::tensorflow::error::Code value) { + _internal_set_code(value); + // @@protoc_insertion_point(field_set:tensorflow.StatusProto.code) +} + +// string message = 2; +inline void StatusProto::clear_message() { + _impl_.message_.ClearToEmpty(); +} +inline const std::string& StatusProto::message() const { + // @@protoc_insertion_point(field_get:tensorflow.StatusProto.message) + return _internal_message(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void StatusProto::set_message(ArgT0&& arg0, ArgT... args) { + + _impl_.message_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.StatusProto.message) +} +inline std::string* StatusProto::mutable_message() { + std::string* _s = _internal_mutable_message(); + // @@protoc_insertion_point(field_mutable:tensorflow.StatusProto.message) + return _s; +} +inline const std::string& StatusProto::_internal_message() const { + return _impl_.message_.Get(); +} +inline void StatusProto::_internal_set_message(const std::string& value) { + + _impl_.message_.Set(value, GetArenaForAllocation()); +} +inline std::string* StatusProto::_internal_mutable_message() { + + return _impl_.message_.Mutable(GetArenaForAllocation()); +} +inline std::string* StatusProto::release_message() { + // @@protoc_insertion_point(field_release:tensorflow.StatusProto.message) + return _impl_.message_.Release(); +} +inline void StatusProto::set_allocated_message(std::string* message) { + if (message != nullptr) { + + } else { + + } + _impl_.message_.SetAllocated(message, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.message_.IsDefault()) { + _impl_.message_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.StatusProto.message) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2fstatus_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.proto new file mode 100644 index 0000000000000000000000000000000000000000..09d72218941ee20cd1c5bc1d84615e789fc0a0e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/status.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package tensorflow; + +import "tsl/protobuf/error_codes.proto"; + +option cc_enable_arenas = true; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/google/tsl/tsl/go/protobuf/for_core_protos_go_proto"; + +// Wire-format for Status. +// Next tag: 3 +message StatusProto { + // Status code as defined in tensorflow/tsl/protobuf/error_codes.proto. + error.Code code = 1; + + // Detail error message. + string message = 2; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..2dcc8e97bac10f8e9c5e368ae5462620777294b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.pb.h @@ -0,0 +1,6514 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tsl/protobuf/test_log.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ftest_5flog_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ftest_5flog_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include +#include +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tsl_2fprotobuf_2ftest_5flog_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tsl_2fprotobuf_2ftest_5flog_2eproto; +namespace tensorflow { +class AvailableDeviceInfo; +struct AvailableDeviceInfoDefaultTypeInternal; +extern AvailableDeviceInfoDefaultTypeInternal _AvailableDeviceInfo_default_instance_; +class BenchmarkEntries; +struct BenchmarkEntriesDefaultTypeInternal; +extern BenchmarkEntriesDefaultTypeInternal _BenchmarkEntries_default_instance_; +class BenchmarkEntry; +struct BenchmarkEntryDefaultTypeInternal; +extern BenchmarkEntryDefaultTypeInternal _BenchmarkEntry_default_instance_; +class BenchmarkEntry_ExtrasEntry_DoNotUse; +struct BenchmarkEntry_ExtrasEntry_DoNotUseDefaultTypeInternal; +extern BenchmarkEntry_ExtrasEntry_DoNotUseDefaultTypeInternal _BenchmarkEntry_ExtrasEntry_DoNotUse_default_instance_; +class BuildConfiguration; +struct BuildConfigurationDefaultTypeInternal; +extern BuildConfigurationDefaultTypeInternal _BuildConfiguration_default_instance_; +class CPUInfo; +struct CPUInfoDefaultTypeInternal; +extern CPUInfoDefaultTypeInternal _CPUInfo_default_instance_; +class CPUInfo_CacheSizeEntry_DoNotUse; +struct CPUInfo_CacheSizeEntry_DoNotUseDefaultTypeInternal; +extern CPUInfo_CacheSizeEntry_DoNotUseDefaultTypeInternal _CPUInfo_CacheSizeEntry_DoNotUse_default_instance_; +class CommitId; +struct CommitIdDefaultTypeInternal; +extern CommitIdDefaultTypeInternal _CommitId_default_instance_; +class EntryValue; +struct EntryValueDefaultTypeInternal; +extern EntryValueDefaultTypeInternal _EntryValue_default_instance_; +class GPUInfo; +struct GPUInfoDefaultTypeInternal; +extern GPUInfoDefaultTypeInternal _GPUInfo_default_instance_; +class MachineConfiguration; +struct MachineConfigurationDefaultTypeInternal; +extern MachineConfigurationDefaultTypeInternal _MachineConfiguration_default_instance_; +class MemoryInfo; +struct MemoryInfoDefaultTypeInternal; +extern MemoryInfoDefaultTypeInternal _MemoryInfo_default_instance_; +class MetricEntry; +struct MetricEntryDefaultTypeInternal; +extern MetricEntryDefaultTypeInternal _MetricEntry_default_instance_; +class PlatformInfo; +struct PlatformInfoDefaultTypeInternal; +extern PlatformInfoDefaultTypeInternal _PlatformInfo_default_instance_; +class RunConfiguration; +struct RunConfigurationDefaultTypeInternal; +extern RunConfigurationDefaultTypeInternal _RunConfiguration_default_instance_; +class RunConfiguration_EnvVarsEntry_DoNotUse; +struct RunConfiguration_EnvVarsEntry_DoNotUseDefaultTypeInternal; +extern RunConfiguration_EnvVarsEntry_DoNotUseDefaultTypeInternal _RunConfiguration_EnvVarsEntry_DoNotUse_default_instance_; +class TestResults; +struct TestResultsDefaultTypeInternal; +extern TestResultsDefaultTypeInternal _TestResults_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::AvailableDeviceInfo* Arena::CreateMaybeMessage<::tensorflow::AvailableDeviceInfo>(Arena*); +template<> ::tensorflow::BenchmarkEntries* Arena::CreateMaybeMessage<::tensorflow::BenchmarkEntries>(Arena*); +template<> ::tensorflow::BenchmarkEntry* Arena::CreateMaybeMessage<::tensorflow::BenchmarkEntry>(Arena*); +template<> ::tensorflow::BenchmarkEntry_ExtrasEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::BenchmarkEntry_ExtrasEntry_DoNotUse>(Arena*); +template<> ::tensorflow::BuildConfiguration* Arena::CreateMaybeMessage<::tensorflow::BuildConfiguration>(Arena*); +template<> ::tensorflow::CPUInfo* Arena::CreateMaybeMessage<::tensorflow::CPUInfo>(Arena*); +template<> ::tensorflow::CPUInfo_CacheSizeEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::CPUInfo_CacheSizeEntry_DoNotUse>(Arena*); +template<> ::tensorflow::CommitId* Arena::CreateMaybeMessage<::tensorflow::CommitId>(Arena*); +template<> ::tensorflow::EntryValue* Arena::CreateMaybeMessage<::tensorflow::EntryValue>(Arena*); +template<> ::tensorflow::GPUInfo* Arena::CreateMaybeMessage<::tensorflow::GPUInfo>(Arena*); +template<> ::tensorflow::MachineConfiguration* Arena::CreateMaybeMessage<::tensorflow::MachineConfiguration>(Arena*); +template<> ::tensorflow::MemoryInfo* Arena::CreateMaybeMessage<::tensorflow::MemoryInfo>(Arena*); +template<> ::tensorflow::MetricEntry* Arena::CreateMaybeMessage<::tensorflow::MetricEntry>(Arena*); +template<> ::tensorflow::PlatformInfo* Arena::CreateMaybeMessage<::tensorflow::PlatformInfo>(Arena*); +template<> ::tensorflow::RunConfiguration* Arena::CreateMaybeMessage<::tensorflow::RunConfiguration>(Arena*); +template<> ::tensorflow::RunConfiguration_EnvVarsEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::RunConfiguration_EnvVarsEntry_DoNotUse>(Arena*); +template<> ::tensorflow::TestResults* Arena::CreateMaybeMessage<::tensorflow::TestResults>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +enum TestResults_BenchmarkType : int { + TestResults_BenchmarkType_UNKNOWN = 0, + TestResults_BenchmarkType_CPP_MICROBENCHMARK = 1, + TestResults_BenchmarkType_PYTHON_BENCHMARK = 2, + TestResults_BenchmarkType_ANDROID_BENCHMARK = 3, + TestResults_BenchmarkType_EDGE_BENCHMARK = 4, + TestResults_BenchmarkType_IOS_BENCHMARK = 5, + TestResults_BenchmarkType_TestResults_BenchmarkType_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + TestResults_BenchmarkType_TestResults_BenchmarkType_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool TestResults_BenchmarkType_IsValid(int value); +constexpr TestResults_BenchmarkType TestResults_BenchmarkType_BenchmarkType_MIN = TestResults_BenchmarkType_UNKNOWN; +constexpr TestResults_BenchmarkType TestResults_BenchmarkType_BenchmarkType_MAX = TestResults_BenchmarkType_IOS_BENCHMARK; +constexpr int TestResults_BenchmarkType_BenchmarkType_ARRAYSIZE = TestResults_BenchmarkType_BenchmarkType_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* TestResults_BenchmarkType_descriptor(); +template +inline const std::string& TestResults_BenchmarkType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function TestResults_BenchmarkType_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + TestResults_BenchmarkType_descriptor(), enum_t_value); +} +inline bool TestResults_BenchmarkType_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, TestResults_BenchmarkType* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + TestResults_BenchmarkType_descriptor(), name, value); +} +// =================================================================== + +class EntryValue final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.EntryValue) */ { + public: + inline EntryValue() : EntryValue(nullptr) {} + ~EntryValue() override; + explicit PROTOBUF_CONSTEXPR EntryValue(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EntryValue(const EntryValue& from); + EntryValue(EntryValue&& from) noexcept + : EntryValue() { + *this = ::std::move(from); + } + + inline EntryValue& operator=(const EntryValue& from) { + CopyFrom(from); + return *this; + } + inline EntryValue& operator=(EntryValue&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const EntryValue& default_instance() { + return *internal_default_instance(); + } + enum KindCase { + kDoubleValue = 1, + kStringValue = 2, + KIND_NOT_SET = 0, + }; + + static inline const EntryValue* internal_default_instance() { + return reinterpret_cast( + &_EntryValue_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(EntryValue& a, EntryValue& b) { + a.Swap(&b); + } + inline void Swap(EntryValue* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(EntryValue* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EntryValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EntryValue& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EntryValue& from) { + EntryValue::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(EntryValue* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.EntryValue"; + } + protected: + explicit EntryValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kDoubleValueFieldNumber = 1, + kStringValueFieldNumber = 2, + }; + // double double_value = 1; + bool has_double_value() const; + private: + bool _internal_has_double_value() const; + public: + void clear_double_value(); + double double_value() const; + void set_double_value(double value); + private: + double _internal_double_value() const; + void _internal_set_double_value(double value); + public: + + // string string_value = 2; + bool has_string_value() const; + private: + bool _internal_has_string_value() const; + public: + void clear_string_value(); + const std::string& string_value() const; + template + void set_string_value(ArgT0&& arg0, ArgT... args); + std::string* mutable_string_value(); + PROTOBUF_NODISCARD std::string* release_string_value(); + void set_allocated_string_value(std::string* string_value); + private: + const std::string& _internal_string_value() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_string_value(const std::string& value); + std::string* _internal_mutable_string_value(); + public: + + void clear_kind(); + KindCase kind_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.EntryValue) + private: + class _Internal; + void set_has_double_value(); + void set_has_string_value(); + + inline bool has_kind() const; + inline void clear_has_kind(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union KindUnion { + constexpr KindUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + double double_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; + } kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class MetricEntry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.MetricEntry) */ { + public: + inline MetricEntry() : MetricEntry(nullptr) {} + ~MetricEntry() override; + explicit PROTOBUF_CONSTEXPR MetricEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MetricEntry(const MetricEntry& from); + MetricEntry(MetricEntry&& from) noexcept + : MetricEntry() { + *this = ::std::move(from); + } + + inline MetricEntry& operator=(const MetricEntry& from) { + CopyFrom(from); + return *this; + } + inline MetricEntry& operator=(MetricEntry&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const MetricEntry& default_instance() { + return *internal_default_instance(); + } + static inline const MetricEntry* internal_default_instance() { + return reinterpret_cast( + &_MetricEntry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(MetricEntry& a, MetricEntry& b) { + a.Swap(&b); + } + inline void Swap(MetricEntry* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(MetricEntry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MetricEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MetricEntry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MetricEntry& from) { + MetricEntry::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(MetricEntry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.MetricEntry"; + } + protected: + explicit MetricEntry(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kMinValueFieldNumber = 3, + kMaxValueFieldNumber = 4, + kValueFieldNumber = 2, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // .google.protobuf.DoubleValue min_value = 3; + bool has_min_value() const; + private: + bool _internal_has_min_value() const; + public: + void clear_min_value(); + const ::PROTOBUF_NAMESPACE_ID::DoubleValue& min_value() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::DoubleValue* release_min_value(); + ::PROTOBUF_NAMESPACE_ID::DoubleValue* mutable_min_value(); + void set_allocated_min_value(::PROTOBUF_NAMESPACE_ID::DoubleValue* min_value); + private: + const ::PROTOBUF_NAMESPACE_ID::DoubleValue& _internal_min_value() const; + ::PROTOBUF_NAMESPACE_ID::DoubleValue* _internal_mutable_min_value(); + public: + void unsafe_arena_set_allocated_min_value( + ::PROTOBUF_NAMESPACE_ID::DoubleValue* min_value); + ::PROTOBUF_NAMESPACE_ID::DoubleValue* unsafe_arena_release_min_value(); + + // .google.protobuf.DoubleValue max_value = 4; + bool has_max_value() const; + private: + bool _internal_has_max_value() const; + public: + void clear_max_value(); + const ::PROTOBUF_NAMESPACE_ID::DoubleValue& max_value() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::DoubleValue* release_max_value(); + ::PROTOBUF_NAMESPACE_ID::DoubleValue* mutable_max_value(); + void set_allocated_max_value(::PROTOBUF_NAMESPACE_ID::DoubleValue* max_value); + private: + const ::PROTOBUF_NAMESPACE_ID::DoubleValue& _internal_max_value() const; + ::PROTOBUF_NAMESPACE_ID::DoubleValue* _internal_mutable_max_value(); + public: + void unsafe_arena_set_allocated_max_value( + ::PROTOBUF_NAMESPACE_ID::DoubleValue* max_value); + ::PROTOBUF_NAMESPACE_ID::DoubleValue* unsafe_arena_release_max_value(); + + // double value = 2; + void clear_value(); + double value() const; + void set_value(double value); + private: + double _internal_value() const; + void _internal_set_value(double value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.MetricEntry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::DoubleValue* min_value_; + ::PROTOBUF_NAMESPACE_ID::DoubleValue* max_value_; + double value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class BenchmarkEntry_ExtrasEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + BenchmarkEntry_ExtrasEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR BenchmarkEntry_ExtrasEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit BenchmarkEntry_ExtrasEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const BenchmarkEntry_ExtrasEntry_DoNotUse& other); + static const BenchmarkEntry_ExtrasEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_BenchmarkEntry_ExtrasEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.BenchmarkEntry.ExtrasEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; + +// ------------------------------------------------------------------- + +class BenchmarkEntry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.BenchmarkEntry) */ { + public: + inline BenchmarkEntry() : BenchmarkEntry(nullptr) {} + ~BenchmarkEntry() override; + explicit PROTOBUF_CONSTEXPR BenchmarkEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BenchmarkEntry(const BenchmarkEntry& from); + BenchmarkEntry(BenchmarkEntry&& from) noexcept + : BenchmarkEntry() { + *this = ::std::move(from); + } + + inline BenchmarkEntry& operator=(const BenchmarkEntry& from) { + CopyFrom(from); + return *this; + } + inline BenchmarkEntry& operator=(BenchmarkEntry&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const BenchmarkEntry& default_instance() { + return *internal_default_instance(); + } + static inline const BenchmarkEntry* internal_default_instance() { + return reinterpret_cast( + &_BenchmarkEntry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(BenchmarkEntry& a, BenchmarkEntry& b) { + a.Swap(&b); + } + inline void Swap(BenchmarkEntry* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(BenchmarkEntry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BenchmarkEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BenchmarkEntry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BenchmarkEntry& from) { + BenchmarkEntry::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(BenchmarkEntry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.BenchmarkEntry"; + } + protected: + explicit BenchmarkEntry(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kExtrasFieldNumber = 6, + kMetricsFieldNumber = 7, + kNameFieldNumber = 1, + kItersFieldNumber = 2, + kCpuTimeFieldNumber = 3, + kWallTimeFieldNumber = 4, + kThroughputFieldNumber = 5, + }; + // map extras = 6; + int extras_size() const; + private: + int _internal_extras_size() const; + public: + void clear_extras(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >& + _internal_extras() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >* + _internal_mutable_extras(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >& + extras() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >* + mutable_extras(); + + // repeated .tensorflow.MetricEntry metrics = 7; + int metrics_size() const; + private: + int _internal_metrics_size() const; + public: + void clear_metrics(); + ::tensorflow::MetricEntry* mutable_metrics(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::MetricEntry >* + mutable_metrics(); + private: + const ::tensorflow::MetricEntry& _internal_metrics(int index) const; + ::tensorflow::MetricEntry* _internal_add_metrics(); + public: + const ::tensorflow::MetricEntry& metrics(int index) const; + ::tensorflow::MetricEntry* add_metrics(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::MetricEntry >& + metrics() const; + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // int64 iters = 2; + void clear_iters(); + int64_t iters() const; + void set_iters(int64_t value); + private: + int64_t _internal_iters() const; + void _internal_set_iters(int64_t value); + public: + + // double cpu_time = 3; + void clear_cpu_time(); + double cpu_time() const; + void set_cpu_time(double value); + private: + double _internal_cpu_time() const; + void _internal_set_cpu_time(double value); + public: + + // double wall_time = 4; + void clear_wall_time(); + double wall_time() const; + void set_wall_time(double value); + private: + double _internal_wall_time() const; + void _internal_set_wall_time(double value); + public: + + // double throughput = 5; + void clear_throughput(); + double throughput() const; + void set_throughput(double value); + private: + double _internal_throughput() const; + void _internal_set_throughput(double value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.BenchmarkEntry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + BenchmarkEntry_ExtrasEntry_DoNotUse, + std::string, ::tensorflow::EntryValue, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> extras_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::MetricEntry > metrics_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + int64_t iters_; + double cpu_time_; + double wall_time_; + double throughput_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class BenchmarkEntries final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.BenchmarkEntries) */ { + public: + inline BenchmarkEntries() : BenchmarkEntries(nullptr) {} + ~BenchmarkEntries() override; + explicit PROTOBUF_CONSTEXPR BenchmarkEntries(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BenchmarkEntries(const BenchmarkEntries& from); + BenchmarkEntries(BenchmarkEntries&& from) noexcept + : BenchmarkEntries() { + *this = ::std::move(from); + } + + inline BenchmarkEntries& operator=(const BenchmarkEntries& from) { + CopyFrom(from); + return *this; + } + inline BenchmarkEntries& operator=(BenchmarkEntries&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const BenchmarkEntries& default_instance() { + return *internal_default_instance(); + } + static inline const BenchmarkEntries* internal_default_instance() { + return reinterpret_cast( + &_BenchmarkEntries_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(BenchmarkEntries& a, BenchmarkEntries& b) { + a.Swap(&b); + } + inline void Swap(BenchmarkEntries* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(BenchmarkEntries* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BenchmarkEntries* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BenchmarkEntries& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BenchmarkEntries& from) { + BenchmarkEntries::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(BenchmarkEntries* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.BenchmarkEntries"; + } + protected: + explicit BenchmarkEntries(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kEntryFieldNumber = 1, + }; + // repeated .tensorflow.BenchmarkEntry entry = 1; + int entry_size() const; + private: + int _internal_entry_size() const; + public: + void clear_entry(); + ::tensorflow::BenchmarkEntry* mutable_entry(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::BenchmarkEntry >* + mutable_entry(); + private: + const ::tensorflow::BenchmarkEntry& _internal_entry(int index) const; + ::tensorflow::BenchmarkEntry* _internal_add_entry(); + public: + const ::tensorflow::BenchmarkEntry& entry(int index) const; + ::tensorflow::BenchmarkEntry* add_entry(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::BenchmarkEntry >& + entry() const; + + // @@protoc_insertion_point(class_scope:tensorflow.BenchmarkEntries) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::BenchmarkEntry > entry_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class BuildConfiguration final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.BuildConfiguration) */ { + public: + inline BuildConfiguration() : BuildConfiguration(nullptr) {} + ~BuildConfiguration() override; + explicit PROTOBUF_CONSTEXPR BuildConfiguration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BuildConfiguration(const BuildConfiguration& from); + BuildConfiguration(BuildConfiguration&& from) noexcept + : BuildConfiguration() { + *this = ::std::move(from); + } + + inline BuildConfiguration& operator=(const BuildConfiguration& from) { + CopyFrom(from); + return *this; + } + inline BuildConfiguration& operator=(BuildConfiguration&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const BuildConfiguration& default_instance() { + return *internal_default_instance(); + } + static inline const BuildConfiguration* internal_default_instance() { + return reinterpret_cast( + &_BuildConfiguration_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(BuildConfiguration& a, BuildConfiguration& b) { + a.Swap(&b); + } + inline void Swap(BuildConfiguration* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(BuildConfiguration* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BuildConfiguration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BuildConfiguration& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BuildConfiguration& from) { + BuildConfiguration::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(BuildConfiguration* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.BuildConfiguration"; + } + protected: + explicit BuildConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kCcFlagsFieldNumber = 2, + kOptsFieldNumber = 3, + kModeFieldNumber = 1, + }; + // repeated string cc_flags = 2; + int cc_flags_size() const; + private: + int _internal_cc_flags_size() const; + public: + void clear_cc_flags(); + const std::string& cc_flags(int index) const; + std::string* mutable_cc_flags(int index); + void set_cc_flags(int index, const std::string& value); + void set_cc_flags(int index, std::string&& value); + void set_cc_flags(int index, const char* value); + void set_cc_flags(int index, const char* value, size_t size); + std::string* add_cc_flags(); + void add_cc_flags(const std::string& value); + void add_cc_flags(std::string&& value); + void add_cc_flags(const char* value); + void add_cc_flags(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& cc_flags() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_cc_flags(); + private: + const std::string& _internal_cc_flags(int index) const; + std::string* _internal_add_cc_flags(); + public: + + // repeated string opts = 3; + int opts_size() const; + private: + int _internal_opts_size() const; + public: + void clear_opts(); + const std::string& opts(int index) const; + std::string* mutable_opts(int index); + void set_opts(int index, const std::string& value); + void set_opts(int index, std::string&& value); + void set_opts(int index, const char* value); + void set_opts(int index, const char* value, size_t size); + std::string* add_opts(); + void add_opts(const std::string& value); + void add_opts(std::string&& value); + void add_opts(const char* value); + void add_opts(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& opts() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_opts(); + private: + const std::string& _internal_opts(int index) const; + std::string* _internal_add_opts(); + public: + + // string mode = 1; + void clear_mode(); + const std::string& mode() const; + template + void set_mode(ArgT0&& arg0, ArgT... args); + std::string* mutable_mode(); + PROTOBUF_NODISCARD std::string* release_mode(); + void set_allocated_mode(std::string* mode); + private: + const std::string& _internal_mode() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_mode(const std::string& value); + std::string* _internal_mutable_mode(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.BuildConfiguration) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField cc_flags_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField opts_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr mode_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class CommitId final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CommitId) */ { + public: + inline CommitId() : CommitId(nullptr) {} + ~CommitId() override; + explicit PROTOBUF_CONSTEXPR CommitId(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CommitId(const CommitId& from); + CommitId(CommitId&& from) noexcept + : CommitId() { + *this = ::std::move(from); + } + + inline CommitId& operator=(const CommitId& from) { + CopyFrom(from); + return *this; + } + inline CommitId& operator=(CommitId&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CommitId& default_instance() { + return *internal_default_instance(); + } + enum KindCase { + kChangelist = 1, + kHash = 2, + KIND_NOT_SET = 0, + }; + + static inline const CommitId* internal_default_instance() { + return reinterpret_cast( + &_CommitId_default_instance_); + } + static constexpr int kIndexInFileMessages = + 6; + + friend void swap(CommitId& a, CommitId& b) { + a.Swap(&b); + } + inline void Swap(CommitId* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CommitId* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CommitId* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CommitId& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CommitId& from) { + CommitId::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(CommitId* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CommitId"; + } + protected: + explicit CommitId(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kSnapshotFieldNumber = 3, + kPendingChangelistFieldNumber = 4, + kChangelistFieldNumber = 1, + kHashFieldNumber = 2, + }; + // string snapshot = 3; + void clear_snapshot(); + const std::string& snapshot() const; + template + void set_snapshot(ArgT0&& arg0, ArgT... args); + std::string* mutable_snapshot(); + PROTOBUF_NODISCARD std::string* release_snapshot(); + void set_allocated_snapshot(std::string* snapshot); + private: + const std::string& _internal_snapshot() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_snapshot(const std::string& value); + std::string* _internal_mutable_snapshot(); + public: + + // int64 pending_changelist = 4; + void clear_pending_changelist(); + int64_t pending_changelist() const; + void set_pending_changelist(int64_t value); + private: + int64_t _internal_pending_changelist() const; + void _internal_set_pending_changelist(int64_t value); + public: + + // int64 changelist = 1; + bool has_changelist() const; + private: + bool _internal_has_changelist() const; + public: + void clear_changelist(); + int64_t changelist() const; + void set_changelist(int64_t value); + private: + int64_t _internal_changelist() const; + void _internal_set_changelist(int64_t value); + public: + + // string hash = 2; + bool has_hash() const; + private: + bool _internal_has_hash() const; + public: + void clear_hash(); + const std::string& hash() const; + template + void set_hash(ArgT0&& arg0, ArgT... args); + std::string* mutable_hash(); + PROTOBUF_NODISCARD std::string* release_hash(); + void set_allocated_hash(std::string* hash); + private: + const std::string& _internal_hash() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_hash(const std::string& value); + std::string* _internal_mutable_hash(); + public: + + void clear_kind(); + KindCase kind_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.CommitId) + private: + class _Internal; + void set_has_changelist(); + void set_has_hash(); + + inline bool has_kind() const; + inline void clear_has_kind(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr snapshot_; + int64_t pending_changelist_; + union KindUnion { + constexpr KindUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int64_t changelist_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hash_; + } kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class CPUInfo_CacheSizeEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + CPUInfo_CacheSizeEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR CPUInfo_CacheSizeEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit CPUInfo_CacheSizeEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const CPUInfo_CacheSizeEntry_DoNotUse& other); + static const CPUInfo_CacheSizeEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_CPUInfo_CacheSizeEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.CPUInfo.CacheSizeEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; + +// ------------------------------------------------------------------- + +class CPUInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CPUInfo) */ { + public: + inline CPUInfo() : CPUInfo(nullptr) {} + ~CPUInfo() override; + explicit PROTOBUF_CONSTEXPR CPUInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CPUInfo(const CPUInfo& from); + CPUInfo(CPUInfo&& from) noexcept + : CPUInfo() { + *this = ::std::move(from); + } + + inline CPUInfo& operator=(const CPUInfo& from) { + CopyFrom(from); + return *this; + } + inline CPUInfo& operator=(CPUInfo&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CPUInfo& default_instance() { + return *internal_default_instance(); + } + static inline const CPUInfo* internal_default_instance() { + return reinterpret_cast( + &_CPUInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 8; + + friend void swap(CPUInfo& a, CPUInfo& b) { + a.Swap(&b); + } + inline void Swap(CPUInfo* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CPUInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CPUInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CPUInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CPUInfo& from) { + CPUInfo::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(CPUInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CPUInfo"; + } + protected: + explicit CPUInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kCacheSizeFieldNumber = 6, + kCpuInfoFieldNumber = 4, + kCpuGovernorFieldNumber = 5, + kNumCoresFieldNumber = 1, + kNumCoresAllowedFieldNumber = 2, + kMhzPerCpuFieldNumber = 3, + }; + // map cache_size = 6; + int cache_size_size() const; + private: + int _internal_cache_size_size() const; + public: + void clear_cache_size(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& + _internal_cache_size() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* + _internal_mutable_cache_size(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& + cache_size() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* + mutable_cache_size(); + + // string cpu_info = 4; + void clear_cpu_info(); + const std::string& cpu_info() const; + template + void set_cpu_info(ArgT0&& arg0, ArgT... args); + std::string* mutable_cpu_info(); + PROTOBUF_NODISCARD std::string* release_cpu_info(); + void set_allocated_cpu_info(std::string* cpu_info); + private: + const std::string& _internal_cpu_info() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_cpu_info(const std::string& value); + std::string* _internal_mutable_cpu_info(); + public: + + // string cpu_governor = 5; + void clear_cpu_governor(); + const std::string& cpu_governor() const; + template + void set_cpu_governor(ArgT0&& arg0, ArgT... args); + std::string* mutable_cpu_governor(); + PROTOBUF_NODISCARD std::string* release_cpu_governor(); + void set_allocated_cpu_governor(std::string* cpu_governor); + private: + const std::string& _internal_cpu_governor() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_cpu_governor(const std::string& value); + std::string* _internal_mutable_cpu_governor(); + public: + + // int64 num_cores = 1; + void clear_num_cores(); + int64_t num_cores() const; + void set_num_cores(int64_t value); + private: + int64_t _internal_num_cores() const; + void _internal_set_num_cores(int64_t value); + public: + + // int64 num_cores_allowed = 2; + void clear_num_cores_allowed(); + int64_t num_cores_allowed() const; + void set_num_cores_allowed(int64_t value); + private: + int64_t _internal_num_cores_allowed() const; + void _internal_set_num_cores_allowed(int64_t value); + public: + + // double mhz_per_cpu = 3; + void clear_mhz_per_cpu(); + double mhz_per_cpu() const; + void set_mhz_per_cpu(double value); + private: + double _internal_mhz_per_cpu() const; + void _internal_set_mhz_per_cpu(double value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.CPUInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + CPUInfo_CacheSizeEntry_DoNotUse, + std::string, int64_t, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> cache_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr cpu_info_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr cpu_governor_; + int64_t num_cores_; + int64_t num_cores_allowed_; + double mhz_per_cpu_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class MemoryInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.MemoryInfo) */ { + public: + inline MemoryInfo() : MemoryInfo(nullptr) {} + ~MemoryInfo() override; + explicit PROTOBUF_CONSTEXPR MemoryInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MemoryInfo(const MemoryInfo& from); + MemoryInfo(MemoryInfo&& from) noexcept + : MemoryInfo() { + *this = ::std::move(from); + } + + inline MemoryInfo& operator=(const MemoryInfo& from) { + CopyFrom(from); + return *this; + } + inline MemoryInfo& operator=(MemoryInfo&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const MemoryInfo& default_instance() { + return *internal_default_instance(); + } + static inline const MemoryInfo* internal_default_instance() { + return reinterpret_cast( + &_MemoryInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 9; + + friend void swap(MemoryInfo& a, MemoryInfo& b) { + a.Swap(&b); + } + inline void Swap(MemoryInfo* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(MemoryInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MemoryInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MemoryInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MemoryInfo& from) { + MemoryInfo::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(MemoryInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.MemoryInfo"; + } + protected: + explicit MemoryInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kTotalFieldNumber = 1, + kAvailableFieldNumber = 2, + }; + // int64 total = 1; + void clear_total(); + int64_t total() const; + void set_total(int64_t value); + private: + int64_t _internal_total() const; + void _internal_set_total(int64_t value); + public: + + // int64 available = 2; + void clear_available(); + int64_t available() const; + void set_available(int64_t value); + private: + int64_t _internal_available() const; + void _internal_set_available(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.MemoryInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t total_; + int64_t available_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class GPUInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.GPUInfo) */ { + public: + inline GPUInfo() : GPUInfo(nullptr) {} + ~GPUInfo() override; + explicit PROTOBUF_CONSTEXPR GPUInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GPUInfo(const GPUInfo& from); + GPUInfo(GPUInfo&& from) noexcept + : GPUInfo() { + *this = ::std::move(from); + } + + inline GPUInfo& operator=(const GPUInfo& from) { + CopyFrom(from); + return *this; + } + inline GPUInfo& operator=(GPUInfo&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const GPUInfo& default_instance() { + return *internal_default_instance(); + } + static inline const GPUInfo* internal_default_instance() { + return reinterpret_cast( + &_GPUInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 10; + + friend void swap(GPUInfo& a, GPUInfo& b) { + a.Swap(&b); + } + inline void Swap(GPUInfo* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(GPUInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GPUInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GPUInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GPUInfo& from) { + GPUInfo::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(GPUInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.GPUInfo"; + } + protected: + explicit GPUInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kModelFieldNumber = 1, + kUuidFieldNumber = 2, + kBusIdFieldNumber = 3, + }; + // string model = 1; + void clear_model(); + const std::string& model() const; + template + void set_model(ArgT0&& arg0, ArgT... args); + std::string* mutable_model(); + PROTOBUF_NODISCARD std::string* release_model(); + void set_allocated_model(std::string* model); + private: + const std::string& _internal_model() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_model(const std::string& value); + std::string* _internal_mutable_model(); + public: + + // string uuid = 2; + void clear_uuid(); + const std::string& uuid() const; + template + void set_uuid(ArgT0&& arg0, ArgT... args); + std::string* mutable_uuid(); + PROTOBUF_NODISCARD std::string* release_uuid(); + void set_allocated_uuid(std::string* uuid); + private: + const std::string& _internal_uuid() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_uuid(const std::string& value); + std::string* _internal_mutable_uuid(); + public: + + // string bus_id = 3; + void clear_bus_id(); + const std::string& bus_id() const; + template + void set_bus_id(ArgT0&& arg0, ArgT... args); + std::string* mutable_bus_id(); + PROTOBUF_NODISCARD std::string* release_bus_id(); + void set_allocated_bus_id(std::string* bus_id); + private: + const std::string& _internal_bus_id() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_bus_id(const std::string& value); + std::string* _internal_mutable_bus_id(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.GPUInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr model_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr uuid_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr bus_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class PlatformInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.PlatformInfo) */ { + public: + inline PlatformInfo() : PlatformInfo(nullptr) {} + ~PlatformInfo() override; + explicit PROTOBUF_CONSTEXPR PlatformInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + PlatformInfo(const PlatformInfo& from); + PlatformInfo(PlatformInfo&& from) noexcept + : PlatformInfo() { + *this = ::std::move(from); + } + + inline PlatformInfo& operator=(const PlatformInfo& from) { + CopyFrom(from); + return *this; + } + inline PlatformInfo& operator=(PlatformInfo&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const PlatformInfo& default_instance() { + return *internal_default_instance(); + } + static inline const PlatformInfo* internal_default_instance() { + return reinterpret_cast( + &_PlatformInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 11; + + friend void swap(PlatformInfo& a, PlatformInfo& b) { + a.Swap(&b); + } + inline void Swap(PlatformInfo* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(PlatformInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + PlatformInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const PlatformInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const PlatformInfo& from) { + PlatformInfo::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(PlatformInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.PlatformInfo"; + } + protected: + explicit PlatformInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kBitsFieldNumber = 1, + kLinkageFieldNumber = 2, + kMachineFieldNumber = 3, + kReleaseFieldNumber = 4, + kSystemFieldNumber = 5, + kVersionFieldNumber = 6, + }; + // string bits = 1; + void clear_bits(); + const std::string& bits() const; + template + void set_bits(ArgT0&& arg0, ArgT... args); + std::string* mutable_bits(); + PROTOBUF_NODISCARD std::string* release_bits(); + void set_allocated_bits(std::string* bits); + private: + const std::string& _internal_bits() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_bits(const std::string& value); + std::string* _internal_mutable_bits(); + public: + + // string linkage = 2; + void clear_linkage(); + const std::string& linkage() const; + template + void set_linkage(ArgT0&& arg0, ArgT... args); + std::string* mutable_linkage(); + PROTOBUF_NODISCARD std::string* release_linkage(); + void set_allocated_linkage(std::string* linkage); + private: + const std::string& _internal_linkage() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_linkage(const std::string& value); + std::string* _internal_mutable_linkage(); + public: + + // string machine = 3; + void clear_machine(); + const std::string& machine() const; + template + void set_machine(ArgT0&& arg0, ArgT... args); + std::string* mutable_machine(); + PROTOBUF_NODISCARD std::string* release_machine(); + void set_allocated_machine(std::string* machine); + private: + const std::string& _internal_machine() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_machine(const std::string& value); + std::string* _internal_mutable_machine(); + public: + + // string release = 4; + void clear_release(); + const std::string& release() const; + template + void set_release(ArgT0&& arg0, ArgT... args); + std::string* mutable_release(); + PROTOBUF_NODISCARD std::string* release_release(); + void set_allocated_release(std::string* release); + private: + const std::string& _internal_release() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_release(const std::string& value); + std::string* _internal_mutable_release(); + public: + + // string system = 5; + void clear_system(); + const std::string& system() const; + template + void set_system(ArgT0&& arg0, ArgT... args); + std::string* mutable_system(); + PROTOBUF_NODISCARD std::string* release_system(); + void set_allocated_system(std::string* system); + private: + const std::string& _internal_system() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_system(const std::string& value); + std::string* _internal_mutable_system(); + public: + + // string version = 6; + void clear_version(); + const std::string& version() const; + template + void set_version(ArgT0&& arg0, ArgT... args); + std::string* mutable_version(); + PROTOBUF_NODISCARD std::string* release_version(); + void set_allocated_version(std::string* version); + private: + const std::string& _internal_version() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_version(const std::string& value); + std::string* _internal_mutable_version(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.PlatformInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr bits_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr linkage_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr machine_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr release_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr system_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class AvailableDeviceInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.AvailableDeviceInfo) */ { + public: + inline AvailableDeviceInfo() : AvailableDeviceInfo(nullptr) {} + ~AvailableDeviceInfo() override; + explicit PROTOBUF_CONSTEXPR AvailableDeviceInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AvailableDeviceInfo(const AvailableDeviceInfo& from); + AvailableDeviceInfo(AvailableDeviceInfo&& from) noexcept + : AvailableDeviceInfo() { + *this = ::std::move(from); + } + + inline AvailableDeviceInfo& operator=(const AvailableDeviceInfo& from) { + CopyFrom(from); + return *this; + } + inline AvailableDeviceInfo& operator=(AvailableDeviceInfo&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AvailableDeviceInfo& default_instance() { + return *internal_default_instance(); + } + static inline const AvailableDeviceInfo* internal_default_instance() { + return reinterpret_cast( + &_AvailableDeviceInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 12; + + friend void swap(AvailableDeviceInfo& a, AvailableDeviceInfo& b) { + a.Swap(&b); + } + inline void Swap(AvailableDeviceInfo* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AvailableDeviceInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AvailableDeviceInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AvailableDeviceInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AvailableDeviceInfo& from) { + AvailableDeviceInfo::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AvailableDeviceInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.AvailableDeviceInfo"; + } + protected: + explicit AvailableDeviceInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kTypeFieldNumber = 2, + kPhysicalDescriptionFieldNumber = 4, + kMemoryLimitFieldNumber = 3, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string type = 2; + void clear_type(); + const std::string& type() const; + template + void set_type(ArgT0&& arg0, ArgT... args); + std::string* mutable_type(); + PROTOBUF_NODISCARD std::string* release_type(); + void set_allocated_type(std::string* type); + private: + const std::string& _internal_type() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_type(const std::string& value); + std::string* _internal_mutable_type(); + public: + + // string physical_description = 4; + void clear_physical_description(); + const std::string& physical_description() const; + template + void set_physical_description(ArgT0&& arg0, ArgT... args); + std::string* mutable_physical_description(); + PROTOBUF_NODISCARD std::string* release_physical_description(); + void set_allocated_physical_description(std::string* physical_description); + private: + const std::string& _internal_physical_description() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_physical_description(const std::string& value); + std::string* _internal_mutable_physical_description(); + public: + + // int64 memory_limit = 3; + void clear_memory_limit(); + int64_t memory_limit() const; + void set_memory_limit(int64_t value); + private: + int64_t _internal_memory_limit() const; + void _internal_set_memory_limit(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.AvailableDeviceInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr physical_description_; + int64_t memory_limit_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class MachineConfiguration final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.MachineConfiguration) */ { + public: + inline MachineConfiguration() : MachineConfiguration(nullptr) {} + ~MachineConfiguration() override; + explicit PROTOBUF_CONSTEXPR MachineConfiguration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MachineConfiguration(const MachineConfiguration& from); + MachineConfiguration(MachineConfiguration&& from) noexcept + : MachineConfiguration() { + *this = ::std::move(from); + } + + inline MachineConfiguration& operator=(const MachineConfiguration& from) { + CopyFrom(from); + return *this; + } + inline MachineConfiguration& operator=(MachineConfiguration&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const MachineConfiguration& default_instance() { + return *internal_default_instance(); + } + static inline const MachineConfiguration* internal_default_instance() { + return reinterpret_cast( + &_MachineConfiguration_default_instance_); + } + static constexpr int kIndexInFileMessages = + 13; + + friend void swap(MachineConfiguration& a, MachineConfiguration& b) { + a.Swap(&b); + } + inline void Swap(MachineConfiguration* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(MachineConfiguration* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MachineConfiguration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MachineConfiguration& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MachineConfiguration& from) { + MachineConfiguration::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(MachineConfiguration* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.MachineConfiguration"; + } + protected: + explicit MachineConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kDeviceInfoFieldNumber = 4, + kAvailableDeviceInfoFieldNumber = 5, + kHostnameFieldNumber = 1, + kSerialIdentifierFieldNumber = 7, + kPlatformInfoFieldNumber = 2, + kCpuInfoFieldNumber = 3, + kMemoryInfoFieldNumber = 6, + }; + // repeated .google.protobuf.Any device_info = 4; + int device_info_size() const; + private: + int _internal_device_info_size() const; + public: + void clear_device_info(); + ::PROTOBUF_NAMESPACE_ID::Any* mutable_device_info(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Any >* + mutable_device_info(); + private: + const ::PROTOBUF_NAMESPACE_ID::Any& _internal_device_info(int index) const; + ::PROTOBUF_NAMESPACE_ID::Any* _internal_add_device_info(); + public: + const ::PROTOBUF_NAMESPACE_ID::Any& device_info(int index) const; + ::PROTOBUF_NAMESPACE_ID::Any* add_device_info(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Any >& + device_info() const; + + // repeated .tensorflow.AvailableDeviceInfo available_device_info = 5; + int available_device_info_size() const; + private: + int _internal_available_device_info_size() const; + public: + void clear_available_device_info(); + ::tensorflow::AvailableDeviceInfo* mutable_available_device_info(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::AvailableDeviceInfo >* + mutable_available_device_info(); + private: + const ::tensorflow::AvailableDeviceInfo& _internal_available_device_info(int index) const; + ::tensorflow::AvailableDeviceInfo* _internal_add_available_device_info(); + public: + const ::tensorflow::AvailableDeviceInfo& available_device_info(int index) const; + ::tensorflow::AvailableDeviceInfo* add_available_device_info(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::AvailableDeviceInfo >& + available_device_info() const; + + // string hostname = 1; + void clear_hostname(); + const std::string& hostname() const; + template + void set_hostname(ArgT0&& arg0, ArgT... args); + std::string* mutable_hostname(); + PROTOBUF_NODISCARD std::string* release_hostname(); + void set_allocated_hostname(std::string* hostname); + private: + const std::string& _internal_hostname() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_hostname(const std::string& value); + std::string* _internal_mutable_hostname(); + public: + + // string serial_identifier = 7; + void clear_serial_identifier(); + const std::string& serial_identifier() const; + template + void set_serial_identifier(ArgT0&& arg0, ArgT... args); + std::string* mutable_serial_identifier(); + PROTOBUF_NODISCARD std::string* release_serial_identifier(); + void set_allocated_serial_identifier(std::string* serial_identifier); + private: + const std::string& _internal_serial_identifier() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_serial_identifier(const std::string& value); + std::string* _internal_mutable_serial_identifier(); + public: + + // .tensorflow.PlatformInfo platform_info = 2; + bool has_platform_info() const; + private: + bool _internal_has_platform_info() const; + public: + void clear_platform_info(); + const ::tensorflow::PlatformInfo& platform_info() const; + PROTOBUF_NODISCARD ::tensorflow::PlatformInfo* release_platform_info(); + ::tensorflow::PlatformInfo* mutable_platform_info(); + void set_allocated_platform_info(::tensorflow::PlatformInfo* platform_info); + private: + const ::tensorflow::PlatformInfo& _internal_platform_info() const; + ::tensorflow::PlatformInfo* _internal_mutable_platform_info(); + public: + void unsafe_arena_set_allocated_platform_info( + ::tensorflow::PlatformInfo* platform_info); + ::tensorflow::PlatformInfo* unsafe_arena_release_platform_info(); + + // .tensorflow.CPUInfo cpu_info = 3; + bool has_cpu_info() const; + private: + bool _internal_has_cpu_info() const; + public: + void clear_cpu_info(); + const ::tensorflow::CPUInfo& cpu_info() const; + PROTOBUF_NODISCARD ::tensorflow::CPUInfo* release_cpu_info(); + ::tensorflow::CPUInfo* mutable_cpu_info(); + void set_allocated_cpu_info(::tensorflow::CPUInfo* cpu_info); + private: + const ::tensorflow::CPUInfo& _internal_cpu_info() const; + ::tensorflow::CPUInfo* _internal_mutable_cpu_info(); + public: + void unsafe_arena_set_allocated_cpu_info( + ::tensorflow::CPUInfo* cpu_info); + ::tensorflow::CPUInfo* unsafe_arena_release_cpu_info(); + + // .tensorflow.MemoryInfo memory_info = 6; + bool has_memory_info() const; + private: + bool _internal_has_memory_info() const; + public: + void clear_memory_info(); + const ::tensorflow::MemoryInfo& memory_info() const; + PROTOBUF_NODISCARD ::tensorflow::MemoryInfo* release_memory_info(); + ::tensorflow::MemoryInfo* mutable_memory_info(); + void set_allocated_memory_info(::tensorflow::MemoryInfo* memory_info); + private: + const ::tensorflow::MemoryInfo& _internal_memory_info() const; + ::tensorflow::MemoryInfo* _internal_mutable_memory_info(); + public: + void unsafe_arena_set_allocated_memory_info( + ::tensorflow::MemoryInfo* memory_info); + ::tensorflow::MemoryInfo* unsafe_arena_release_memory_info(); + + // @@protoc_insertion_point(class_scope:tensorflow.MachineConfiguration) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Any > device_info_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::AvailableDeviceInfo > available_device_info_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hostname_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr serial_identifier_; + ::tensorflow::PlatformInfo* platform_info_; + ::tensorflow::CPUInfo* cpu_info_; + ::tensorflow::MemoryInfo* memory_info_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class RunConfiguration_EnvVarsEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + RunConfiguration_EnvVarsEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR RunConfiguration_EnvVarsEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit RunConfiguration_EnvVarsEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const RunConfiguration_EnvVarsEntry_DoNotUse& other); + static const RunConfiguration_EnvVarsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_RunConfiguration_EnvVarsEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.RunConfiguration.EnvVarsEntry.key"); + } + static bool ValidateValue(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.RunConfiguration.EnvVarsEntry.value"); + } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; + +// ------------------------------------------------------------------- + +class RunConfiguration final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.RunConfiguration) */ { + public: + inline RunConfiguration() : RunConfiguration(nullptr) {} + ~RunConfiguration() override; + explicit PROTOBUF_CONSTEXPR RunConfiguration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + RunConfiguration(const RunConfiguration& from); + RunConfiguration(RunConfiguration&& from) noexcept + : RunConfiguration() { + *this = ::std::move(from); + } + + inline RunConfiguration& operator=(const RunConfiguration& from) { + CopyFrom(from); + return *this; + } + inline RunConfiguration& operator=(RunConfiguration&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const RunConfiguration& default_instance() { + return *internal_default_instance(); + } + static inline const RunConfiguration* internal_default_instance() { + return reinterpret_cast( + &_RunConfiguration_default_instance_); + } + static constexpr int kIndexInFileMessages = + 15; + + friend void swap(RunConfiguration& a, RunConfiguration& b) { + a.Swap(&b); + } + inline void Swap(RunConfiguration* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(RunConfiguration* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + RunConfiguration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const RunConfiguration& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const RunConfiguration& from) { + RunConfiguration::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(RunConfiguration* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.RunConfiguration"; + } + protected: + explicit RunConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kArgumentFieldNumber = 1, + kEnvVarsFieldNumber = 2, + }; + // repeated string argument = 1; + int argument_size() const; + private: + int _internal_argument_size() const; + public: + void clear_argument(); + const std::string& argument(int index) const; + std::string* mutable_argument(int index); + void set_argument(int index, const std::string& value); + void set_argument(int index, std::string&& value); + void set_argument(int index, const char* value); + void set_argument(int index, const char* value, size_t size); + std::string* add_argument(); + void add_argument(const std::string& value); + void add_argument(std::string&& value); + void add_argument(const char* value); + void add_argument(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& argument() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_argument(); + private: + const std::string& _internal_argument(int index) const; + std::string* _internal_add_argument(); + public: + + // map env_vars = 2; + int env_vars_size() const; + private: + int _internal_env_vars_size() const; + public: + void clear_env_vars(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& + _internal_env_vars() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* + _internal_mutable_env_vars(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& + env_vars() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* + mutable_env_vars(); + + // @@protoc_insertion_point(class_scope:tensorflow.RunConfiguration) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField argument_; + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + RunConfiguration_EnvVarsEntry_DoNotUse, + std::string, std::string, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> env_vars_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// ------------------------------------------------------------------- + +class TestResults final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.TestResults) */ { + public: + inline TestResults() : TestResults(nullptr) {} + ~TestResults() override; + explicit PROTOBUF_CONSTEXPR TestResults(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + TestResults(const TestResults& from); + TestResults(TestResults&& from) noexcept + : TestResults() { + *this = ::std::move(from); + } + + inline TestResults& operator=(const TestResults& from) { + CopyFrom(from); + return *this; + } + inline TestResults& operator=(TestResults&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const TestResults& default_instance() { + return *internal_default_instance(); + } + static inline const TestResults* internal_default_instance() { + return reinterpret_cast( + &_TestResults_default_instance_); + } + static constexpr int kIndexInFileMessages = + 16; + + friend void swap(TestResults& a, TestResults& b) { + a.Swap(&b); + } + inline void Swap(TestResults* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(TestResults* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + TestResults* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const TestResults& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const TestResults& from) { + TestResults::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(TestResults* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.TestResults"; + } + protected: + explicit TestResults(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + typedef TestResults_BenchmarkType BenchmarkType; + static constexpr BenchmarkType UNKNOWN = + TestResults_BenchmarkType_UNKNOWN; + static constexpr BenchmarkType CPP_MICROBENCHMARK = + TestResults_BenchmarkType_CPP_MICROBENCHMARK; + static constexpr BenchmarkType PYTHON_BENCHMARK = + TestResults_BenchmarkType_PYTHON_BENCHMARK; + static constexpr BenchmarkType ANDROID_BENCHMARK = + TestResults_BenchmarkType_ANDROID_BENCHMARK; + static constexpr BenchmarkType EDGE_BENCHMARK = + TestResults_BenchmarkType_EDGE_BENCHMARK; + static constexpr BenchmarkType IOS_BENCHMARK = + TestResults_BenchmarkType_IOS_BENCHMARK; + static inline bool BenchmarkType_IsValid(int value) { + return TestResults_BenchmarkType_IsValid(value); + } + static constexpr BenchmarkType BenchmarkType_MIN = + TestResults_BenchmarkType_BenchmarkType_MIN; + static constexpr BenchmarkType BenchmarkType_MAX = + TestResults_BenchmarkType_BenchmarkType_MAX; + static constexpr int BenchmarkType_ARRAYSIZE = + TestResults_BenchmarkType_BenchmarkType_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + BenchmarkType_descriptor() { + return TestResults_BenchmarkType_descriptor(); + } + template + static inline const std::string& BenchmarkType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function BenchmarkType_Name."); + return TestResults_BenchmarkType_Name(enum_t_value); + } + static inline bool BenchmarkType_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + BenchmarkType* value) { + return TestResults_BenchmarkType_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kTargetFieldNumber = 1, + kNameFieldNumber = 9, + kRunModeFieldNumber = 11, + kTfVersionFieldNumber = 12, + kEntriesFieldNumber = 2, + kBuildConfigurationFieldNumber = 3, + kCommitIdFieldNumber = 4, + kMachineConfigurationFieldNumber = 7, + kRunConfigurationFieldNumber = 8, + kStartTimeFieldNumber = 5, + kRunTimeFieldNumber = 6, + kBenchmarkTypeFieldNumber = 10, + }; + // string target = 1; + void clear_target(); + const std::string& target() const; + template + void set_target(ArgT0&& arg0, ArgT... args); + std::string* mutable_target(); + PROTOBUF_NODISCARD std::string* release_target(); + void set_allocated_target(std::string* target); + private: + const std::string& _internal_target() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_target(const std::string& value); + std::string* _internal_mutable_target(); + public: + + // string name = 9; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string run_mode = 11; + void clear_run_mode(); + const std::string& run_mode() const; + template + void set_run_mode(ArgT0&& arg0, ArgT... args); + std::string* mutable_run_mode(); + PROTOBUF_NODISCARD std::string* release_run_mode(); + void set_allocated_run_mode(std::string* run_mode); + private: + const std::string& _internal_run_mode() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_run_mode(const std::string& value); + std::string* _internal_mutable_run_mode(); + public: + + // string tf_version = 12; + void clear_tf_version(); + const std::string& tf_version() const; + template + void set_tf_version(ArgT0&& arg0, ArgT... args); + std::string* mutable_tf_version(); + PROTOBUF_NODISCARD std::string* release_tf_version(); + void set_allocated_tf_version(std::string* tf_version); + private: + const std::string& _internal_tf_version() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_tf_version(const std::string& value); + std::string* _internal_mutable_tf_version(); + public: + + // .tensorflow.BenchmarkEntries entries = 2; + bool has_entries() const; + private: + bool _internal_has_entries() const; + public: + void clear_entries(); + const ::tensorflow::BenchmarkEntries& entries() const; + PROTOBUF_NODISCARD ::tensorflow::BenchmarkEntries* release_entries(); + ::tensorflow::BenchmarkEntries* mutable_entries(); + void set_allocated_entries(::tensorflow::BenchmarkEntries* entries); + private: + const ::tensorflow::BenchmarkEntries& _internal_entries() const; + ::tensorflow::BenchmarkEntries* _internal_mutable_entries(); + public: + void unsafe_arena_set_allocated_entries( + ::tensorflow::BenchmarkEntries* entries); + ::tensorflow::BenchmarkEntries* unsafe_arena_release_entries(); + + // .tensorflow.BuildConfiguration build_configuration = 3; + bool has_build_configuration() const; + private: + bool _internal_has_build_configuration() const; + public: + void clear_build_configuration(); + const ::tensorflow::BuildConfiguration& build_configuration() const; + PROTOBUF_NODISCARD ::tensorflow::BuildConfiguration* release_build_configuration(); + ::tensorflow::BuildConfiguration* mutable_build_configuration(); + void set_allocated_build_configuration(::tensorflow::BuildConfiguration* build_configuration); + private: + const ::tensorflow::BuildConfiguration& _internal_build_configuration() const; + ::tensorflow::BuildConfiguration* _internal_mutable_build_configuration(); + public: + void unsafe_arena_set_allocated_build_configuration( + ::tensorflow::BuildConfiguration* build_configuration); + ::tensorflow::BuildConfiguration* unsafe_arena_release_build_configuration(); + + // .tensorflow.CommitId commit_id = 4; + bool has_commit_id() const; + private: + bool _internal_has_commit_id() const; + public: + void clear_commit_id(); + const ::tensorflow::CommitId& commit_id() const; + PROTOBUF_NODISCARD ::tensorflow::CommitId* release_commit_id(); + ::tensorflow::CommitId* mutable_commit_id(); + void set_allocated_commit_id(::tensorflow::CommitId* commit_id); + private: + const ::tensorflow::CommitId& _internal_commit_id() const; + ::tensorflow::CommitId* _internal_mutable_commit_id(); + public: + void unsafe_arena_set_allocated_commit_id( + ::tensorflow::CommitId* commit_id); + ::tensorflow::CommitId* unsafe_arena_release_commit_id(); + + // .tensorflow.MachineConfiguration machine_configuration = 7; + bool has_machine_configuration() const; + private: + bool _internal_has_machine_configuration() const; + public: + void clear_machine_configuration(); + const ::tensorflow::MachineConfiguration& machine_configuration() const; + PROTOBUF_NODISCARD ::tensorflow::MachineConfiguration* release_machine_configuration(); + ::tensorflow::MachineConfiguration* mutable_machine_configuration(); + void set_allocated_machine_configuration(::tensorflow::MachineConfiguration* machine_configuration); + private: + const ::tensorflow::MachineConfiguration& _internal_machine_configuration() const; + ::tensorflow::MachineConfiguration* _internal_mutable_machine_configuration(); + public: + void unsafe_arena_set_allocated_machine_configuration( + ::tensorflow::MachineConfiguration* machine_configuration); + ::tensorflow::MachineConfiguration* unsafe_arena_release_machine_configuration(); + + // .tensorflow.RunConfiguration run_configuration = 8; + bool has_run_configuration() const; + private: + bool _internal_has_run_configuration() const; + public: + void clear_run_configuration(); + const ::tensorflow::RunConfiguration& run_configuration() const; + PROTOBUF_NODISCARD ::tensorflow::RunConfiguration* release_run_configuration(); + ::tensorflow::RunConfiguration* mutable_run_configuration(); + void set_allocated_run_configuration(::tensorflow::RunConfiguration* run_configuration); + private: + const ::tensorflow::RunConfiguration& _internal_run_configuration() const; + ::tensorflow::RunConfiguration* _internal_mutable_run_configuration(); + public: + void unsafe_arena_set_allocated_run_configuration( + ::tensorflow::RunConfiguration* run_configuration); + ::tensorflow::RunConfiguration* unsafe_arena_release_run_configuration(); + + // int64 start_time = 5; + void clear_start_time(); + int64_t start_time() const; + void set_start_time(int64_t value); + private: + int64_t _internal_start_time() const; + void _internal_set_start_time(int64_t value); + public: + + // double run_time = 6; + void clear_run_time(); + double run_time() const; + void set_run_time(double value); + private: + double _internal_run_time() const; + void _internal_set_run_time(double value); + public: + + // .tensorflow.TestResults.BenchmarkType benchmark_type = 10; + void clear_benchmark_type(); + ::tensorflow::TestResults_BenchmarkType benchmark_type() const; + void set_benchmark_type(::tensorflow::TestResults_BenchmarkType value); + private: + ::tensorflow::TestResults_BenchmarkType _internal_benchmark_type() const; + void _internal_set_benchmark_type(::tensorflow::TestResults_BenchmarkType value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.TestResults) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr target_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr run_mode_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr tf_version_; + ::tensorflow::BenchmarkEntries* entries_; + ::tensorflow::BuildConfiguration* build_configuration_; + ::tensorflow::CommitId* commit_id_; + ::tensorflow::MachineConfiguration* machine_configuration_; + ::tensorflow::RunConfiguration* run_configuration_; + int64_t start_time_; + double run_time_; + int benchmark_type_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tsl_2fprotobuf_2ftest_5flog_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// EntryValue + +// double double_value = 1; +inline bool EntryValue::_internal_has_double_value() const { + return kind_case() == kDoubleValue; +} +inline bool EntryValue::has_double_value() const { + return _internal_has_double_value(); +} +inline void EntryValue::set_has_double_value() { + _impl_._oneof_case_[0] = kDoubleValue; +} +inline void EntryValue::clear_double_value() { + if (_internal_has_double_value()) { + _impl_.kind_.double_value_ = 0; + clear_has_kind(); + } +} +inline double EntryValue::_internal_double_value() const { + if (_internal_has_double_value()) { + return _impl_.kind_.double_value_; + } + return 0; +} +inline void EntryValue::_internal_set_double_value(double value) { + if (!_internal_has_double_value()) { + clear_kind(); + set_has_double_value(); + } + _impl_.kind_.double_value_ = value; +} +inline double EntryValue::double_value() const { + // @@protoc_insertion_point(field_get:tensorflow.EntryValue.double_value) + return _internal_double_value(); +} +inline void EntryValue::set_double_value(double value) { + _internal_set_double_value(value); + // @@protoc_insertion_point(field_set:tensorflow.EntryValue.double_value) +} + +// string string_value = 2; +inline bool EntryValue::_internal_has_string_value() const { + return kind_case() == kStringValue; +} +inline bool EntryValue::has_string_value() const { + return _internal_has_string_value(); +} +inline void EntryValue::set_has_string_value() { + _impl_._oneof_case_[0] = kStringValue; +} +inline void EntryValue::clear_string_value() { + if (_internal_has_string_value()) { + _impl_.kind_.string_value_.Destroy(); + clear_has_kind(); + } +} +inline const std::string& EntryValue::string_value() const { + // @@protoc_insertion_point(field_get:tensorflow.EntryValue.string_value) + return _internal_string_value(); +} +template +inline void EntryValue::set_string_value(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + _impl_.kind_.string_value_.InitDefault(); + } + _impl_.kind_.string_value_.Set( static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.EntryValue.string_value) +} +inline std::string* EntryValue::mutable_string_value() { + std::string* _s = _internal_mutable_string_value(); + // @@protoc_insertion_point(field_mutable:tensorflow.EntryValue.string_value) + return _s; +} +inline const std::string& EntryValue::_internal_string_value() const { + if (_internal_has_string_value()) { + return _impl_.kind_.string_value_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void EntryValue::_internal_set_string_value(const std::string& value) { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + _impl_.kind_.string_value_.InitDefault(); + } + _impl_.kind_.string_value_.Set(value, GetArenaForAllocation()); +} +inline std::string* EntryValue::_internal_mutable_string_value() { + if (!_internal_has_string_value()) { + clear_kind(); + set_has_string_value(); + _impl_.kind_.string_value_.InitDefault(); + } + return _impl_.kind_.string_value_.Mutable( GetArenaForAllocation()); +} +inline std::string* EntryValue::release_string_value() { + // @@protoc_insertion_point(field_release:tensorflow.EntryValue.string_value) + if (_internal_has_string_value()) { + clear_has_kind(); + return _impl_.kind_.string_value_.Release(); + } else { + return nullptr; + } +} +inline void EntryValue::set_allocated_string_value(std::string* string_value) { + if (has_kind()) { + clear_kind(); + } + if (string_value != nullptr) { + set_has_string_value(); + _impl_.kind_.string_value_.InitAllocated(string_value, GetArenaForAllocation()); + } + // @@protoc_insertion_point(field_set_allocated:tensorflow.EntryValue.string_value) +} + +inline bool EntryValue::has_kind() const { + return kind_case() != KIND_NOT_SET; +} +inline void EntryValue::clear_has_kind() { + _impl_._oneof_case_[0] = KIND_NOT_SET; +} +inline EntryValue::KindCase EntryValue::kind_case() const { + return EntryValue::KindCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// MetricEntry + +// string name = 1; +inline void MetricEntry::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& MetricEntry::name() const { + // @@protoc_insertion_point(field_get:tensorflow.MetricEntry.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void MetricEntry::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.MetricEntry.name) +} +inline std::string* MetricEntry::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.MetricEntry.name) + return _s; +} +inline const std::string& MetricEntry::_internal_name() const { + return _impl_.name_.Get(); +} +inline void MetricEntry::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* MetricEntry::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* MetricEntry::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.MetricEntry.name) + return _impl_.name_.Release(); +} +inline void MetricEntry::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.MetricEntry.name) +} + +// double value = 2; +inline void MetricEntry::clear_value() { + _impl_.value_ = 0; +} +inline double MetricEntry::_internal_value() const { + return _impl_.value_; +} +inline double MetricEntry::value() const { + // @@protoc_insertion_point(field_get:tensorflow.MetricEntry.value) + return _internal_value(); +} +inline void MetricEntry::_internal_set_value(double value) { + + _impl_.value_ = value; +} +inline void MetricEntry::set_value(double value) { + _internal_set_value(value); + // @@protoc_insertion_point(field_set:tensorflow.MetricEntry.value) +} + +// .google.protobuf.DoubleValue min_value = 3; +inline bool MetricEntry::_internal_has_min_value() const { + return this != internal_default_instance() && _impl_.min_value_ != nullptr; +} +inline bool MetricEntry::has_min_value() const { + return _internal_has_min_value(); +} +inline const ::PROTOBUF_NAMESPACE_ID::DoubleValue& MetricEntry::_internal_min_value() const { + const ::PROTOBUF_NAMESPACE_ID::DoubleValue* p = _impl_.min_value_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_DoubleValue_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::DoubleValue& MetricEntry::min_value() const { + // @@protoc_insertion_point(field_get:tensorflow.MetricEntry.min_value) + return _internal_min_value(); +} +inline void MetricEntry::unsafe_arena_set_allocated_min_value( + ::PROTOBUF_NAMESPACE_ID::DoubleValue* min_value) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.min_value_); + } + _impl_.min_value_ = min_value; + if (min_value) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetricEntry.min_value) +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::release_min_value() { + + ::PROTOBUF_NAMESPACE_ID::DoubleValue* temp = _impl_.min_value_; + _impl_.min_value_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::unsafe_arena_release_min_value() { + // @@protoc_insertion_point(field_release:tensorflow.MetricEntry.min_value) + + ::PROTOBUF_NAMESPACE_ID::DoubleValue* temp = _impl_.min_value_; + _impl_.min_value_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::_internal_mutable_min_value() { + + if (_impl_.min_value_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::DoubleValue>(GetArenaForAllocation()); + _impl_.min_value_ = p; + } + return _impl_.min_value_; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::mutable_min_value() { + ::PROTOBUF_NAMESPACE_ID::DoubleValue* _msg = _internal_mutable_min_value(); + // @@protoc_insertion_point(field_mutable:tensorflow.MetricEntry.min_value) + return _msg; +} +inline void MetricEntry::set_allocated_min_value(::PROTOBUF_NAMESPACE_ID::DoubleValue* min_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.min_value_); + } + if (min_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(min_value)); + if (message_arena != submessage_arena) { + min_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, min_value, submessage_arena); + } + + } else { + + } + _impl_.min_value_ = min_value; + // @@protoc_insertion_point(field_set_allocated:tensorflow.MetricEntry.min_value) +} + +// .google.protobuf.DoubleValue max_value = 4; +inline bool MetricEntry::_internal_has_max_value() const { + return this != internal_default_instance() && _impl_.max_value_ != nullptr; +} +inline bool MetricEntry::has_max_value() const { + return _internal_has_max_value(); +} +inline const ::PROTOBUF_NAMESPACE_ID::DoubleValue& MetricEntry::_internal_max_value() const { + const ::PROTOBUF_NAMESPACE_ID::DoubleValue* p = _impl_.max_value_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_DoubleValue_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::DoubleValue& MetricEntry::max_value() const { + // @@protoc_insertion_point(field_get:tensorflow.MetricEntry.max_value) + return _internal_max_value(); +} +inline void MetricEntry::unsafe_arena_set_allocated_max_value( + ::PROTOBUF_NAMESPACE_ID::DoubleValue* max_value) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.max_value_); + } + _impl_.max_value_ = max_value; + if (max_value) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetricEntry.max_value) +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::release_max_value() { + + ::PROTOBUF_NAMESPACE_ID::DoubleValue* temp = _impl_.max_value_; + _impl_.max_value_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::unsafe_arena_release_max_value() { + // @@protoc_insertion_point(field_release:tensorflow.MetricEntry.max_value) + + ::PROTOBUF_NAMESPACE_ID::DoubleValue* temp = _impl_.max_value_; + _impl_.max_value_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::_internal_mutable_max_value() { + + if (_impl_.max_value_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::DoubleValue>(GetArenaForAllocation()); + _impl_.max_value_ = p; + } + return _impl_.max_value_; +} +inline ::PROTOBUF_NAMESPACE_ID::DoubleValue* MetricEntry::mutable_max_value() { + ::PROTOBUF_NAMESPACE_ID::DoubleValue* _msg = _internal_mutable_max_value(); + // @@protoc_insertion_point(field_mutable:tensorflow.MetricEntry.max_value) + return _msg; +} +inline void MetricEntry::set_allocated_max_value(::PROTOBUF_NAMESPACE_ID::DoubleValue* max_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.max_value_); + } + if (max_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(max_value)); + if (message_arena != submessage_arena) { + max_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, max_value, submessage_arena); + } + + } else { + + } + _impl_.max_value_ = max_value; + // @@protoc_insertion_point(field_set_allocated:tensorflow.MetricEntry.max_value) +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// BenchmarkEntry + +// string name = 1; +inline void BenchmarkEntry::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& BenchmarkEntry::name() const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void BenchmarkEntry::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.BenchmarkEntry.name) +} +inline std::string* BenchmarkEntry::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.BenchmarkEntry.name) + return _s; +} +inline const std::string& BenchmarkEntry::_internal_name() const { + return _impl_.name_.Get(); +} +inline void BenchmarkEntry::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* BenchmarkEntry::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* BenchmarkEntry::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.BenchmarkEntry.name) + return _impl_.name_.Release(); +} +inline void BenchmarkEntry::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.BenchmarkEntry.name) +} + +// int64 iters = 2; +inline void BenchmarkEntry::clear_iters() { + _impl_.iters_ = int64_t{0}; +} +inline int64_t BenchmarkEntry::_internal_iters() const { + return _impl_.iters_; +} +inline int64_t BenchmarkEntry::iters() const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.iters) + return _internal_iters(); +} +inline void BenchmarkEntry::_internal_set_iters(int64_t value) { + + _impl_.iters_ = value; +} +inline void BenchmarkEntry::set_iters(int64_t value) { + _internal_set_iters(value); + // @@protoc_insertion_point(field_set:tensorflow.BenchmarkEntry.iters) +} + +// double cpu_time = 3; +inline void BenchmarkEntry::clear_cpu_time() { + _impl_.cpu_time_ = 0; +} +inline double BenchmarkEntry::_internal_cpu_time() const { + return _impl_.cpu_time_; +} +inline double BenchmarkEntry::cpu_time() const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.cpu_time) + return _internal_cpu_time(); +} +inline void BenchmarkEntry::_internal_set_cpu_time(double value) { + + _impl_.cpu_time_ = value; +} +inline void BenchmarkEntry::set_cpu_time(double value) { + _internal_set_cpu_time(value); + // @@protoc_insertion_point(field_set:tensorflow.BenchmarkEntry.cpu_time) +} + +// double wall_time = 4; +inline void BenchmarkEntry::clear_wall_time() { + _impl_.wall_time_ = 0; +} +inline double BenchmarkEntry::_internal_wall_time() const { + return _impl_.wall_time_; +} +inline double BenchmarkEntry::wall_time() const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.wall_time) + return _internal_wall_time(); +} +inline void BenchmarkEntry::_internal_set_wall_time(double value) { + + _impl_.wall_time_ = value; +} +inline void BenchmarkEntry::set_wall_time(double value) { + _internal_set_wall_time(value); + // @@protoc_insertion_point(field_set:tensorflow.BenchmarkEntry.wall_time) +} + +// double throughput = 5; +inline void BenchmarkEntry::clear_throughput() { + _impl_.throughput_ = 0; +} +inline double BenchmarkEntry::_internal_throughput() const { + return _impl_.throughput_; +} +inline double BenchmarkEntry::throughput() const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.throughput) + return _internal_throughput(); +} +inline void BenchmarkEntry::_internal_set_throughput(double value) { + + _impl_.throughput_ = value; +} +inline void BenchmarkEntry::set_throughput(double value) { + _internal_set_throughput(value); + // @@protoc_insertion_point(field_set:tensorflow.BenchmarkEntry.throughput) +} + +// map extras = 6; +inline int BenchmarkEntry::_internal_extras_size() const { + return _impl_.extras_.size(); +} +inline int BenchmarkEntry::extras_size() const { + return _internal_extras_size(); +} +inline void BenchmarkEntry::clear_extras() { + _impl_.extras_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >& +BenchmarkEntry::_internal_extras() const { + return _impl_.extras_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >& +BenchmarkEntry::extras() const { + // @@protoc_insertion_point(field_map:tensorflow.BenchmarkEntry.extras) + return _internal_extras(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >* +BenchmarkEntry::_internal_mutable_extras() { + return _impl_.extras_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::EntryValue >* +BenchmarkEntry::mutable_extras() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.BenchmarkEntry.extras) + return _internal_mutable_extras(); +} + +// repeated .tensorflow.MetricEntry metrics = 7; +inline int BenchmarkEntry::_internal_metrics_size() const { + return _impl_.metrics_.size(); +} +inline int BenchmarkEntry::metrics_size() const { + return _internal_metrics_size(); +} +inline void BenchmarkEntry::clear_metrics() { + _impl_.metrics_.Clear(); +} +inline ::tensorflow::MetricEntry* BenchmarkEntry::mutable_metrics(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.BenchmarkEntry.metrics) + return _impl_.metrics_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::MetricEntry >* +BenchmarkEntry::mutable_metrics() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.BenchmarkEntry.metrics) + return &_impl_.metrics_; +} +inline const ::tensorflow::MetricEntry& BenchmarkEntry::_internal_metrics(int index) const { + return _impl_.metrics_.Get(index); +} +inline const ::tensorflow::MetricEntry& BenchmarkEntry::metrics(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntry.metrics) + return _internal_metrics(index); +} +inline ::tensorflow::MetricEntry* BenchmarkEntry::_internal_add_metrics() { + return _impl_.metrics_.Add(); +} +inline ::tensorflow::MetricEntry* BenchmarkEntry::add_metrics() { + ::tensorflow::MetricEntry* _add = _internal_add_metrics(); + // @@protoc_insertion_point(field_add:tensorflow.BenchmarkEntry.metrics) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::MetricEntry >& +BenchmarkEntry::metrics() const { + // @@protoc_insertion_point(field_list:tensorflow.BenchmarkEntry.metrics) + return _impl_.metrics_; +} + +// ------------------------------------------------------------------- + +// BenchmarkEntries + +// repeated .tensorflow.BenchmarkEntry entry = 1; +inline int BenchmarkEntries::_internal_entry_size() const { + return _impl_.entry_.size(); +} +inline int BenchmarkEntries::entry_size() const { + return _internal_entry_size(); +} +inline void BenchmarkEntries::clear_entry() { + _impl_.entry_.Clear(); +} +inline ::tensorflow::BenchmarkEntry* BenchmarkEntries::mutable_entry(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.BenchmarkEntries.entry) + return _impl_.entry_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::BenchmarkEntry >* +BenchmarkEntries::mutable_entry() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.BenchmarkEntries.entry) + return &_impl_.entry_; +} +inline const ::tensorflow::BenchmarkEntry& BenchmarkEntries::_internal_entry(int index) const { + return _impl_.entry_.Get(index); +} +inline const ::tensorflow::BenchmarkEntry& BenchmarkEntries::entry(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.BenchmarkEntries.entry) + return _internal_entry(index); +} +inline ::tensorflow::BenchmarkEntry* BenchmarkEntries::_internal_add_entry() { + return _impl_.entry_.Add(); +} +inline ::tensorflow::BenchmarkEntry* BenchmarkEntries::add_entry() { + ::tensorflow::BenchmarkEntry* _add = _internal_add_entry(); + // @@protoc_insertion_point(field_add:tensorflow.BenchmarkEntries.entry) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::BenchmarkEntry >& +BenchmarkEntries::entry() const { + // @@protoc_insertion_point(field_list:tensorflow.BenchmarkEntries.entry) + return _impl_.entry_; +} + +// ------------------------------------------------------------------- + +// BuildConfiguration + +// string mode = 1; +inline void BuildConfiguration::clear_mode() { + _impl_.mode_.ClearToEmpty(); +} +inline const std::string& BuildConfiguration::mode() const { + // @@protoc_insertion_point(field_get:tensorflow.BuildConfiguration.mode) + return _internal_mode(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void BuildConfiguration::set_mode(ArgT0&& arg0, ArgT... args) { + + _impl_.mode_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.BuildConfiguration.mode) +} +inline std::string* BuildConfiguration::mutable_mode() { + std::string* _s = _internal_mutable_mode(); + // @@protoc_insertion_point(field_mutable:tensorflow.BuildConfiguration.mode) + return _s; +} +inline const std::string& BuildConfiguration::_internal_mode() const { + return _impl_.mode_.Get(); +} +inline void BuildConfiguration::_internal_set_mode(const std::string& value) { + + _impl_.mode_.Set(value, GetArenaForAllocation()); +} +inline std::string* BuildConfiguration::_internal_mutable_mode() { + + return _impl_.mode_.Mutable(GetArenaForAllocation()); +} +inline std::string* BuildConfiguration::release_mode() { + // @@protoc_insertion_point(field_release:tensorflow.BuildConfiguration.mode) + return _impl_.mode_.Release(); +} +inline void BuildConfiguration::set_allocated_mode(std::string* mode) { + if (mode != nullptr) { + + } else { + + } + _impl_.mode_.SetAllocated(mode, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.mode_.IsDefault()) { + _impl_.mode_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.BuildConfiguration.mode) +} + +// repeated string cc_flags = 2; +inline int BuildConfiguration::_internal_cc_flags_size() const { + return _impl_.cc_flags_.size(); +} +inline int BuildConfiguration::cc_flags_size() const { + return _internal_cc_flags_size(); +} +inline void BuildConfiguration::clear_cc_flags() { + _impl_.cc_flags_.Clear(); +} +inline std::string* BuildConfiguration::add_cc_flags() { + std::string* _s = _internal_add_cc_flags(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.BuildConfiguration.cc_flags) + return _s; +} +inline const std::string& BuildConfiguration::_internal_cc_flags(int index) const { + return _impl_.cc_flags_.Get(index); +} +inline const std::string& BuildConfiguration::cc_flags(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.BuildConfiguration.cc_flags) + return _internal_cc_flags(index); +} +inline std::string* BuildConfiguration::mutable_cc_flags(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.BuildConfiguration.cc_flags) + return _impl_.cc_flags_.Mutable(index); +} +inline void BuildConfiguration::set_cc_flags(int index, const std::string& value) { + _impl_.cc_flags_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::set_cc_flags(int index, std::string&& value) { + _impl_.cc_flags_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::set_cc_flags(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.cc_flags_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::set_cc_flags(int index, const char* value, size_t size) { + _impl_.cc_flags_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.BuildConfiguration.cc_flags) +} +inline std::string* BuildConfiguration::_internal_add_cc_flags() { + return _impl_.cc_flags_.Add(); +} +inline void BuildConfiguration::add_cc_flags(const std::string& value) { + _impl_.cc_flags_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::add_cc_flags(std::string&& value) { + _impl_.cc_flags_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::add_cc_flags(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.cc_flags_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.BuildConfiguration.cc_flags) +} +inline void BuildConfiguration::add_cc_flags(const char* value, size_t size) { + _impl_.cc_flags_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.BuildConfiguration.cc_flags) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +BuildConfiguration::cc_flags() const { + // @@protoc_insertion_point(field_list:tensorflow.BuildConfiguration.cc_flags) + return _impl_.cc_flags_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +BuildConfiguration::mutable_cc_flags() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.BuildConfiguration.cc_flags) + return &_impl_.cc_flags_; +} + +// repeated string opts = 3; +inline int BuildConfiguration::_internal_opts_size() const { + return _impl_.opts_.size(); +} +inline int BuildConfiguration::opts_size() const { + return _internal_opts_size(); +} +inline void BuildConfiguration::clear_opts() { + _impl_.opts_.Clear(); +} +inline std::string* BuildConfiguration::add_opts() { + std::string* _s = _internal_add_opts(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.BuildConfiguration.opts) + return _s; +} +inline const std::string& BuildConfiguration::_internal_opts(int index) const { + return _impl_.opts_.Get(index); +} +inline const std::string& BuildConfiguration::opts(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.BuildConfiguration.opts) + return _internal_opts(index); +} +inline std::string* BuildConfiguration::mutable_opts(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.BuildConfiguration.opts) + return _impl_.opts_.Mutable(index); +} +inline void BuildConfiguration::set_opts(int index, const std::string& value) { + _impl_.opts_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::set_opts(int index, std::string&& value) { + _impl_.opts_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::set_opts(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.opts_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::set_opts(int index, const char* value, size_t size) { + _impl_.opts_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.BuildConfiguration.opts) +} +inline std::string* BuildConfiguration::_internal_add_opts() { + return _impl_.opts_.Add(); +} +inline void BuildConfiguration::add_opts(const std::string& value) { + _impl_.opts_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::add_opts(std::string&& value) { + _impl_.opts_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::add_opts(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.opts_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.BuildConfiguration.opts) +} +inline void BuildConfiguration::add_opts(const char* value, size_t size) { + _impl_.opts_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.BuildConfiguration.opts) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +BuildConfiguration::opts() const { + // @@protoc_insertion_point(field_list:tensorflow.BuildConfiguration.opts) + return _impl_.opts_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +BuildConfiguration::mutable_opts() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.BuildConfiguration.opts) + return &_impl_.opts_; +} + +// ------------------------------------------------------------------- + +// CommitId + +// int64 changelist = 1; +inline bool CommitId::_internal_has_changelist() const { + return kind_case() == kChangelist; +} +inline bool CommitId::has_changelist() const { + return _internal_has_changelist(); +} +inline void CommitId::set_has_changelist() { + _impl_._oneof_case_[0] = kChangelist; +} +inline void CommitId::clear_changelist() { + if (_internal_has_changelist()) { + _impl_.kind_.changelist_ = int64_t{0}; + clear_has_kind(); + } +} +inline int64_t CommitId::_internal_changelist() const { + if (_internal_has_changelist()) { + return _impl_.kind_.changelist_; + } + return int64_t{0}; +} +inline void CommitId::_internal_set_changelist(int64_t value) { + if (!_internal_has_changelist()) { + clear_kind(); + set_has_changelist(); + } + _impl_.kind_.changelist_ = value; +} +inline int64_t CommitId::changelist() const { + // @@protoc_insertion_point(field_get:tensorflow.CommitId.changelist) + return _internal_changelist(); +} +inline void CommitId::set_changelist(int64_t value) { + _internal_set_changelist(value); + // @@protoc_insertion_point(field_set:tensorflow.CommitId.changelist) +} + +// string hash = 2; +inline bool CommitId::_internal_has_hash() const { + return kind_case() == kHash; +} +inline bool CommitId::has_hash() const { + return _internal_has_hash(); +} +inline void CommitId::set_has_hash() { + _impl_._oneof_case_[0] = kHash; +} +inline void CommitId::clear_hash() { + if (_internal_has_hash()) { + _impl_.kind_.hash_.Destroy(); + clear_has_kind(); + } +} +inline const std::string& CommitId::hash() const { + // @@protoc_insertion_point(field_get:tensorflow.CommitId.hash) + return _internal_hash(); +} +template +inline void CommitId::set_hash(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_hash()) { + clear_kind(); + set_has_hash(); + _impl_.kind_.hash_.InitDefault(); + } + _impl_.kind_.hash_.Set( static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CommitId.hash) +} +inline std::string* CommitId::mutable_hash() { + std::string* _s = _internal_mutable_hash(); + // @@protoc_insertion_point(field_mutable:tensorflow.CommitId.hash) + return _s; +} +inline const std::string& CommitId::_internal_hash() const { + if (_internal_has_hash()) { + return _impl_.kind_.hash_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void CommitId::_internal_set_hash(const std::string& value) { + if (!_internal_has_hash()) { + clear_kind(); + set_has_hash(); + _impl_.kind_.hash_.InitDefault(); + } + _impl_.kind_.hash_.Set(value, GetArenaForAllocation()); +} +inline std::string* CommitId::_internal_mutable_hash() { + if (!_internal_has_hash()) { + clear_kind(); + set_has_hash(); + _impl_.kind_.hash_.InitDefault(); + } + return _impl_.kind_.hash_.Mutable( GetArenaForAllocation()); +} +inline std::string* CommitId::release_hash() { + // @@protoc_insertion_point(field_release:tensorflow.CommitId.hash) + if (_internal_has_hash()) { + clear_has_kind(); + return _impl_.kind_.hash_.Release(); + } else { + return nullptr; + } +} +inline void CommitId::set_allocated_hash(std::string* hash) { + if (has_kind()) { + clear_kind(); + } + if (hash != nullptr) { + set_has_hash(); + _impl_.kind_.hash_.InitAllocated(hash, GetArenaForAllocation()); + } + // @@protoc_insertion_point(field_set_allocated:tensorflow.CommitId.hash) +} + +// string snapshot = 3; +inline void CommitId::clear_snapshot() { + _impl_.snapshot_.ClearToEmpty(); +} +inline const std::string& CommitId::snapshot() const { + // @@protoc_insertion_point(field_get:tensorflow.CommitId.snapshot) + return _internal_snapshot(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CommitId::set_snapshot(ArgT0&& arg0, ArgT... args) { + + _impl_.snapshot_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CommitId.snapshot) +} +inline std::string* CommitId::mutable_snapshot() { + std::string* _s = _internal_mutable_snapshot(); + // @@protoc_insertion_point(field_mutable:tensorflow.CommitId.snapshot) + return _s; +} +inline const std::string& CommitId::_internal_snapshot() const { + return _impl_.snapshot_.Get(); +} +inline void CommitId::_internal_set_snapshot(const std::string& value) { + + _impl_.snapshot_.Set(value, GetArenaForAllocation()); +} +inline std::string* CommitId::_internal_mutable_snapshot() { + + return _impl_.snapshot_.Mutable(GetArenaForAllocation()); +} +inline std::string* CommitId::release_snapshot() { + // @@protoc_insertion_point(field_release:tensorflow.CommitId.snapshot) + return _impl_.snapshot_.Release(); +} +inline void CommitId::set_allocated_snapshot(std::string* snapshot) { + if (snapshot != nullptr) { + + } else { + + } + _impl_.snapshot_.SetAllocated(snapshot, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.snapshot_.IsDefault()) { + _impl_.snapshot_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CommitId.snapshot) +} + +// int64 pending_changelist = 4; +inline void CommitId::clear_pending_changelist() { + _impl_.pending_changelist_ = int64_t{0}; +} +inline int64_t CommitId::_internal_pending_changelist() const { + return _impl_.pending_changelist_; +} +inline int64_t CommitId::pending_changelist() const { + // @@protoc_insertion_point(field_get:tensorflow.CommitId.pending_changelist) + return _internal_pending_changelist(); +} +inline void CommitId::_internal_set_pending_changelist(int64_t value) { + + _impl_.pending_changelist_ = value; +} +inline void CommitId::set_pending_changelist(int64_t value) { + _internal_set_pending_changelist(value); + // @@protoc_insertion_point(field_set:tensorflow.CommitId.pending_changelist) +} + +inline bool CommitId::has_kind() const { + return kind_case() != KIND_NOT_SET; +} +inline void CommitId::clear_has_kind() { + _impl_._oneof_case_[0] = KIND_NOT_SET; +} +inline CommitId::KindCase CommitId::kind_case() const { + return CommitId::KindCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// CPUInfo + +// int64 num_cores = 1; +inline void CPUInfo::clear_num_cores() { + _impl_.num_cores_ = int64_t{0}; +} +inline int64_t CPUInfo::_internal_num_cores() const { + return _impl_.num_cores_; +} +inline int64_t CPUInfo::num_cores() const { + // @@protoc_insertion_point(field_get:tensorflow.CPUInfo.num_cores) + return _internal_num_cores(); +} +inline void CPUInfo::_internal_set_num_cores(int64_t value) { + + _impl_.num_cores_ = value; +} +inline void CPUInfo::set_num_cores(int64_t value) { + _internal_set_num_cores(value); + // @@protoc_insertion_point(field_set:tensorflow.CPUInfo.num_cores) +} + +// int64 num_cores_allowed = 2; +inline void CPUInfo::clear_num_cores_allowed() { + _impl_.num_cores_allowed_ = int64_t{0}; +} +inline int64_t CPUInfo::_internal_num_cores_allowed() const { + return _impl_.num_cores_allowed_; +} +inline int64_t CPUInfo::num_cores_allowed() const { + // @@protoc_insertion_point(field_get:tensorflow.CPUInfo.num_cores_allowed) + return _internal_num_cores_allowed(); +} +inline void CPUInfo::_internal_set_num_cores_allowed(int64_t value) { + + _impl_.num_cores_allowed_ = value; +} +inline void CPUInfo::set_num_cores_allowed(int64_t value) { + _internal_set_num_cores_allowed(value); + // @@protoc_insertion_point(field_set:tensorflow.CPUInfo.num_cores_allowed) +} + +// double mhz_per_cpu = 3; +inline void CPUInfo::clear_mhz_per_cpu() { + _impl_.mhz_per_cpu_ = 0; +} +inline double CPUInfo::_internal_mhz_per_cpu() const { + return _impl_.mhz_per_cpu_; +} +inline double CPUInfo::mhz_per_cpu() const { + // @@protoc_insertion_point(field_get:tensorflow.CPUInfo.mhz_per_cpu) + return _internal_mhz_per_cpu(); +} +inline void CPUInfo::_internal_set_mhz_per_cpu(double value) { + + _impl_.mhz_per_cpu_ = value; +} +inline void CPUInfo::set_mhz_per_cpu(double value) { + _internal_set_mhz_per_cpu(value); + // @@protoc_insertion_point(field_set:tensorflow.CPUInfo.mhz_per_cpu) +} + +// string cpu_info = 4; +inline void CPUInfo::clear_cpu_info() { + _impl_.cpu_info_.ClearToEmpty(); +} +inline const std::string& CPUInfo::cpu_info() const { + // @@protoc_insertion_point(field_get:tensorflow.CPUInfo.cpu_info) + return _internal_cpu_info(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CPUInfo::set_cpu_info(ArgT0&& arg0, ArgT... args) { + + _impl_.cpu_info_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CPUInfo.cpu_info) +} +inline std::string* CPUInfo::mutable_cpu_info() { + std::string* _s = _internal_mutable_cpu_info(); + // @@protoc_insertion_point(field_mutable:tensorflow.CPUInfo.cpu_info) + return _s; +} +inline const std::string& CPUInfo::_internal_cpu_info() const { + return _impl_.cpu_info_.Get(); +} +inline void CPUInfo::_internal_set_cpu_info(const std::string& value) { + + _impl_.cpu_info_.Set(value, GetArenaForAllocation()); +} +inline std::string* CPUInfo::_internal_mutable_cpu_info() { + + return _impl_.cpu_info_.Mutable(GetArenaForAllocation()); +} +inline std::string* CPUInfo::release_cpu_info() { + // @@protoc_insertion_point(field_release:tensorflow.CPUInfo.cpu_info) + return _impl_.cpu_info_.Release(); +} +inline void CPUInfo::set_allocated_cpu_info(std::string* cpu_info) { + if (cpu_info != nullptr) { + + } else { + + } + _impl_.cpu_info_.SetAllocated(cpu_info, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.cpu_info_.IsDefault()) { + _impl_.cpu_info_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CPUInfo.cpu_info) +} + +// string cpu_governor = 5; +inline void CPUInfo::clear_cpu_governor() { + _impl_.cpu_governor_.ClearToEmpty(); +} +inline const std::string& CPUInfo::cpu_governor() const { + // @@protoc_insertion_point(field_get:tensorflow.CPUInfo.cpu_governor) + return _internal_cpu_governor(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CPUInfo::set_cpu_governor(ArgT0&& arg0, ArgT... args) { + + _impl_.cpu_governor_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CPUInfo.cpu_governor) +} +inline std::string* CPUInfo::mutable_cpu_governor() { + std::string* _s = _internal_mutable_cpu_governor(); + // @@protoc_insertion_point(field_mutable:tensorflow.CPUInfo.cpu_governor) + return _s; +} +inline const std::string& CPUInfo::_internal_cpu_governor() const { + return _impl_.cpu_governor_.Get(); +} +inline void CPUInfo::_internal_set_cpu_governor(const std::string& value) { + + _impl_.cpu_governor_.Set(value, GetArenaForAllocation()); +} +inline std::string* CPUInfo::_internal_mutable_cpu_governor() { + + return _impl_.cpu_governor_.Mutable(GetArenaForAllocation()); +} +inline std::string* CPUInfo::release_cpu_governor() { + // @@protoc_insertion_point(field_release:tensorflow.CPUInfo.cpu_governor) + return _impl_.cpu_governor_.Release(); +} +inline void CPUInfo::set_allocated_cpu_governor(std::string* cpu_governor) { + if (cpu_governor != nullptr) { + + } else { + + } + _impl_.cpu_governor_.SetAllocated(cpu_governor, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.cpu_governor_.IsDefault()) { + _impl_.cpu_governor_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CPUInfo.cpu_governor) +} + +// map cache_size = 6; +inline int CPUInfo::_internal_cache_size_size() const { + return _impl_.cache_size_.size(); +} +inline int CPUInfo::cache_size_size() const { + return _internal_cache_size_size(); +} +inline void CPUInfo::clear_cache_size() { + _impl_.cache_size_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& +CPUInfo::_internal_cache_size() const { + return _impl_.cache_size_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& +CPUInfo::cache_size() const { + // @@protoc_insertion_point(field_map:tensorflow.CPUInfo.cache_size) + return _internal_cache_size(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* +CPUInfo::_internal_mutable_cache_size() { + return _impl_.cache_size_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* +CPUInfo::mutable_cache_size() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.CPUInfo.cache_size) + return _internal_mutable_cache_size(); +} + +// ------------------------------------------------------------------- + +// MemoryInfo + +// int64 total = 1; +inline void MemoryInfo::clear_total() { + _impl_.total_ = int64_t{0}; +} +inline int64_t MemoryInfo::_internal_total() const { + return _impl_.total_; +} +inline int64_t MemoryInfo::total() const { + // @@protoc_insertion_point(field_get:tensorflow.MemoryInfo.total) + return _internal_total(); +} +inline void MemoryInfo::_internal_set_total(int64_t value) { + + _impl_.total_ = value; +} +inline void MemoryInfo::set_total(int64_t value) { + _internal_set_total(value); + // @@protoc_insertion_point(field_set:tensorflow.MemoryInfo.total) +} + +// int64 available = 2; +inline void MemoryInfo::clear_available() { + _impl_.available_ = int64_t{0}; +} +inline int64_t MemoryInfo::_internal_available() const { + return _impl_.available_; +} +inline int64_t MemoryInfo::available() const { + // @@protoc_insertion_point(field_get:tensorflow.MemoryInfo.available) + return _internal_available(); +} +inline void MemoryInfo::_internal_set_available(int64_t value) { + + _impl_.available_ = value; +} +inline void MemoryInfo::set_available(int64_t value) { + _internal_set_available(value); + // @@protoc_insertion_point(field_set:tensorflow.MemoryInfo.available) +} + +// ------------------------------------------------------------------- + +// GPUInfo + +// string model = 1; +inline void GPUInfo::clear_model() { + _impl_.model_.ClearToEmpty(); +} +inline const std::string& GPUInfo::model() const { + // @@protoc_insertion_point(field_get:tensorflow.GPUInfo.model) + return _internal_model(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GPUInfo::set_model(ArgT0&& arg0, ArgT... args) { + + _impl_.model_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.GPUInfo.model) +} +inline std::string* GPUInfo::mutable_model() { + std::string* _s = _internal_mutable_model(); + // @@protoc_insertion_point(field_mutable:tensorflow.GPUInfo.model) + return _s; +} +inline const std::string& GPUInfo::_internal_model() const { + return _impl_.model_.Get(); +} +inline void GPUInfo::_internal_set_model(const std::string& value) { + + _impl_.model_.Set(value, GetArenaForAllocation()); +} +inline std::string* GPUInfo::_internal_mutable_model() { + + return _impl_.model_.Mutable(GetArenaForAllocation()); +} +inline std::string* GPUInfo::release_model() { + // @@protoc_insertion_point(field_release:tensorflow.GPUInfo.model) + return _impl_.model_.Release(); +} +inline void GPUInfo::set_allocated_model(std::string* model) { + if (model != nullptr) { + + } else { + + } + _impl_.model_.SetAllocated(model, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.model_.IsDefault()) { + _impl_.model_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.GPUInfo.model) +} + +// string uuid = 2; +inline void GPUInfo::clear_uuid() { + _impl_.uuid_.ClearToEmpty(); +} +inline const std::string& GPUInfo::uuid() const { + // @@protoc_insertion_point(field_get:tensorflow.GPUInfo.uuid) + return _internal_uuid(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GPUInfo::set_uuid(ArgT0&& arg0, ArgT... args) { + + _impl_.uuid_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.GPUInfo.uuid) +} +inline std::string* GPUInfo::mutable_uuid() { + std::string* _s = _internal_mutable_uuid(); + // @@protoc_insertion_point(field_mutable:tensorflow.GPUInfo.uuid) + return _s; +} +inline const std::string& GPUInfo::_internal_uuid() const { + return _impl_.uuid_.Get(); +} +inline void GPUInfo::_internal_set_uuid(const std::string& value) { + + _impl_.uuid_.Set(value, GetArenaForAllocation()); +} +inline std::string* GPUInfo::_internal_mutable_uuid() { + + return _impl_.uuid_.Mutable(GetArenaForAllocation()); +} +inline std::string* GPUInfo::release_uuid() { + // @@protoc_insertion_point(field_release:tensorflow.GPUInfo.uuid) + return _impl_.uuid_.Release(); +} +inline void GPUInfo::set_allocated_uuid(std::string* uuid) { + if (uuid != nullptr) { + + } else { + + } + _impl_.uuid_.SetAllocated(uuid, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.uuid_.IsDefault()) { + _impl_.uuid_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.GPUInfo.uuid) +} + +// string bus_id = 3; +inline void GPUInfo::clear_bus_id() { + _impl_.bus_id_.ClearToEmpty(); +} +inline const std::string& GPUInfo::bus_id() const { + // @@protoc_insertion_point(field_get:tensorflow.GPUInfo.bus_id) + return _internal_bus_id(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GPUInfo::set_bus_id(ArgT0&& arg0, ArgT... args) { + + _impl_.bus_id_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.GPUInfo.bus_id) +} +inline std::string* GPUInfo::mutable_bus_id() { + std::string* _s = _internal_mutable_bus_id(); + // @@protoc_insertion_point(field_mutable:tensorflow.GPUInfo.bus_id) + return _s; +} +inline const std::string& GPUInfo::_internal_bus_id() const { + return _impl_.bus_id_.Get(); +} +inline void GPUInfo::_internal_set_bus_id(const std::string& value) { + + _impl_.bus_id_.Set(value, GetArenaForAllocation()); +} +inline std::string* GPUInfo::_internal_mutable_bus_id() { + + return _impl_.bus_id_.Mutable(GetArenaForAllocation()); +} +inline std::string* GPUInfo::release_bus_id() { + // @@protoc_insertion_point(field_release:tensorflow.GPUInfo.bus_id) + return _impl_.bus_id_.Release(); +} +inline void GPUInfo::set_allocated_bus_id(std::string* bus_id) { + if (bus_id != nullptr) { + + } else { + + } + _impl_.bus_id_.SetAllocated(bus_id, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.bus_id_.IsDefault()) { + _impl_.bus_id_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.GPUInfo.bus_id) +} + +// ------------------------------------------------------------------- + +// PlatformInfo + +// string bits = 1; +inline void PlatformInfo::clear_bits() { + _impl_.bits_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::bits() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.bits) + return _internal_bits(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_bits(ArgT0&& arg0, ArgT... args) { + + _impl_.bits_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.bits) +} +inline std::string* PlatformInfo::mutable_bits() { + std::string* _s = _internal_mutable_bits(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.bits) + return _s; +} +inline const std::string& PlatformInfo::_internal_bits() const { + return _impl_.bits_.Get(); +} +inline void PlatformInfo::_internal_set_bits(const std::string& value) { + + _impl_.bits_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_bits() { + + return _impl_.bits_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_bits() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.bits) + return _impl_.bits_.Release(); +} +inline void PlatformInfo::set_allocated_bits(std::string* bits) { + if (bits != nullptr) { + + } else { + + } + _impl_.bits_.SetAllocated(bits, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.bits_.IsDefault()) { + _impl_.bits_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.bits) +} + +// string linkage = 2; +inline void PlatformInfo::clear_linkage() { + _impl_.linkage_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::linkage() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.linkage) + return _internal_linkage(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_linkage(ArgT0&& arg0, ArgT... args) { + + _impl_.linkage_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.linkage) +} +inline std::string* PlatformInfo::mutable_linkage() { + std::string* _s = _internal_mutable_linkage(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.linkage) + return _s; +} +inline const std::string& PlatformInfo::_internal_linkage() const { + return _impl_.linkage_.Get(); +} +inline void PlatformInfo::_internal_set_linkage(const std::string& value) { + + _impl_.linkage_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_linkage() { + + return _impl_.linkage_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_linkage() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.linkage) + return _impl_.linkage_.Release(); +} +inline void PlatformInfo::set_allocated_linkage(std::string* linkage) { + if (linkage != nullptr) { + + } else { + + } + _impl_.linkage_.SetAllocated(linkage, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.linkage_.IsDefault()) { + _impl_.linkage_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.linkage) +} + +// string machine = 3; +inline void PlatformInfo::clear_machine() { + _impl_.machine_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::machine() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.machine) + return _internal_machine(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_machine(ArgT0&& arg0, ArgT... args) { + + _impl_.machine_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.machine) +} +inline std::string* PlatformInfo::mutable_machine() { + std::string* _s = _internal_mutable_machine(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.machine) + return _s; +} +inline const std::string& PlatformInfo::_internal_machine() const { + return _impl_.machine_.Get(); +} +inline void PlatformInfo::_internal_set_machine(const std::string& value) { + + _impl_.machine_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_machine() { + + return _impl_.machine_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_machine() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.machine) + return _impl_.machine_.Release(); +} +inline void PlatformInfo::set_allocated_machine(std::string* machine) { + if (machine != nullptr) { + + } else { + + } + _impl_.machine_.SetAllocated(machine, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.machine_.IsDefault()) { + _impl_.machine_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.machine) +} + +// string release = 4; +inline void PlatformInfo::clear_release() { + _impl_.release_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::release() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.release) + return _internal_release(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_release(ArgT0&& arg0, ArgT... args) { + + _impl_.release_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.release) +} +inline std::string* PlatformInfo::mutable_release() { + std::string* _s = _internal_mutable_release(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.release) + return _s; +} +inline const std::string& PlatformInfo::_internal_release() const { + return _impl_.release_.Get(); +} +inline void PlatformInfo::_internal_set_release(const std::string& value) { + + _impl_.release_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_release() { + + return _impl_.release_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_release() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.release) + return _impl_.release_.Release(); +} +inline void PlatformInfo::set_allocated_release(std::string* release) { + if (release != nullptr) { + + } else { + + } + _impl_.release_.SetAllocated(release, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.release_.IsDefault()) { + _impl_.release_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.release) +} + +// string system = 5; +inline void PlatformInfo::clear_system() { + _impl_.system_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::system() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.system) + return _internal_system(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_system(ArgT0&& arg0, ArgT... args) { + + _impl_.system_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.system) +} +inline std::string* PlatformInfo::mutable_system() { + std::string* _s = _internal_mutable_system(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.system) + return _s; +} +inline const std::string& PlatformInfo::_internal_system() const { + return _impl_.system_.Get(); +} +inline void PlatformInfo::_internal_set_system(const std::string& value) { + + _impl_.system_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_system() { + + return _impl_.system_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_system() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.system) + return _impl_.system_.Release(); +} +inline void PlatformInfo::set_allocated_system(std::string* system) { + if (system != nullptr) { + + } else { + + } + _impl_.system_.SetAllocated(system, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.system_.IsDefault()) { + _impl_.system_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.system) +} + +// string version = 6; +inline void PlatformInfo::clear_version() { + _impl_.version_.ClearToEmpty(); +} +inline const std::string& PlatformInfo::version() const { + // @@protoc_insertion_point(field_get:tensorflow.PlatformInfo.version) + return _internal_version(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PlatformInfo::set_version(ArgT0&& arg0, ArgT... args) { + + _impl_.version_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.PlatformInfo.version) +} +inline std::string* PlatformInfo::mutable_version() { + std::string* _s = _internal_mutable_version(); + // @@protoc_insertion_point(field_mutable:tensorflow.PlatformInfo.version) + return _s; +} +inline const std::string& PlatformInfo::_internal_version() const { + return _impl_.version_.Get(); +} +inline void PlatformInfo::_internal_set_version(const std::string& value) { + + _impl_.version_.Set(value, GetArenaForAllocation()); +} +inline std::string* PlatformInfo::_internal_mutable_version() { + + return _impl_.version_.Mutable(GetArenaForAllocation()); +} +inline std::string* PlatformInfo::release_version() { + // @@protoc_insertion_point(field_release:tensorflow.PlatformInfo.version) + return _impl_.version_.Release(); +} +inline void PlatformInfo::set_allocated_version(std::string* version) { + if (version != nullptr) { + + } else { + + } + _impl_.version_.SetAllocated(version, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.version_.IsDefault()) { + _impl_.version_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.PlatformInfo.version) +} + +// ------------------------------------------------------------------- + +// AvailableDeviceInfo + +// string name = 1; +inline void AvailableDeviceInfo::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& AvailableDeviceInfo::name() const { + // @@protoc_insertion_point(field_get:tensorflow.AvailableDeviceInfo.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AvailableDeviceInfo::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AvailableDeviceInfo.name) +} +inline std::string* AvailableDeviceInfo::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.AvailableDeviceInfo.name) + return _s; +} +inline const std::string& AvailableDeviceInfo::_internal_name() const { + return _impl_.name_.Get(); +} +inline void AvailableDeviceInfo::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.AvailableDeviceInfo.name) + return _impl_.name_.Release(); +} +inline void AvailableDeviceInfo::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.AvailableDeviceInfo.name) +} + +// string type = 2; +inline void AvailableDeviceInfo::clear_type() { + _impl_.type_.ClearToEmpty(); +} +inline const std::string& AvailableDeviceInfo::type() const { + // @@protoc_insertion_point(field_get:tensorflow.AvailableDeviceInfo.type) + return _internal_type(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AvailableDeviceInfo::set_type(ArgT0&& arg0, ArgT... args) { + + _impl_.type_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AvailableDeviceInfo.type) +} +inline std::string* AvailableDeviceInfo::mutable_type() { + std::string* _s = _internal_mutable_type(); + // @@protoc_insertion_point(field_mutable:tensorflow.AvailableDeviceInfo.type) + return _s; +} +inline const std::string& AvailableDeviceInfo::_internal_type() const { + return _impl_.type_.Get(); +} +inline void AvailableDeviceInfo::_internal_set_type(const std::string& value) { + + _impl_.type_.Set(value, GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::_internal_mutable_type() { + + return _impl_.type_.Mutable(GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::release_type() { + // @@protoc_insertion_point(field_release:tensorflow.AvailableDeviceInfo.type) + return _impl_.type_.Release(); +} +inline void AvailableDeviceInfo::set_allocated_type(std::string* type) { + if (type != nullptr) { + + } else { + + } + _impl_.type_.SetAllocated(type, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.type_.IsDefault()) { + _impl_.type_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.AvailableDeviceInfo.type) +} + +// int64 memory_limit = 3; +inline void AvailableDeviceInfo::clear_memory_limit() { + _impl_.memory_limit_ = int64_t{0}; +} +inline int64_t AvailableDeviceInfo::_internal_memory_limit() const { + return _impl_.memory_limit_; +} +inline int64_t AvailableDeviceInfo::memory_limit() const { + // @@protoc_insertion_point(field_get:tensorflow.AvailableDeviceInfo.memory_limit) + return _internal_memory_limit(); +} +inline void AvailableDeviceInfo::_internal_set_memory_limit(int64_t value) { + + _impl_.memory_limit_ = value; +} +inline void AvailableDeviceInfo::set_memory_limit(int64_t value) { + _internal_set_memory_limit(value); + // @@protoc_insertion_point(field_set:tensorflow.AvailableDeviceInfo.memory_limit) +} + +// string physical_description = 4; +inline void AvailableDeviceInfo::clear_physical_description() { + _impl_.physical_description_.ClearToEmpty(); +} +inline const std::string& AvailableDeviceInfo::physical_description() const { + // @@protoc_insertion_point(field_get:tensorflow.AvailableDeviceInfo.physical_description) + return _internal_physical_description(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AvailableDeviceInfo::set_physical_description(ArgT0&& arg0, ArgT... args) { + + _impl_.physical_description_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AvailableDeviceInfo.physical_description) +} +inline std::string* AvailableDeviceInfo::mutable_physical_description() { + std::string* _s = _internal_mutable_physical_description(); + // @@protoc_insertion_point(field_mutable:tensorflow.AvailableDeviceInfo.physical_description) + return _s; +} +inline const std::string& AvailableDeviceInfo::_internal_physical_description() const { + return _impl_.physical_description_.Get(); +} +inline void AvailableDeviceInfo::_internal_set_physical_description(const std::string& value) { + + _impl_.physical_description_.Set(value, GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::_internal_mutable_physical_description() { + + return _impl_.physical_description_.Mutable(GetArenaForAllocation()); +} +inline std::string* AvailableDeviceInfo::release_physical_description() { + // @@protoc_insertion_point(field_release:tensorflow.AvailableDeviceInfo.physical_description) + return _impl_.physical_description_.Release(); +} +inline void AvailableDeviceInfo::set_allocated_physical_description(std::string* physical_description) { + if (physical_description != nullptr) { + + } else { + + } + _impl_.physical_description_.SetAllocated(physical_description, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.physical_description_.IsDefault()) { + _impl_.physical_description_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.AvailableDeviceInfo.physical_description) +} + +// ------------------------------------------------------------------- + +// MachineConfiguration + +// string hostname = 1; +inline void MachineConfiguration::clear_hostname() { + _impl_.hostname_.ClearToEmpty(); +} +inline const std::string& MachineConfiguration::hostname() const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.hostname) + return _internal_hostname(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void MachineConfiguration::set_hostname(ArgT0&& arg0, ArgT... args) { + + _impl_.hostname_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.MachineConfiguration.hostname) +} +inline std::string* MachineConfiguration::mutable_hostname() { + std::string* _s = _internal_mutable_hostname(); + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.hostname) + return _s; +} +inline const std::string& MachineConfiguration::_internal_hostname() const { + return _impl_.hostname_.Get(); +} +inline void MachineConfiguration::_internal_set_hostname(const std::string& value) { + + _impl_.hostname_.Set(value, GetArenaForAllocation()); +} +inline std::string* MachineConfiguration::_internal_mutable_hostname() { + + return _impl_.hostname_.Mutable(GetArenaForAllocation()); +} +inline std::string* MachineConfiguration::release_hostname() { + // @@protoc_insertion_point(field_release:tensorflow.MachineConfiguration.hostname) + return _impl_.hostname_.Release(); +} +inline void MachineConfiguration::set_allocated_hostname(std::string* hostname) { + if (hostname != nullptr) { + + } else { + + } + _impl_.hostname_.SetAllocated(hostname, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.hostname_.IsDefault()) { + _impl_.hostname_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.MachineConfiguration.hostname) +} + +// string serial_identifier = 7; +inline void MachineConfiguration::clear_serial_identifier() { + _impl_.serial_identifier_.ClearToEmpty(); +} +inline const std::string& MachineConfiguration::serial_identifier() const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.serial_identifier) + return _internal_serial_identifier(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void MachineConfiguration::set_serial_identifier(ArgT0&& arg0, ArgT... args) { + + _impl_.serial_identifier_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.MachineConfiguration.serial_identifier) +} +inline std::string* MachineConfiguration::mutable_serial_identifier() { + std::string* _s = _internal_mutable_serial_identifier(); + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.serial_identifier) + return _s; +} +inline const std::string& MachineConfiguration::_internal_serial_identifier() const { + return _impl_.serial_identifier_.Get(); +} +inline void MachineConfiguration::_internal_set_serial_identifier(const std::string& value) { + + _impl_.serial_identifier_.Set(value, GetArenaForAllocation()); +} +inline std::string* MachineConfiguration::_internal_mutable_serial_identifier() { + + return _impl_.serial_identifier_.Mutable(GetArenaForAllocation()); +} +inline std::string* MachineConfiguration::release_serial_identifier() { + // @@protoc_insertion_point(field_release:tensorflow.MachineConfiguration.serial_identifier) + return _impl_.serial_identifier_.Release(); +} +inline void MachineConfiguration::set_allocated_serial_identifier(std::string* serial_identifier) { + if (serial_identifier != nullptr) { + + } else { + + } + _impl_.serial_identifier_.SetAllocated(serial_identifier, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.serial_identifier_.IsDefault()) { + _impl_.serial_identifier_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.MachineConfiguration.serial_identifier) +} + +// .tensorflow.PlatformInfo platform_info = 2; +inline bool MachineConfiguration::_internal_has_platform_info() const { + return this != internal_default_instance() && _impl_.platform_info_ != nullptr; +} +inline bool MachineConfiguration::has_platform_info() const { + return _internal_has_platform_info(); +} +inline void MachineConfiguration::clear_platform_info() { + if (GetArenaForAllocation() == nullptr && _impl_.platform_info_ != nullptr) { + delete _impl_.platform_info_; + } + _impl_.platform_info_ = nullptr; +} +inline const ::tensorflow::PlatformInfo& MachineConfiguration::_internal_platform_info() const { + const ::tensorflow::PlatformInfo* p = _impl_.platform_info_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_PlatformInfo_default_instance_); +} +inline const ::tensorflow::PlatformInfo& MachineConfiguration::platform_info() const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.platform_info) + return _internal_platform_info(); +} +inline void MachineConfiguration::unsafe_arena_set_allocated_platform_info( + ::tensorflow::PlatformInfo* platform_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.platform_info_); + } + _impl_.platform_info_ = platform_info; + if (platform_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MachineConfiguration.platform_info) +} +inline ::tensorflow::PlatformInfo* MachineConfiguration::release_platform_info() { + + ::tensorflow::PlatformInfo* temp = _impl_.platform_info_; + _impl_.platform_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::PlatformInfo* MachineConfiguration::unsafe_arena_release_platform_info() { + // @@protoc_insertion_point(field_release:tensorflow.MachineConfiguration.platform_info) + + ::tensorflow::PlatformInfo* temp = _impl_.platform_info_; + _impl_.platform_info_ = nullptr; + return temp; +} +inline ::tensorflow::PlatformInfo* MachineConfiguration::_internal_mutable_platform_info() { + + if (_impl_.platform_info_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::PlatformInfo>(GetArenaForAllocation()); + _impl_.platform_info_ = p; + } + return _impl_.platform_info_; +} +inline ::tensorflow::PlatformInfo* MachineConfiguration::mutable_platform_info() { + ::tensorflow::PlatformInfo* _msg = _internal_mutable_platform_info(); + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.platform_info) + return _msg; +} +inline void MachineConfiguration::set_allocated_platform_info(::tensorflow::PlatformInfo* platform_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.platform_info_; + } + if (platform_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(platform_info); + if (message_arena != submessage_arena) { + platform_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, platform_info, submessage_arena); + } + + } else { + + } + _impl_.platform_info_ = platform_info; + // @@protoc_insertion_point(field_set_allocated:tensorflow.MachineConfiguration.platform_info) +} + +// .tensorflow.CPUInfo cpu_info = 3; +inline bool MachineConfiguration::_internal_has_cpu_info() const { + return this != internal_default_instance() && _impl_.cpu_info_ != nullptr; +} +inline bool MachineConfiguration::has_cpu_info() const { + return _internal_has_cpu_info(); +} +inline void MachineConfiguration::clear_cpu_info() { + if (GetArenaForAllocation() == nullptr && _impl_.cpu_info_ != nullptr) { + delete _impl_.cpu_info_; + } + _impl_.cpu_info_ = nullptr; +} +inline const ::tensorflow::CPUInfo& MachineConfiguration::_internal_cpu_info() const { + const ::tensorflow::CPUInfo* p = _impl_.cpu_info_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_CPUInfo_default_instance_); +} +inline const ::tensorflow::CPUInfo& MachineConfiguration::cpu_info() const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.cpu_info) + return _internal_cpu_info(); +} +inline void MachineConfiguration::unsafe_arena_set_allocated_cpu_info( + ::tensorflow::CPUInfo* cpu_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cpu_info_); + } + _impl_.cpu_info_ = cpu_info; + if (cpu_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MachineConfiguration.cpu_info) +} +inline ::tensorflow::CPUInfo* MachineConfiguration::release_cpu_info() { + + ::tensorflow::CPUInfo* temp = _impl_.cpu_info_; + _impl_.cpu_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::CPUInfo* MachineConfiguration::unsafe_arena_release_cpu_info() { + // @@protoc_insertion_point(field_release:tensorflow.MachineConfiguration.cpu_info) + + ::tensorflow::CPUInfo* temp = _impl_.cpu_info_; + _impl_.cpu_info_ = nullptr; + return temp; +} +inline ::tensorflow::CPUInfo* MachineConfiguration::_internal_mutable_cpu_info() { + + if (_impl_.cpu_info_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::CPUInfo>(GetArenaForAllocation()); + _impl_.cpu_info_ = p; + } + return _impl_.cpu_info_; +} +inline ::tensorflow::CPUInfo* MachineConfiguration::mutable_cpu_info() { + ::tensorflow::CPUInfo* _msg = _internal_mutable_cpu_info(); + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.cpu_info) + return _msg; +} +inline void MachineConfiguration::set_allocated_cpu_info(::tensorflow::CPUInfo* cpu_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.cpu_info_; + } + if (cpu_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(cpu_info); + if (message_arena != submessage_arena) { + cpu_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cpu_info, submessage_arena); + } + + } else { + + } + _impl_.cpu_info_ = cpu_info; + // @@protoc_insertion_point(field_set_allocated:tensorflow.MachineConfiguration.cpu_info) +} + +// repeated .google.protobuf.Any device_info = 4; +inline int MachineConfiguration::_internal_device_info_size() const { + return _impl_.device_info_.size(); +} +inline int MachineConfiguration::device_info_size() const { + return _internal_device_info_size(); +} +inline ::PROTOBUF_NAMESPACE_ID::Any* MachineConfiguration::mutable_device_info(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.device_info) + return _impl_.device_info_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Any >* +MachineConfiguration::mutable_device_info() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.MachineConfiguration.device_info) + return &_impl_.device_info_; +} +inline const ::PROTOBUF_NAMESPACE_ID::Any& MachineConfiguration::_internal_device_info(int index) const { + return _impl_.device_info_.Get(index); +} +inline const ::PROTOBUF_NAMESPACE_ID::Any& MachineConfiguration::device_info(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.device_info) + return _internal_device_info(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Any* MachineConfiguration::_internal_add_device_info() { + return _impl_.device_info_.Add(); +} +inline ::PROTOBUF_NAMESPACE_ID::Any* MachineConfiguration::add_device_info() { + ::PROTOBUF_NAMESPACE_ID::Any* _add = _internal_add_device_info(); + // @@protoc_insertion_point(field_add:tensorflow.MachineConfiguration.device_info) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Any >& +MachineConfiguration::device_info() const { + // @@protoc_insertion_point(field_list:tensorflow.MachineConfiguration.device_info) + return _impl_.device_info_; +} + +// repeated .tensorflow.AvailableDeviceInfo available_device_info = 5; +inline int MachineConfiguration::_internal_available_device_info_size() const { + return _impl_.available_device_info_.size(); +} +inline int MachineConfiguration::available_device_info_size() const { + return _internal_available_device_info_size(); +} +inline void MachineConfiguration::clear_available_device_info() { + _impl_.available_device_info_.Clear(); +} +inline ::tensorflow::AvailableDeviceInfo* MachineConfiguration::mutable_available_device_info(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.available_device_info) + return _impl_.available_device_info_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::AvailableDeviceInfo >* +MachineConfiguration::mutable_available_device_info() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.MachineConfiguration.available_device_info) + return &_impl_.available_device_info_; +} +inline const ::tensorflow::AvailableDeviceInfo& MachineConfiguration::_internal_available_device_info(int index) const { + return _impl_.available_device_info_.Get(index); +} +inline const ::tensorflow::AvailableDeviceInfo& MachineConfiguration::available_device_info(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.available_device_info) + return _internal_available_device_info(index); +} +inline ::tensorflow::AvailableDeviceInfo* MachineConfiguration::_internal_add_available_device_info() { + return _impl_.available_device_info_.Add(); +} +inline ::tensorflow::AvailableDeviceInfo* MachineConfiguration::add_available_device_info() { + ::tensorflow::AvailableDeviceInfo* _add = _internal_add_available_device_info(); + // @@protoc_insertion_point(field_add:tensorflow.MachineConfiguration.available_device_info) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::AvailableDeviceInfo >& +MachineConfiguration::available_device_info() const { + // @@protoc_insertion_point(field_list:tensorflow.MachineConfiguration.available_device_info) + return _impl_.available_device_info_; +} + +// .tensorflow.MemoryInfo memory_info = 6; +inline bool MachineConfiguration::_internal_has_memory_info() const { + return this != internal_default_instance() && _impl_.memory_info_ != nullptr; +} +inline bool MachineConfiguration::has_memory_info() const { + return _internal_has_memory_info(); +} +inline void MachineConfiguration::clear_memory_info() { + if (GetArenaForAllocation() == nullptr && _impl_.memory_info_ != nullptr) { + delete _impl_.memory_info_; + } + _impl_.memory_info_ = nullptr; +} +inline const ::tensorflow::MemoryInfo& MachineConfiguration::_internal_memory_info() const { + const ::tensorflow::MemoryInfo* p = _impl_.memory_info_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_MemoryInfo_default_instance_); +} +inline const ::tensorflow::MemoryInfo& MachineConfiguration::memory_info() const { + // @@protoc_insertion_point(field_get:tensorflow.MachineConfiguration.memory_info) + return _internal_memory_info(); +} +inline void MachineConfiguration::unsafe_arena_set_allocated_memory_info( + ::tensorflow::MemoryInfo* memory_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.memory_info_); + } + _impl_.memory_info_ = memory_info; + if (memory_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MachineConfiguration.memory_info) +} +inline ::tensorflow::MemoryInfo* MachineConfiguration::release_memory_info() { + + ::tensorflow::MemoryInfo* temp = _impl_.memory_info_; + _impl_.memory_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::MemoryInfo* MachineConfiguration::unsafe_arena_release_memory_info() { + // @@protoc_insertion_point(field_release:tensorflow.MachineConfiguration.memory_info) + + ::tensorflow::MemoryInfo* temp = _impl_.memory_info_; + _impl_.memory_info_ = nullptr; + return temp; +} +inline ::tensorflow::MemoryInfo* MachineConfiguration::_internal_mutable_memory_info() { + + if (_impl_.memory_info_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::MemoryInfo>(GetArenaForAllocation()); + _impl_.memory_info_ = p; + } + return _impl_.memory_info_; +} +inline ::tensorflow::MemoryInfo* MachineConfiguration::mutable_memory_info() { + ::tensorflow::MemoryInfo* _msg = _internal_mutable_memory_info(); + // @@protoc_insertion_point(field_mutable:tensorflow.MachineConfiguration.memory_info) + return _msg; +} +inline void MachineConfiguration::set_allocated_memory_info(::tensorflow::MemoryInfo* memory_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.memory_info_; + } + if (memory_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(memory_info); + if (message_arena != submessage_arena) { + memory_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, memory_info, submessage_arena); + } + + } else { + + } + _impl_.memory_info_ = memory_info; + // @@protoc_insertion_point(field_set_allocated:tensorflow.MachineConfiguration.memory_info) +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// RunConfiguration + +// repeated string argument = 1; +inline int RunConfiguration::_internal_argument_size() const { + return _impl_.argument_.size(); +} +inline int RunConfiguration::argument_size() const { + return _internal_argument_size(); +} +inline void RunConfiguration::clear_argument() { + _impl_.argument_.Clear(); +} +inline std::string* RunConfiguration::add_argument() { + std::string* _s = _internal_add_argument(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.RunConfiguration.argument) + return _s; +} +inline const std::string& RunConfiguration::_internal_argument(int index) const { + return _impl_.argument_.Get(index); +} +inline const std::string& RunConfiguration::argument(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.RunConfiguration.argument) + return _internal_argument(index); +} +inline std::string* RunConfiguration::mutable_argument(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.RunConfiguration.argument) + return _impl_.argument_.Mutable(index); +} +inline void RunConfiguration::set_argument(int index, const std::string& value) { + _impl_.argument_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::set_argument(int index, std::string&& value) { + _impl_.argument_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::set_argument(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.argument_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::set_argument(int index, const char* value, size_t size) { + _impl_.argument_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.RunConfiguration.argument) +} +inline std::string* RunConfiguration::_internal_add_argument() { + return _impl_.argument_.Add(); +} +inline void RunConfiguration::add_argument(const std::string& value) { + _impl_.argument_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::add_argument(std::string&& value) { + _impl_.argument_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::add_argument(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.argument_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.RunConfiguration.argument) +} +inline void RunConfiguration::add_argument(const char* value, size_t size) { + _impl_.argument_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.RunConfiguration.argument) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +RunConfiguration::argument() const { + // @@protoc_insertion_point(field_list:tensorflow.RunConfiguration.argument) + return _impl_.argument_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +RunConfiguration::mutable_argument() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.RunConfiguration.argument) + return &_impl_.argument_; +} + +// map env_vars = 2; +inline int RunConfiguration::_internal_env_vars_size() const { + return _impl_.env_vars_.size(); +} +inline int RunConfiguration::env_vars_size() const { + return _internal_env_vars_size(); +} +inline void RunConfiguration::clear_env_vars() { + _impl_.env_vars_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& +RunConfiguration::_internal_env_vars() const { + return _impl_.env_vars_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >& +RunConfiguration::env_vars() const { + // @@protoc_insertion_point(field_map:tensorflow.RunConfiguration.env_vars) + return _internal_env_vars(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* +RunConfiguration::_internal_mutable_env_vars() { + return _impl_.env_vars_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, std::string >* +RunConfiguration::mutable_env_vars() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.RunConfiguration.env_vars) + return _internal_mutable_env_vars(); +} + +// ------------------------------------------------------------------- + +// TestResults + +// string target = 1; +inline void TestResults::clear_target() { + _impl_.target_.ClearToEmpty(); +} +inline const std::string& TestResults::target() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.target) + return _internal_target(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void TestResults::set_target(ArgT0&& arg0, ArgT... args) { + + _impl_.target_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.target) +} +inline std::string* TestResults::mutable_target() { + std::string* _s = _internal_mutable_target(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.target) + return _s; +} +inline const std::string& TestResults::_internal_target() const { + return _impl_.target_.Get(); +} +inline void TestResults::_internal_set_target(const std::string& value) { + + _impl_.target_.Set(value, GetArenaForAllocation()); +} +inline std::string* TestResults::_internal_mutable_target() { + + return _impl_.target_.Mutable(GetArenaForAllocation()); +} +inline std::string* TestResults::release_target() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.target) + return _impl_.target_.Release(); +} +inline void TestResults::set_allocated_target(std::string* target) { + if (target != nullptr) { + + } else { + + } + _impl_.target_.SetAllocated(target, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.target_.IsDefault()) { + _impl_.target_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.target) +} + +// .tensorflow.BenchmarkEntries entries = 2; +inline bool TestResults::_internal_has_entries() const { + return this != internal_default_instance() && _impl_.entries_ != nullptr; +} +inline bool TestResults::has_entries() const { + return _internal_has_entries(); +} +inline void TestResults::clear_entries() { + if (GetArenaForAllocation() == nullptr && _impl_.entries_ != nullptr) { + delete _impl_.entries_; + } + _impl_.entries_ = nullptr; +} +inline const ::tensorflow::BenchmarkEntries& TestResults::_internal_entries() const { + const ::tensorflow::BenchmarkEntries* p = _impl_.entries_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_BenchmarkEntries_default_instance_); +} +inline const ::tensorflow::BenchmarkEntries& TestResults::entries() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.entries) + return _internal_entries(); +} +inline void TestResults::unsafe_arena_set_allocated_entries( + ::tensorflow::BenchmarkEntries* entries) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.entries_); + } + _impl_.entries_ = entries; + if (entries) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TestResults.entries) +} +inline ::tensorflow::BenchmarkEntries* TestResults::release_entries() { + + ::tensorflow::BenchmarkEntries* temp = _impl_.entries_; + _impl_.entries_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::BenchmarkEntries* TestResults::unsafe_arena_release_entries() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.entries) + + ::tensorflow::BenchmarkEntries* temp = _impl_.entries_; + _impl_.entries_ = nullptr; + return temp; +} +inline ::tensorflow::BenchmarkEntries* TestResults::_internal_mutable_entries() { + + if (_impl_.entries_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::BenchmarkEntries>(GetArenaForAllocation()); + _impl_.entries_ = p; + } + return _impl_.entries_; +} +inline ::tensorflow::BenchmarkEntries* TestResults::mutable_entries() { + ::tensorflow::BenchmarkEntries* _msg = _internal_mutable_entries(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.entries) + return _msg; +} +inline void TestResults::set_allocated_entries(::tensorflow::BenchmarkEntries* entries) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.entries_; + } + if (entries) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(entries); + if (message_arena != submessage_arena) { + entries = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, entries, submessage_arena); + } + + } else { + + } + _impl_.entries_ = entries; + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.entries) +} + +// .tensorflow.BuildConfiguration build_configuration = 3; +inline bool TestResults::_internal_has_build_configuration() const { + return this != internal_default_instance() && _impl_.build_configuration_ != nullptr; +} +inline bool TestResults::has_build_configuration() const { + return _internal_has_build_configuration(); +} +inline void TestResults::clear_build_configuration() { + if (GetArenaForAllocation() == nullptr && _impl_.build_configuration_ != nullptr) { + delete _impl_.build_configuration_; + } + _impl_.build_configuration_ = nullptr; +} +inline const ::tensorflow::BuildConfiguration& TestResults::_internal_build_configuration() const { + const ::tensorflow::BuildConfiguration* p = _impl_.build_configuration_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_BuildConfiguration_default_instance_); +} +inline const ::tensorflow::BuildConfiguration& TestResults::build_configuration() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.build_configuration) + return _internal_build_configuration(); +} +inline void TestResults::unsafe_arena_set_allocated_build_configuration( + ::tensorflow::BuildConfiguration* build_configuration) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.build_configuration_); + } + _impl_.build_configuration_ = build_configuration; + if (build_configuration) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TestResults.build_configuration) +} +inline ::tensorflow::BuildConfiguration* TestResults::release_build_configuration() { + + ::tensorflow::BuildConfiguration* temp = _impl_.build_configuration_; + _impl_.build_configuration_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::BuildConfiguration* TestResults::unsafe_arena_release_build_configuration() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.build_configuration) + + ::tensorflow::BuildConfiguration* temp = _impl_.build_configuration_; + _impl_.build_configuration_ = nullptr; + return temp; +} +inline ::tensorflow::BuildConfiguration* TestResults::_internal_mutable_build_configuration() { + + if (_impl_.build_configuration_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::BuildConfiguration>(GetArenaForAllocation()); + _impl_.build_configuration_ = p; + } + return _impl_.build_configuration_; +} +inline ::tensorflow::BuildConfiguration* TestResults::mutable_build_configuration() { + ::tensorflow::BuildConfiguration* _msg = _internal_mutable_build_configuration(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.build_configuration) + return _msg; +} +inline void TestResults::set_allocated_build_configuration(::tensorflow::BuildConfiguration* build_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.build_configuration_; + } + if (build_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(build_configuration); + if (message_arena != submessage_arena) { + build_configuration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, build_configuration, submessage_arena); + } + + } else { + + } + _impl_.build_configuration_ = build_configuration; + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.build_configuration) +} + +// .tensorflow.CommitId commit_id = 4; +inline bool TestResults::_internal_has_commit_id() const { + return this != internal_default_instance() && _impl_.commit_id_ != nullptr; +} +inline bool TestResults::has_commit_id() const { + return _internal_has_commit_id(); +} +inline void TestResults::clear_commit_id() { + if (GetArenaForAllocation() == nullptr && _impl_.commit_id_ != nullptr) { + delete _impl_.commit_id_; + } + _impl_.commit_id_ = nullptr; +} +inline const ::tensorflow::CommitId& TestResults::_internal_commit_id() const { + const ::tensorflow::CommitId* p = _impl_.commit_id_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_CommitId_default_instance_); +} +inline const ::tensorflow::CommitId& TestResults::commit_id() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.commit_id) + return _internal_commit_id(); +} +inline void TestResults::unsafe_arena_set_allocated_commit_id( + ::tensorflow::CommitId* commit_id) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.commit_id_); + } + _impl_.commit_id_ = commit_id; + if (commit_id) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TestResults.commit_id) +} +inline ::tensorflow::CommitId* TestResults::release_commit_id() { + + ::tensorflow::CommitId* temp = _impl_.commit_id_; + _impl_.commit_id_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::CommitId* TestResults::unsafe_arena_release_commit_id() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.commit_id) + + ::tensorflow::CommitId* temp = _impl_.commit_id_; + _impl_.commit_id_ = nullptr; + return temp; +} +inline ::tensorflow::CommitId* TestResults::_internal_mutable_commit_id() { + + if (_impl_.commit_id_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::CommitId>(GetArenaForAllocation()); + _impl_.commit_id_ = p; + } + return _impl_.commit_id_; +} +inline ::tensorflow::CommitId* TestResults::mutable_commit_id() { + ::tensorflow::CommitId* _msg = _internal_mutable_commit_id(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.commit_id) + return _msg; +} +inline void TestResults::set_allocated_commit_id(::tensorflow::CommitId* commit_id) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.commit_id_; + } + if (commit_id) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(commit_id); + if (message_arena != submessage_arena) { + commit_id = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, commit_id, submessage_arena); + } + + } else { + + } + _impl_.commit_id_ = commit_id; + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.commit_id) +} + +// int64 start_time = 5; +inline void TestResults::clear_start_time() { + _impl_.start_time_ = int64_t{0}; +} +inline int64_t TestResults::_internal_start_time() const { + return _impl_.start_time_; +} +inline int64_t TestResults::start_time() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.start_time) + return _internal_start_time(); +} +inline void TestResults::_internal_set_start_time(int64_t value) { + + _impl_.start_time_ = value; +} +inline void TestResults::set_start_time(int64_t value) { + _internal_set_start_time(value); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.start_time) +} + +// double run_time = 6; +inline void TestResults::clear_run_time() { + _impl_.run_time_ = 0; +} +inline double TestResults::_internal_run_time() const { + return _impl_.run_time_; +} +inline double TestResults::run_time() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.run_time) + return _internal_run_time(); +} +inline void TestResults::_internal_set_run_time(double value) { + + _impl_.run_time_ = value; +} +inline void TestResults::set_run_time(double value) { + _internal_set_run_time(value); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.run_time) +} + +// .tensorflow.MachineConfiguration machine_configuration = 7; +inline bool TestResults::_internal_has_machine_configuration() const { + return this != internal_default_instance() && _impl_.machine_configuration_ != nullptr; +} +inline bool TestResults::has_machine_configuration() const { + return _internal_has_machine_configuration(); +} +inline void TestResults::clear_machine_configuration() { + if (GetArenaForAllocation() == nullptr && _impl_.machine_configuration_ != nullptr) { + delete _impl_.machine_configuration_; + } + _impl_.machine_configuration_ = nullptr; +} +inline const ::tensorflow::MachineConfiguration& TestResults::_internal_machine_configuration() const { + const ::tensorflow::MachineConfiguration* p = _impl_.machine_configuration_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_MachineConfiguration_default_instance_); +} +inline const ::tensorflow::MachineConfiguration& TestResults::machine_configuration() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.machine_configuration) + return _internal_machine_configuration(); +} +inline void TestResults::unsafe_arena_set_allocated_machine_configuration( + ::tensorflow::MachineConfiguration* machine_configuration) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.machine_configuration_); + } + _impl_.machine_configuration_ = machine_configuration; + if (machine_configuration) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TestResults.machine_configuration) +} +inline ::tensorflow::MachineConfiguration* TestResults::release_machine_configuration() { + + ::tensorflow::MachineConfiguration* temp = _impl_.machine_configuration_; + _impl_.machine_configuration_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::MachineConfiguration* TestResults::unsafe_arena_release_machine_configuration() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.machine_configuration) + + ::tensorflow::MachineConfiguration* temp = _impl_.machine_configuration_; + _impl_.machine_configuration_ = nullptr; + return temp; +} +inline ::tensorflow::MachineConfiguration* TestResults::_internal_mutable_machine_configuration() { + + if (_impl_.machine_configuration_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::MachineConfiguration>(GetArenaForAllocation()); + _impl_.machine_configuration_ = p; + } + return _impl_.machine_configuration_; +} +inline ::tensorflow::MachineConfiguration* TestResults::mutable_machine_configuration() { + ::tensorflow::MachineConfiguration* _msg = _internal_mutable_machine_configuration(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.machine_configuration) + return _msg; +} +inline void TestResults::set_allocated_machine_configuration(::tensorflow::MachineConfiguration* machine_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.machine_configuration_; + } + if (machine_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(machine_configuration); + if (message_arena != submessage_arena) { + machine_configuration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, machine_configuration, submessage_arena); + } + + } else { + + } + _impl_.machine_configuration_ = machine_configuration; + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.machine_configuration) +} + +// .tensorflow.RunConfiguration run_configuration = 8; +inline bool TestResults::_internal_has_run_configuration() const { + return this != internal_default_instance() && _impl_.run_configuration_ != nullptr; +} +inline bool TestResults::has_run_configuration() const { + return _internal_has_run_configuration(); +} +inline void TestResults::clear_run_configuration() { + if (GetArenaForAllocation() == nullptr && _impl_.run_configuration_ != nullptr) { + delete _impl_.run_configuration_; + } + _impl_.run_configuration_ = nullptr; +} +inline const ::tensorflow::RunConfiguration& TestResults::_internal_run_configuration() const { + const ::tensorflow::RunConfiguration* p = _impl_.run_configuration_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_RunConfiguration_default_instance_); +} +inline const ::tensorflow::RunConfiguration& TestResults::run_configuration() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.run_configuration) + return _internal_run_configuration(); +} +inline void TestResults::unsafe_arena_set_allocated_run_configuration( + ::tensorflow::RunConfiguration* run_configuration) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.run_configuration_); + } + _impl_.run_configuration_ = run_configuration; + if (run_configuration) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TestResults.run_configuration) +} +inline ::tensorflow::RunConfiguration* TestResults::release_run_configuration() { + + ::tensorflow::RunConfiguration* temp = _impl_.run_configuration_; + _impl_.run_configuration_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::RunConfiguration* TestResults::unsafe_arena_release_run_configuration() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.run_configuration) + + ::tensorflow::RunConfiguration* temp = _impl_.run_configuration_; + _impl_.run_configuration_ = nullptr; + return temp; +} +inline ::tensorflow::RunConfiguration* TestResults::_internal_mutable_run_configuration() { + + if (_impl_.run_configuration_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::RunConfiguration>(GetArenaForAllocation()); + _impl_.run_configuration_ = p; + } + return _impl_.run_configuration_; +} +inline ::tensorflow::RunConfiguration* TestResults::mutable_run_configuration() { + ::tensorflow::RunConfiguration* _msg = _internal_mutable_run_configuration(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.run_configuration) + return _msg; +} +inline void TestResults::set_allocated_run_configuration(::tensorflow::RunConfiguration* run_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.run_configuration_; + } + if (run_configuration) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(run_configuration); + if (message_arena != submessage_arena) { + run_configuration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, run_configuration, submessage_arena); + } + + } else { + + } + _impl_.run_configuration_ = run_configuration; + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.run_configuration) +} + +// string name = 9; +inline void TestResults::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& TestResults::name() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void TestResults::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.name) +} +inline std::string* TestResults::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.name) + return _s; +} +inline const std::string& TestResults::_internal_name() const { + return _impl_.name_.Get(); +} +inline void TestResults::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* TestResults::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* TestResults::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.name) + return _impl_.name_.Release(); +} +inline void TestResults::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.name) +} + +// .tensorflow.TestResults.BenchmarkType benchmark_type = 10; +inline void TestResults::clear_benchmark_type() { + _impl_.benchmark_type_ = 0; +} +inline ::tensorflow::TestResults_BenchmarkType TestResults::_internal_benchmark_type() const { + return static_cast< ::tensorflow::TestResults_BenchmarkType >(_impl_.benchmark_type_); +} +inline ::tensorflow::TestResults_BenchmarkType TestResults::benchmark_type() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.benchmark_type) + return _internal_benchmark_type(); +} +inline void TestResults::_internal_set_benchmark_type(::tensorflow::TestResults_BenchmarkType value) { + + _impl_.benchmark_type_ = value; +} +inline void TestResults::set_benchmark_type(::tensorflow::TestResults_BenchmarkType value) { + _internal_set_benchmark_type(value); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.benchmark_type) +} + +// string run_mode = 11; +inline void TestResults::clear_run_mode() { + _impl_.run_mode_.ClearToEmpty(); +} +inline const std::string& TestResults::run_mode() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.run_mode) + return _internal_run_mode(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void TestResults::set_run_mode(ArgT0&& arg0, ArgT... args) { + + _impl_.run_mode_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.run_mode) +} +inline std::string* TestResults::mutable_run_mode() { + std::string* _s = _internal_mutable_run_mode(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.run_mode) + return _s; +} +inline const std::string& TestResults::_internal_run_mode() const { + return _impl_.run_mode_.Get(); +} +inline void TestResults::_internal_set_run_mode(const std::string& value) { + + _impl_.run_mode_.Set(value, GetArenaForAllocation()); +} +inline std::string* TestResults::_internal_mutable_run_mode() { + + return _impl_.run_mode_.Mutable(GetArenaForAllocation()); +} +inline std::string* TestResults::release_run_mode() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.run_mode) + return _impl_.run_mode_.Release(); +} +inline void TestResults::set_allocated_run_mode(std::string* run_mode) { + if (run_mode != nullptr) { + + } else { + + } + _impl_.run_mode_.SetAllocated(run_mode, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.run_mode_.IsDefault()) { + _impl_.run_mode_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.run_mode) +} + +// string tf_version = 12; +inline void TestResults::clear_tf_version() { + _impl_.tf_version_.ClearToEmpty(); +} +inline const std::string& TestResults::tf_version() const { + // @@protoc_insertion_point(field_get:tensorflow.TestResults.tf_version) + return _internal_tf_version(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void TestResults::set_tf_version(ArgT0&& arg0, ArgT... args) { + + _impl_.tf_version_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.TestResults.tf_version) +} +inline std::string* TestResults::mutable_tf_version() { + std::string* _s = _internal_mutable_tf_version(); + // @@protoc_insertion_point(field_mutable:tensorflow.TestResults.tf_version) + return _s; +} +inline const std::string& TestResults::_internal_tf_version() const { + return _impl_.tf_version_.Get(); +} +inline void TestResults::_internal_set_tf_version(const std::string& value) { + + _impl_.tf_version_.Set(value, GetArenaForAllocation()); +} +inline std::string* TestResults::_internal_mutable_tf_version() { + + return _impl_.tf_version_.Mutable(GetArenaForAllocation()); +} +inline std::string* TestResults::release_tf_version() { + // @@protoc_insertion_point(field_release:tensorflow.TestResults.tf_version) + return _impl_.tf_version_.Release(); +} +inline void TestResults::set_allocated_tf_version(std::string* tf_version) { + if (tf_version != nullptr) { + + } else { + + } + _impl_.tf_version_.SetAllocated(tf_version, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.tf_version_.IsDefault()) { + _impl_.tf_version_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.TestResults.tf_version) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::TestResults_BenchmarkType> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::TestResults_BenchmarkType>() { + return ::tensorflow::TestResults_BenchmarkType_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tsl_2fprotobuf_2ftest_5flog_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.proto new file mode 100644 index 0000000000000000000000000000000000000000..6d3af02e65767be895dafa319cc05b2be6582581 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/protobuf/test_log.proto @@ -0,0 +1,223 @@ +// Protocol messages for describing the results of benchmarks and unit tests. +syntax = "proto3"; + +package tensorflow; + +import "google/protobuf/any.proto"; +import "google/protobuf/wrappers.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "TestLogProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.util.testlog"; + +message EntryValue { + oneof kind { + double double_value = 1; + string string_value = 2; + } +} + +message MetricEntry { + // Metric name + string name = 1; + + // Metric value + double value = 2; + + // The minimum acceptable value for the metric if specified + google.protobuf.DoubleValue min_value = 3; + + // The maximum acceptable value for the metric if specified + google.protobuf.DoubleValue max_value = 4; +} + +// Each unit test or benchmark in a test or benchmark run provides +// some set of information. Here we provide some reasonable keys +// one would expect to see, with optional key/value pairs for things +// we haven't considered. +// +// This BenchmarkEntry should be emitted by each unit test or benchmark +// reporter. +message BenchmarkEntry { + // The name of the specific benchmark or test + // (e.g. BM_AdjustContrast_gpu_B_W_H) + string name = 1; + + // If a benchmark, how many iterations it was run for + int64 iters = 2; + + // Total cpu time used for all iterations (in seconds) + double cpu_time = 3; + + // Total wall time used for all iterations (in seconds) + double wall_time = 4; + + // Throughput (in MB/s) + double throughput = 5; + + // Generic map from result key to value. + map extras = 6; + + // Metric name, value and expected range. This can include accuracy metrics + // typically used to determine whether the accuracy test has passed + repeated MetricEntry metrics = 7; +} + +message BenchmarkEntries { + repeated BenchmarkEntry entry = 1; +} + +message BuildConfiguration { + string mode = 1; // opt, dbg, etc + repeated string cc_flags = 2; // CC compiler flags, if known + repeated string opts = 3; // Bazel compilation options, if known +} + +message CommitId { + oneof kind { + // Submitted changelist. + int64 changelist = 1; + string hash = 2; + } + // Hash of intermediate change between hash/changelist and what was tested. + // Not used if the build is from a commit without modifications. + string snapshot = 3; + // Changelist tested if the change list is not already submitted. + int64 pending_changelist = 4; +} + +message CPUInfo { + int64 num_cores = 1; + + int64 num_cores_allowed = 2; + + // How fast are these cpus? + double mhz_per_cpu = 3; + + // Additional cpu information. For example, + // Intel Ivybridge with HyperThreading (24 cores) dL1:32KB dL2:256KB dL3:30MB + string cpu_info = 4; + + // What kind of cpu scaling is enabled on the host. + // Examples include "performance", "ondemand", "conservative", "mixed". + string cpu_governor = 5; + + // Cache sizes (in bytes), e.g. "L2": 262144 (for 256KB) + map cache_size = 6; +} + +message MemoryInfo { + int64 total = 1; // Total virtual memory in bytes + int64 available = 2; // Immediately available memory in bytes +} + +message GPUInfo { + string model = 1; // e.g. "Tesla K40c" + string uuid = 2; // Final entry in output of "nvidia-smi -L" + string bus_id = 3; // e.g. "0000:04:00.0" +} + +message PlatformInfo { + string bits = 1; // e.g. '64bit' + string linkage = 2; // e.g. 'ELF' + string machine = 3; // e.g. 'i386' + string release = 4; // e.g. '3.13.0-76-generic' + string system = 5; // e.g. 'Linux' + string version = 6; // e.g. '#120-Ubuntu SMP Mon Jan 18 15:59:10 UTC 2016' +} + +message AvailableDeviceInfo { // Matches DeviceAttributes + string name = 1; // Device name. + string type = 2; // Device type, e.g. 'CPU' or 'GPU'. + int64 memory_limit = 3; // Memory capacity in bytes. + string physical_description = 4; // The physical description of this device. +} + +message MachineConfiguration { + // Host name of machine that ran the benchmark. + string hostname = 1; + + // Unique serial number of the machine. + string serial_identifier = 7; + + // Additional platform information. + PlatformInfo platform_info = 2; + + // CPU Information. + CPUInfo cpu_info = 3; + + // Other devices that are attached and relevant (e.g. GPUInfo). + repeated google.protobuf.Any device_info = 4; + + // Devices accessible to the test (e.g. as given by list_local_devices). + repeated AvailableDeviceInfo available_device_info = 5; + + MemoryInfo memory_info = 6; +} + +// Run-specific items such as arguments to the test / benchmark. +message RunConfiguration { + repeated string argument = 1; + // Environment variables used to run the test/benchmark. + map env_vars = 2; +} + +// The output of one benchmark / test run. Each run contains a list of +// tests or benchmarks, stored as BenchmarkEntry messages. +// +// This message should be emitted by the reporter (which runs the +// test / BM in a subprocess and then reads the emitted BenchmarkEntry messages; +// usually from a serialized json file, finally collecting them along +// with additional information about the test run. +message TestResults { + // The target of the run, e.g.: + // //tensorflow/core:kernels_adjust_contrast_op_benchmark_test + string target = 1; + + // The list of tests or benchmarks in this run. + BenchmarkEntries entries = 2; + + // The configuration of the build (compiled opt? with cuda? any copts?) + BuildConfiguration build_configuration = 3; + + // The commit id (git hash or changelist) + CommitId commit_id = 4; + + // The time the run started (in seconds of UTC time since Unix epoch) + int64 start_time = 5; + + // The amount of time the total run took (wall time in seconds) + double run_time = 6; + + // Machine-specific parameters (Platform and CPU info) + MachineConfiguration machine_configuration = 7; + + // Run-specific parameters (arguments, etc) + RunConfiguration run_configuration = 8; + + // Benchmark target identifier. + string name = 9; + + // The type of benchmark. + enum BenchmarkType { + UNKNOWN = 0; // Fallback for protos written before Type was introduced. + CPP_MICROBENCHMARK = 1; + PYTHON_BENCHMARK = 2; + ANDROID_BENCHMARK = 3; + EDGE_BENCHMARK = 4; + IOS_BENCHMARK = 5; + } + BenchmarkType benchmark_type = 10; + + // Used for differentiating between continuous and debug builds. + // Must be one of: + // * cbuild: results from continuous build. + // * presubmit: results from oneshot requests. + // * culprit: results from culprit finder rerun. + string run_mode = 11; + + // TensorFlow version this benchmark runs against. + // This can be either set to full version or just the major version. + string tf_version = 12; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/ml_dtypes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/ml_dtypes.h new file mode 100644 index 0000000000000000000000000000000000000000..f2b93ebee41a218e05a41dda76a74c3c5b5a4326 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/ml_dtypes.h @@ -0,0 +1,50 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_ +#define TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_ + +// Registers all custom types from the python ml_dtypes package. +// https://github.com/jax-ml/ml_dtypes + +namespace tsl { +namespace ml_dtypes { + +struct NumpyDtypes { + int bfloat16; + int float8_e4m3fn; + int float8_e4m3b11fnuz; + int float8_e4m3fnuz; + int float8_e5m2; + int float8_e5m2fnuz; + int int4; + int uint4; +}; + +// RegisterTypes imports the ml_dtypes module. It should be called before using +// the functions below, and it fails (by returning false) if there was an error +// importing that module. If the build system guarantees that the module exists, +// the call can be omitted, since it is implied by the functions below. +bool RegisterTypes(); + +// Implicitly calls RegisterTypes on first use. +const NumpyDtypes& GetNumpyDtypes(); + +inline int GetBfloat16TypeNum() { return GetNumpyDtypes().bfloat16; } + +} // namespace ml_dtypes +} // namespace tsl + +#endif // TENSORFLOW_TSL_PYTHON_LIB_CORE_ML_DTYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/numpy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/numpy.h new file mode 100644 index 0000000000000000000000000000000000000000..8cbe3ab74e20d1f5a72d94b1e0bd2dde51864380 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/python/lib/core/numpy.h @@ -0,0 +1,50 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_ +#define TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_ + +#ifdef PyArray_Type +#error "Numpy cannot be included before numpy.h." +#endif + +// Disallow Numpy 1.7 deprecated symbols. +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION + +// We import_array in the XLA init function only. +#define PY_ARRAY_UNIQUE_SYMBOL _xla_numpy_api +#ifndef XLA_IMPORT_NUMPY +#define NO_IMPORT_ARRAY +#endif + +// Place `` before to avoid build failure in macOS. +#include + +#include + +#include "numpy/arrayobject.h" +#include "numpy/ufuncobject.h" + +namespace tsl { + +// Import numpy. This wrapper function exists so that the +// PY_ARRAY_UNIQUE_SYMBOL can be safely defined in a .cc file to +// avoid weird linking issues. Should be called only from our +// module initialization function. +void ImportNumpy(); + +} // namespace tsl + +#endif // TENSORFLOW_TSL_PYTHON_LIB_CORE_NUMPY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/byte_swap_array.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/byte_swap_array.h new file mode 100644 index 0000000000000000000000000000000000000000..ad7e34efcd51f7cb6e2f16b4c97c0ef5f92946bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/byte_swap_array.h @@ -0,0 +1,104 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_ +#define TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_ + +#include "tsl/platform/byte_order.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" + +// Define basic byte swapping operations. +// These operations must be macros to use compiler intrinsics. +// Note that the code here is written for portability, not speed. Byte swapping +// only happens when importing a checkpoint from one hardware architecture onto +// a different architecture. If these operations become part of a fast path, +// then the function ByteSwapArray() below should be rewritten to use +// architecture-appropriate SIMD instructions that swap multiple words at once. + +#if defined(__linux__) + +// Use the Gnu byte swap macros when available. See bswap(3) for more info. +#include +#define BYTE_SWAP_16(x) bswap_16(x) +#define BYTE_SWAP_32(x) bswap_32(x) +#define BYTE_SWAP_64(x) bswap_64(x) + +#elif defined(PLATFORM_WINDOWS) + +// On windows, byte-swapping is in winsock.h, and winsock2.h has a version of +// of htonl that can byte-swap 64-bit values. +#include +#define BYTE_SWAP_16(x) htons(x) +#define BYTE_SWAP_32(x) htonl(x) +// At the moment the 64-bit and 128-bit byte-swapping routines in Winsock2 are +// disabled in TensorFlow's standard Windows build environment, so we use +// htonl() instead of "#define BYTE_SWAP_64(x) htonll (x)". +#define BYTE_SWAP_64(x) \ + ((uint64_t(htonl((x)&0x00000000ffffffffUL)) << 32) | \ + (htonl(((x)&0xffffffff00000000UL) >> 32))) + +#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + +// On non-Linux, non-Windows, but little-endian, environments, use htonl/s, +// which byte-swap when the host byte order is little-endian. POSIX doesn't +// define a 64-bit version of these library functions, so we roll our own. +#include +#define BYTE_SWAP_16(x) htons(x) +#define BYTE_SWAP_32(x) htonl(x) +#define BYTE_SWAP_64(x) \ + ((uint64_t(htonl((x)&0x00000000ffffffffUL)) << 32) | \ + (htonl(((x)&0xffffffff00000000UL) >> 32))) + +#else // not defined(__linux__) and not defined(PLATFORM_WINDOWS) + // and (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__) + +// Fall back on a non-optimized implementation on other big-endian targets. +// This code swaps one byte at a time and is probably an order of magnitude +// slower. + +#define BYTE_SWAP_16(x) ((((x)&0x00ff) << 8) | (((x)&0xff00) >> 8)) + +#define BYTE_SWAP_32(x) \ + ((((x)&0x000000ffU) << 24) | (((x)&0x0000ff00U) << 8) | \ + (((x)&0x00ff0000U) >> 8) | (((x)&0xff000000U) >> 24)) + +#define BYTE_SWAP_64(x) \ + ((((x)&0x00000000000000ffUL) << 56) | (((x)&0x000000000000ff00UL) << 40) | \ + (((x)&0x0000000000ff0000UL) << 24) | (((x)&0x00000000ff000000UL) << 8) | \ + (((x)&0x000000ff00000000UL) >> 8) | (((x)&0x0000ff0000000000UL) >> 24) | \ + (((x)&0x00ff000000000000UL) >> 40) | (((x)&0xff00000000000000UL) >> 56)) + +#endif // defined(__linux__) + +namespace tsl { + +// Byte-swap an entire array of atomic C/C++ types in place. +// +// Note: When calling this function on arrays of std::complex<> types, +// multiply the number of elements by 2 and divide the bytes per element by 2. +// +// Args: +// array: Pointer to the beginning of the array +// bytes_per_elem: Number of bytes in each element of the array +// array_len: Number of elements in the array +// +// Returns: OkStatus() on success, -1 otherwise +// +Status ByteSwapArray(char *array, size_t bytes_per_elem, int array_len); + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_BYTE_SWAP_ARRAY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/command_line_flags.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/command_line_flags.h new file mode 100644 index 0000000000000000000000000000000000000000..6553bc887c853e8d11cada3ae513db5727e058ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/command_line_flags.h @@ -0,0 +1,143 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_ +#define TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_ + +#include +#include +#include + +#include "tsl/platform/types.h" + +namespace tsl { + +// N.B. This library is for INTERNAL use only. +// +// This is a simple command-line argument parsing module to help us handle +// parameters for C++ binaries. The recommended way of using it is with local +// variables and an initializer list of Flag objects, for example: +// +// int some_int = 10; +// bool some_switch = false; +// string some_name = "something"; +// std::vector flag_list = { +// Flag("some_int", &some_int, "an integer that affects X"), +// Flag("some_switch", &some_switch, "a bool that affects Y"), +// Flag("some_name", &some_name, "a string that affects Z") +// }; +// // Get usage message before ParseFlags() to capture default values. +// string usage = Flag::Usage(argv[0], flag_list); +// bool parsed_values_ok = Flags::Parse(&argc, argv, flag_list); +// +// tsl::port::InitMain(usage.c_str(), &argc, &argv); +// if (argc != 1 || !parsed_values_ok) { +// ...output usage and error message... +// } +// +// The argc and argv values are adjusted by the Parse function so all that +// remains is the program name (at argv[0]) and any unknown arguments fill the +// rest of the array. This means you can check for flags that weren't understood +// by seeing if argv is greater than 1. +// The result indicates if there were any errors parsing the values that were +// passed to the command-line switches. For example, --some_int=foo would return +// false because the argument is expected to be an integer. +// +// NOTE: Unlike gflags-style libraries, this library is intended to be +// used in the `main()` function of your binary. It does not handle +// flag definitions that are scattered around the source code. + +// A description of a single command line flag, holding its name, type, usage +// text, and a pointer to the corresponding variable. +class Flag { + public: + Flag(const char* name, int32* dst, const string& usage_text, + bool* dst_updated = nullptr); + Flag(const char* name, int64_t* dst, const string& usage_text, + bool* dst_updated = nullptr); + Flag(const char* name, bool* dst, const string& usage_text, + bool* dst_updated = nullptr); + Flag(const char* name, string* dst, const string& usage_text, + bool* dst_updated = nullptr); + Flag(const char* name, float* dst, const string& usage_text, + bool* dst_updated = nullptr); + + // These constructors invoke a hook on a match instead of writing to a + // specific memory location. The hook may return false to signal a malformed + // or illegal value, which will then fail the command line parse. + // + // "default_value_for_display" is shown as the default value of this flag in + // Flags::Usage(). + Flag(const char* name, std::function int32_hook, + int32_t default_value_for_display, const string& usage_text); + Flag(const char* name, std::function int64_hook, + int64_t default_value_for_display, const string& usage_text); + Flag(const char* name, std::function float_hook, + float default_value_for_display, const string& usage_text); + Flag(const char* name, std::function bool_hook, + bool default_value_for_display, const string& usage_text); + Flag(const char* name, std::function string_hook, + string default_value_for_display, const string& usage_text); + + private: + friend class Flags; + + bool Parse(string arg, bool* value_parsing_ok) const; + + string name_; + enum { + TYPE_INT32, + TYPE_INT64, + TYPE_BOOL, + TYPE_STRING, + TYPE_FLOAT, + } type_; + + std::function int32_hook_; + int32 int32_default_for_display_; + + std::function int64_hook_; + int64_t int64_default_for_display_; + + std::function float_hook_; + float float_default_for_display_; + + std::function bool_hook_; + bool bool_default_for_display_; + + std::function string_hook_; + string string_default_for_display_; + + string usage_text_; +}; + +class Flags { + public: + // Parse the command line represented by argv[0, ..., (*argc)-1] to find flag + // instances matching flags in flaglist[]. Update the variables associated + // with matching flags, and remove the matching arguments from (*argc, argv). + // Return true iff all recognized flag values were parsed correctly, and the + // first remaining argument is not "--help". + static bool Parse(int* argc, char** argv, const std::vector& flag_list); + + // Return a usage message with command line cmdline, and the + // usage_text strings in flag_list[]. + static string Usage(const string& cmdline, + const std::vector& flag_list); +}; + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_COMMAND_LINE_FLAGS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/determinism.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/determinism.h new file mode 100644 index 0000000000000000000000000000000000000000..fff5b195845a39a51d31a3426b21cb4e586c6f17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/determinism.h @@ -0,0 +1,27 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_DETERMINISM_H_ +#define TENSORFLOW_TSL_UTIL_DETERMINISM_H_ + +namespace tsl { + +bool OpDeterminismRequired(); +bool OpOrderDeterminismRequired(); +void EnableOpDeterminism(bool enabled); + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_DETERMINISM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/device_name_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/device_name_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..51dcca37ac05493e2ca6305f7229747fcce47771 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/device_name_utils.h @@ -0,0 +1,294 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_ +#define TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_ + +#include + +#include "tsl/platform/status.h" +#include "tsl/platform/stringpiece.h" + +namespace tsl { + +// In TensorFlow a device name is a string of the following form: +// /job:/replica:/task:/device:: +// +// is a short identifier conforming to the regexp +// [a-zA-Z][_a-zA-Z]* +// is a supported device type (e.g. 'cpu' or 'gpu') +// , , are small non-negative integers and are +// densely allocated (except in tests). +// +// For some purposes, we also allow device patterns, which can specify +// some or none of the specific fields above, with missing components, +// or ":*" indicating "any value allowed for that component. +// +// For example: +// "/job:param_server" - Consider any devices in the "param_server" job +// "/device:cpu:*" - Consider any cpu devices in any job/task/replica +// "/job:*/replica:*/task:*/device:cpu:*" - Consider any cpu devices in any +// job/task/replica +// "/job:w/replica:0/task:0/device:gpu:*" - Consider any gpu devices in +// replica 0, task 0, of job "w" +class DeviceNameUtils { + public: + // Returns a fully qualified device name given the parameters. + static std::string FullName(const std::string& job, int replica, int task, + const std::string& type, int id); + + // TODO(b/278776328): Convert this to a Protobuf, since emptiness of a field + // is a standardized pattern in Protobuf. + struct ParsedName { + void Clear() { + has_job = false; + has_replica = false; + has_task = false; + has_type = false; + has_id = false; + job.clear(); + replica = 0; + task = 0; + type.clear(); + id = 0; + } + + bool operator==(const ParsedName& other) const { + return (has_job ? (other.has_job && job == other.job) : !other.has_job) && + (has_replica ? (other.has_replica && replica == other.replica) + : !other.has_replica) && + (has_task ? (other.has_task && task == other.task) + : !other.has_task) && + (has_type ? (other.has_type && type == other.type) + : !other.has_type) && + (has_id ? (other.has_id && id == other.id) : !other.has_id); + } + + bool operator!=(const ParsedName& other) const { + return !operator==(other); + } + + bool operator<(const ParsedName& other) const { + if (has_job != other.has_job) return !has_job; + if (has_job) { + if (job < other.job) { + return true; + } + if (job > other.job) { + return false; + } + } + if (has_replica != other.has_replica) return !has_replica; + if (has_replica) { + if (replica < other.replica) { + return true; + } + if (replica > other.replica) { + return false; + } + } + if (has_task != other.has_task) return !has_task; + if (has_task) { + if (task < other.task) { + return true; + } + if (task > other.task) { + return false; + } + } + if (has_type != other.has_type) return !has_type; + if (has_type) { + if (type < other.type) { + return true; + } + if (type > other.type) { + return false; + } + } + if (has_id != other.has_id) return !has_id; + if (has_id) { + if (id < other.id) { + return true; + } + if (id > other.id) { + return false; + } + } + return false; + } + + template + friend H AbslHashValue(H h, const ParsedName& n) { + return H::combine(std::move(h), n.has_job, n.job, n.has_replica, + n.replica, n.has_task, n.task, n.has_type, n.type, + n.has_id, n.id); + } + + bool has_job = false; + std::string job; + bool has_replica = false; + int replica = 0; + bool has_task = false; + int task = 0; + bool has_type = false; + std::string type; + bool has_id = false; + int id = 0; + }; + + // Parses the device name, first as a full name, then, if it fails, as a + // global one. Returns `false` if both attempts fail. + static bool ParseFullOrLocalName(StringPiece fullname, ParsedName* parsed); + + // Parses "fullname" into "*parsed". Returns true iff succeeds. + // Legacy names like "/cpu:0" that don't contain "device", + // are parsed to mean their current counterparts "/device:CPU:0". More + // specifically, the lower case "cpu" and "gpu" is capitalized and "device" + // is added. "/tpu:0" is not treated the same way - it has use the current + // full syntax. + // Also, note that lower case "cpu" and "gpu" device types in current syntax + // are not capitalized. For example, "/device:CPU:0" is different from + // "/device:cpu:0" + static bool ParseFullName(StringPiece fullname, ParsedName* parsed); + + // Canonicalizes "fullname" into "*canonical_name". Uses a fully specified + // basename to fill in fields that are missing. Accepts both legacy, newer + // and local versions of the device spec. Returns the newer version of the + // device spec. If we were unable to interpret / parse "fullname" returns + // an error and *canonical_name is set to "". + static Status CanonicalizeDeviceName(StringPiece fullname, + StringPiece basename, + std::string* canonical_name); + + // Returns true if "name" specifies any non-trivial constraint on the device. + static bool HasSomeDetails(const ParsedName& name) { + return name.has_job || name.has_replica || name.has_task || name.has_type || + name.has_id; + } + + // Returns true if more_specific is a specification of + // less_specific, i.e. everywhere that less-specific has a + // non-wildcard component value, more_specific has the same value + // for that component. + static bool IsSpecification(const ParsedName& less_specific, + const ParsedName& more_specific); + + // Makes minimal changes to more_specific so that it becomes a + // specification of less_specific. + static void EnsureSpecification(ParsedName* more_specific, + const ParsedName& less_specific); + + // Like IsSpecification, but the second argument "name" must have a + // non-wildcard value for all of its components. + static bool IsCompleteSpecification(const ParsedName& pattern, + const ParsedName& name); + + // True iff there exists any possible device name that is a specification of + // both "a" and "b". + static bool AreCompatibleDevNames(const ParsedName& a, const ParsedName& b); + + // Merges the device specifications in "*target" and "other", and + // stores the result in "*target". Returns OK if "*target" and + // "other" are compatible, otherwise returns an error. + static Status MergeDevNames(ParsedName* target, const ParsedName& other) { + return MergeDevNames(target, other, false); + } + static Status MergeDevNames(ParsedName* target, const ParsedName& other, + bool allow_soft_placement); + // Same as MergeDevNames with allow_soft_placement=true, but instead of + // clearing conflicting fields, overrides them with `other`'s values. + static Status MergeOverrideDevNames(ParsedName* target, + const ParsedName& other); + + // Merges the device specifications in "*target" and "other", and + // stores the result in "*target" by setting all unset values in target with + // corresponding set ones in other. + static void MergeUnsetDevNames(ParsedName* target, const ParsedName& other); + + // Returns true iff devices identified by 'src' and 'dst' are in the + // same address space. + static bool IsSameAddressSpace(StringPiece src, StringPiece dst); + static bool IsSameAddressSpace(const ParsedName& src, const ParsedName& dst); + + // Returns true iff devices identified by 'a' and 'b' are in different + // address space. + static bool IsDifferentAddressSpace(const ParsedName& a, const ParsedName& b); + + // Returns the an address space specification containing only the + // job/replica/task of the given name. + static const ParsedName AddressSpace(const ParsedName& name); + + // Returns the local device given its "type" and "id". + static std::string LocalName(StringPiece type, int id); + + // Returns a short local device name (cpu:0, gpu:1, etc) based on + // the given fullname. + static std::string LocalName(StringPiece fullname); + + // If "name" is a valid local device name (cpu:0, gpu:1, etc.), + // fills in parsed.type and parsed.id accordingly. Returns true iff + // succeeds. + static bool ParseLocalName(StringPiece name, ParsedName* parsed); + + // Splits a fully-qualified device name into a task identifier and a + // relative device identifier. It first parses "name" using + // ParseFullName(), then assigns *task with everything except for + // the local device component, and assigns the relative device + // component into *device. This function will still return true if + // the task component is empty, but it requires the relative device + // component to be fully specified. + static bool SplitDeviceName(StringPiece name, std::string* task, + std::string* device); + + // Get the task name from ParsedName. Return false if the task component is + // not fully specified. + static bool GetTaskName(const ParsedName& pn, std::string* task); + + static std::string ParsedNameToString(const ParsedName& pn); + + // Returns canonical and legacy full names for the given parsed + // device name 'pn'. The returned string names are often useful to + // look up devices from a mapping. + static std::vector GetNamesForDeviceMappings(const ParsedName& pn); + + // Returns canonical and legacy local names for the given parsed device name + // 'pn'. The returned string names are often useful to look up devices from a + // mapping. + static std::vector GetLocalNamesForDeviceMappings( + const ParsedName& pn); + + // Returns name of the CPU:0 device on the same host as the device + // `device_name`. + static Status DeviceNameToCpuDeviceName(const std::string& device_name, + std::string* host_device_name); + + static bool CompareFullNames(const StringPiece& a, const StringPiece& b) { + ParsedName parsed_a; + ParsedName parsed_b; + bool a_status = ParseFullName(a, &parsed_a); + bool b_status = ParseFullName(b, &parsed_b); + // Orders unparsable names first. + if (a_status != b_status) return !a_status; + if (!a_status) return a < b; + return parsed_a < parsed_b; + } +}; + +std::ostream& operator<<(std::ostream& os, + const DeviceNameUtils::ParsedName& x); + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_DEVICE_NAME_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/env_var.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/env_var.h new file mode 100644 index 0000000000000000000000000000000000000000..9c6925c57f643ba896b84a9ac68b1c93c07cb926 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/env_var.h @@ -0,0 +1,56 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_ENV_VAR_H_ +#define TENSORFLOW_TSL_UTIL_ENV_VAR_H_ + +#include "tsl/platform/status.h" +#include "tsl/platform/stringpiece.h" +#include "tsl/platform/types.h" + +namespace tsl { + +// Returns a boolean into "value" from the environmental variable +// "env_var_name". If it is unset, the default value is used. A string "0" or a +// case insensitive "false" is interpreted as false. A string "1" or a case +// insensitive "true" is interpreted as true. Otherwise, an error status is +// returned. +Status ReadBoolFromEnvVar(StringPiece env_var_name, bool default_val, + bool* value); + +// Returns an int64 into "value" from the environmental variable "env_var_name". +// If it is unset, the default value is used. +// If the string cannot be parsed into int64, an error status is returned. +Status ReadInt64FromEnvVar(StringPiece env_var_name, int64_t default_val, + int64_t* value); +// Returns a float into "value" from the environmental variable "env_var_name". +// If it is unset, the default value is used. +// If the string cannot be parsed into float, an error status is returned. +Status ReadFloatFromEnvVar(StringPiece env_var_name, float default_val, + float* value); + +// Returns a string into "value" from the environmental variable "env_var_name". +// If it is unset, the default value is used. +Status ReadStringFromEnvVar(StringPiece env_var_name, StringPiece default_val, + std::string* value); + +// Returns a comma separated string into "value" from the environmental variable +// "env_var_name". If it is unset, the default value is comma split and used. +Status ReadStringsFromEnvVar(StringPiece env_var_name, StringPiece default_val, + std::vector* value); + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_ENV_VAR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/onednn_threadpool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/onednn_threadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..82fbec738f00eed8fab5f35bc7b1bc0c9d8d0950 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/onednn_threadpool.h @@ -0,0 +1,188 @@ + +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_ +#define TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_ +#ifdef INTEL_MKL + +#include +#include +#include +#include +#include +#include + +#define EIGEN_USE_THREADS + +#include "dnnl.hpp" +#include "dnnl_threadpool.hpp" +#include "tsl/platform/blocking_counter.h" +#include "tsl/platform/cpu_info.h" +#include "tsl/platform/threadpool.h" + +namespace tsl { + +#ifndef ENABLE_ONEDNN_OPENMP +using dnnl::threadpool_interop::threadpool_iface; + +// Divide 'n' units of work equally among 'teams' threads. If 'n' is not +// divisible by 'teams' and has a remainder 'r', the first 'r' teams have one +// unit of work more than the rest. Returns the range of work that belongs to +// the team 'tid'. +// Parameters +// n Total number of jobs. +// team Number of workers. +// tid Current thread_id. +// n_start start of range operated by the thread. +// n_end end of the range operated by the thread. + +template +inline void balance211(T n, U team, U tid, T* n_start, T* n_end) { + if (team <= 1 || n == 0) { + *n_start = 0; + *n_end = n; + return; + } + T min_per_team = n / team; + T remainder = n - min_per_team * team; // i.e., n % teams. + *n_start = tid * min_per_team + std::min(tid, remainder); + *n_end = *n_start + min_per_team + (tid < remainder); +} + +inline void run_jobs(bool balance, int i, int n, int njobs, + const std::function& fn) { + if (balance) { + int start, end; + balance211(n, njobs, i, &start, &end); + for (int j = start; j < end; j++) fn(j, n); + } else { + fn(i, n); + } +} + +class OneDnnThreadPool : public threadpool_iface { + public: + OneDnnThreadPool() = default; + + OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface, + int num_threads = -1) + : eigen_interface_(eigen_interface) { + set_num_and_max_threads(num_threads); + } + OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface, + bool can_use_caller_thread, int num_threads = -1) + : eigen_interface_(eigen_interface), + can_use_caller_thread_(can_use_caller_thread) { + set_num_and_max_threads(num_threads); + } + virtual int get_num_threads() const override { return num_threads_; } + virtual bool get_in_parallel() const override { + return (eigen_interface_->CurrentThreadId() != -1) ? true : false; + } + virtual uint64_t get_flags() const override { return ASYNCHRONOUS; } + virtual void parallel_for(int n, + const std::function& fn) override { + // Should never happen (handled by DNNL) + if (n == 0) return; + + // Should never happen (handled by DNNL) + if (n == 1) { + fn(0, 1); + return; + } + + int nthr = get_num_threads(); + int njobs = std::min(n, nthr); + bool balance = (nthr < n); + + // If use_caller_thread, schedule njobs-1 jobs to thread pool and run last + // job directly. + const bool use_caller_thread = + can_use_caller_thread_ && nthr == port::NumSchedulableCPUs(); + const int njobs_to_schedule = use_caller_thread ? njobs - 1 : njobs; + + if (use_caller_thread) { + for (int i = 0; i < njobs_to_schedule; i++) { + eigen_interface_->ScheduleWithHint( + [balance, i, n, njobs, fn]() { + run_jobs(balance, i, n, njobs, fn); + }, + i, i + 1); + } + run_jobs(balance, njobs_to_schedule, n, njobs, fn); + } else { + tsl::BlockingCounter counter(njobs); + std::function handle_range = [=, &handle_range, &counter]( + int first, int last) { + while (last - first > 1) { + const auto mid = first + (last - first) / 2; + // Find something near the midpoint which is a multiple of block size. + eigen_interface_->ScheduleWithHint([=]() { handle_range(mid, last); }, + mid, mid + 1); + last = mid; + } + counter.DecrementCount(); + run_jobs(balance, first, n, njobs, fn); + }; + + // Eigen avoids a thread hop by running the root of the tree on the main + // thread. We have disabled this because it actually slows things down + // relative to base because base cheats and uses n threads while letting + // main continue doing other work + eigen_interface_->ScheduleWithHint([=]() { handle_range(0, njobs); }, 0, + 1); + + counter.Wait(); + } + } + + ~OneDnnThreadPool() {} + + private: + Eigen::ThreadPoolInterface* eigen_interface_ = nullptr; + int num_threads_ = 1; // Execute in caller thread. + bool can_use_caller_thread_ = false; // true if the user set the env variable + // to use caller thread also. + inline void set_num_and_max_threads(int num_threads) { + num_threads_ = + num_threads == -1 ? eigen_interface_->NumThreads() : num_threads; +#if DNNL_VERSION_MAJOR >= 3 || \ + (DNNL_VERSION_MAJOR == 2 && DNNL_VERSION_MINOR >= 7) +#ifndef DNNL_AARCH64_USE_ACL + dnnl_threadpool_interop_set_max_concurrency(num_threads_); +#endif // DNNL_AARCH64_USE_ACL +#endif // DNNL_VERSION_MAJOR >= 3 || + // (DNNL_VERSION_MAJOR == 2 && DNNL_VERSION_MINOR >= 7) + } +}; + +#else + +// This class was just added to enable successful OMP-based build. +class OneDnnThreadPool { + public: + OneDnnThreadPool() = default; + OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface) {} + OneDnnThreadPool(Eigen::ThreadPoolInterface* eigen_interface, + bool can_use_caller_thread, int num_threads = -1) {} +}; + +#endif // !ENABLE_ONEDNN_OPENMP + +} // namespace tsl + +#endif // INTEL_MKL +#endif // TENSORFLOW_TSL_UTIL_ONEDNN_THREADPOOL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/proto/proto_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/proto/proto_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..9a1dee8eed5224370c76ae5ab34c374cfc829567 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/proto/proto_utils.h @@ -0,0 +1,42 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_ +#define TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_ + +#include "google/protobuf/duration.pb.h" +#include "absl/time/time.h" + +namespace tsl { +namespace proto_utils { + +// Converts an absl::Duration to a google::protobuf::Duration. +inline google::protobuf::Duration ToDurationProto(absl::Duration duration) { + google::protobuf::Duration proto; + proto.set_seconds(absl::IDivDuration(duration, absl::Seconds(1), &duration)); + proto.set_nanos( + absl::IDivDuration(duration, absl::Nanoseconds(1), &duration)); + return proto; +} + +// Converts a google::protobuf::Duration to an absl::Duration. +inline absl::Duration FromDurationProto(google::protobuf::Duration proto) { + return absl::Seconds(proto.seconds()) + absl::Nanoseconds(proto.nanos()); +} + +} // namespace proto_utils +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_PROTO_PROTO_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stat_summarizer_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stat_summarizer_options.h new file mode 100644 index 0000000000000000000000000000000000000000..e07de6e8d5d9d14ea381f2b84b47950cb5c68038 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stat_summarizer_options.h @@ -0,0 +1,44 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_ +#define TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_ +namespace tsl { +// Used to control the output of the statistics summarizer; +struct StatSummarizerOptions { + StatSummarizerOptions() + : show_run_order(true), + run_order_limit(0), + show_time(true), + time_limit(10), + show_memory(true), + memory_limit(10), + show_type(true), + show_summary(true), + format_as_csv(false) {} + + bool show_run_order; + int run_order_limit; + bool show_time; + int time_limit; + bool show_memory; + int memory_limit; + bool show_type; + bool show_summary; + bool format_as_csv; +}; +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_STAT_SUMMARIZER_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stats_calculator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stats_calculator.h new file mode 100644 index 0000000000000000000000000000000000000000..5c23f432971c23db140e1deec82d2d9c8928502a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/stats_calculator.h @@ -0,0 +1,201 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_ +#define TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "tsl/util/stat_summarizer_options.h" + +namespace tsl { + +template +class Stat { + public: + void UpdateStat(ValueType v) { + if (count_ == 0) { + first_ = v; + } + + newest_ = v; + max_ = std::max(v, max_); + min_ = std::min(v, min_); + ++count_; + sum_ += v; + squared_sum_ += static_cast(v) * v; + } + + void Reset() { new (this) Stat(); } + + bool empty() const { return count_ == 0; } + + ValueType first() const { return first_; } + + ValueType newest() const { return newest_; } + + ValueType max() const { return max_; } + + ValueType min() const { return min_; } + + int64_t count() const { return count_; } + + ValueType sum() const { return sum_; } + + HighPrecisionValueType squared_sum() const { return squared_sum_; } + + bool all_same() const { return (count_ == 0 || min_ == max_); } + + HighPrecisionValueType avg() const { + return empty() ? std::numeric_limits::quiet_NaN() + : static_cast(sum_) / count_; + } + + // Returns sample variance. + ValueType sample_variance() const { + return all_same() + ? 0 + : (squared_sum_ - std::pow(sum_, 2.0) / count_) / (count_ - 1); + } + + // Returns population variance. + ValueType variance() const { + return all_same() ? 0 : (squared_sum_ / count_) - (avg() * avg()); + } + + // Returns population stddev. + ValueType std_deviation() const { + return all_same() ? 0 : std::sqrt(variance()); + } + + void OutputToStream(std::ostream* stream) const { + if (empty()) { + *stream << "count=0"; + } else if (all_same()) { + *stream << "count=" << count_ << " curr=" << newest_; + if (count_ > 1) *stream << "(all same)"; + } else { + *stream << "count=" << count_ << " first=" << first_ + << " curr=" << newest_ << " min=" << min_ << " max=" << max_ + << " avg=" << avg() << " std=" << std_deviation(); + } + } + + friend std::ostream& operator<<(std::ostream& stream, + const Stat& stat) { + stat.OutputToStream(&stream); + return stream; + } + + private: + ValueType first_ = 0; + ValueType newest_ = 0; + ValueType max_ = std::numeric_limits::min(); + ValueType min_ = std::numeric_limits::max(); + int64_t count_ = 0; + ValueType sum_ = 0; + HighPrecisionValueType squared_sum_ = 0; +}; + +// A StatsCalculator assists in performance analysis of Graph executions. +// +// It summarizes time spent executing (on GPU/CPU), memory used etc for +// graph execution. +// +// For example usage see StatsSummarizer. +class StatsCalculator { + public: + enum SortingMetric { + BY_NAME, + BY_RUN_ORDER, + BY_TIME, + BY_MEMORY, + BY_TYPE, + }; + + explicit StatsCalculator(const StatSummarizerOptions& options); + + // Returns a string detailing the accumulated runtime stats in a tab-separated + // format which can be pasted into a spreadsheet for further analysis. + std::string GetOutputString() const; + + std::string GetShortSummary() const; + + void ComputeStatsByType( + std::map* node_type_map_count, + std::map* node_type_map_time, + std::map* node_type_map_memory, + std::map* node_type_map_times_called, + int64_t* accumulated_us) const; + + std::string GetStatsByNodeType() const; + + std::string GetStatsByMetric(const std::string& title, + SortingMetric sorting_metric, + int num_stats) const; + + // Returns number of runs. + int num_runs() const { return static_cast(run_total_us_.count()); } + + // Returns stats of total microseconds spent by all nodes in each run. + const Stat& run_total_us() const { return run_total_us_; } + + void UpdateRunTotalUs(int64_t run_total_us) { + run_total_us_.UpdateStat(run_total_us); + } + + void UpdateMemoryUsed(int64_t memory) { memory_.UpdateStat(memory); } + + struct Detail { + std::string name; + std::string type; + int64_t run_order; + Stat elapsed_time; + Stat mem_used; + int64_t times_called; + }; + + const std::map& GetDetails() const { return details_; } + + void AddNodeStats(const std::string& name, const std::string& type, + int64_t run_order, int64_t rel_end_us, int64_t mem_used); + + private: + void OrderNodesByMetric(SortingMetric sorting_metric, + std::vector* details) const; + + std::string HeaderString(const std::string& title) const; + std::string ColumnString(const Detail& detail, + const int64_t cumulative_stat_on_node, + const Stat& stat) const; + + Stat run_total_us_; + Stat memory_; + + std::map details_; + StatSummarizerOptions options_; +}; + +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_STATS_CALCULATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/use_cudnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/use_cudnn.h new file mode 100644 index 0000000000000000000000000000000000000000..738e727e4c7808c3ad979eb42b7977ca2a1502e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tsl/util/use_cudnn.h @@ -0,0 +1,43 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The utility to check Cudnn dependency and set Cudnn-related flags. + +#ifndef TENSORFLOW_TSL_UTIL_USE_CUDNN_H_ +#define TENSORFLOW_TSL_UTIL_USE_CUDNN_H_ + +#include + +namespace tsl { + +bool CudnnUseAutotune(); +bool CudnnUseFrontend(); +bool CudnnUseRuntimeFusion(); +bool CudnnRnnUseAutotune(); +bool CudnnDisableConv1x1Optimization(); +bool DebugCudnnRnn(); +bool DebugCudnnRnnUseTensorOps(); +int64_t DebugCudnnRnnAlgo(); + +// Returns true if the CuDNN depthwise convolution can be used. See cudnn +// release note 7.6.3. +// (https://docs.nvidia.com/deeplearning/sdk/cudnn-release-notes/rel_763.html) +bool ShouldCudnnGroupedConvolutionBeUsed(const int32_t filter_rows, + const int32_t filter_cols, + const int32_t in_depth, + const int32_t out_depth); +} // namespace tsl + +#endif // TENSORFLOW_TSL_UTIL_USE_CUDNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AdolcForward b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AdolcForward new file mode 100644 index 0000000000000000000000000000000000000000..ad05504b232b606a47cf6174e596c2359b349df7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AdolcForward @@ -0,0 +1,159 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ADLOC_FORWARD_MODULE_H +#define EIGEN_ADLOC_FORWARD_MODULE_H + +//-------------------------------------------------------------------------------- +// +// This file provides support for adolc's adouble type in forward mode. +// ADOL-C is a C++ automatic differentiation library, +// see https://projects.coin-or.org/ADOL-C for more information. +// +// Note that the maximal number of directions is controlled by +// the preprocessor token NUMBER_DIRECTIONS. The default is 2. +// +//-------------------------------------------------------------------------------- + +#define ADOLC_TAPELESS +#ifndef NUMBER_DIRECTIONS +# define NUMBER_DIRECTIONS 2 +#endif +#include + +// adolc defines some very stupid macros: +#if defined(malloc) +# undef malloc +#endif + +#if defined(calloc) +# undef calloc +#endif + +#if defined(realloc) +# undef realloc +#endif + +#include "../../Eigen/Core" + +namespace Eigen { + +/** + * \defgroup AdolcForward_Module Adolc forward module + * This module provides support for adolc's adouble type in forward mode. + * ADOL-C is a C++ automatic differentiation library, + * see https://projects.coin-or.org/ADOL-C for more information. + * It mainly consists in: + * - a struct Eigen::NumTraits specialization + * - overloads of internal::* math function for adtl::adouble type. + * + * Note that the maximal number of directions is controlled by + * the preprocessor token NUMBER_DIRECTIONS. The default is 2. + * + * \code + * #include + * \endcode + */ + //@{ + +} // namespace Eigen + +// Eigen's require a few additional functions which must be defined in the same namespace +// than the custom scalar type own namespace +namespace adtl { + +inline const adouble& conj(const adouble& x) { return x; } +inline const adouble& real(const adouble& x) { return x; } +inline adouble imag(const adouble&) { return 0.; } +inline adouble abs(const adouble& x) { return fabs(x); } +inline adouble abs2(const adouble& x) { return x*x; } + +inline bool (isinf)(const adouble& x) { return (Eigen::numext::isinf)(x.getValue()); } +inline bool (isnan)(const adouble& x) { return (Eigen::numext::isnan)(x.getValue()); } + +} + +namespace Eigen { + +template<> struct NumTraits + : NumTraits +{ + typedef adtl::adouble Real; + typedef adtl::adouble NonInteger; + typedef adtl::adouble Nested; + enum { + IsComplex = 0, + IsInteger = 0, + IsSigned = 1, + RequireInitialization = 1, + ReadCost = 1, + AddCost = 1, + MulCost = 1 + }; +}; + +template class AdolcForwardJacobian : public Functor +{ + typedef adtl::adouble ActiveScalar; +public: + + AdolcForwardJacobian() : Functor() {} + AdolcForwardJacobian(const Functor& f) : Functor(f) {} + + // forward constructors + template + AdolcForwardJacobian(const T0& a0) : Functor(a0) {} + template + AdolcForwardJacobian(const T0& a0, const T1& a1) : Functor(a0, a1) {} + template + AdolcForwardJacobian(const T0& a0, const T1& a1, const T1& a2) : Functor(a0, a1, a2) {} + + typedef typename Functor::InputType InputType; + typedef typename Functor::ValueType ValueType; + typedef typename Functor::JacobianType JacobianType; + + typedef Matrix ActiveInput; + typedef Matrix ActiveValue; + + void operator() (const InputType& x, ValueType* v, JacobianType* _jac) const + { + eigen_assert(v!=0); + if (!_jac) + { + Functor::operator()(x, v); + return; + } + + JacobianType& jac = *_jac; + + ActiveInput ax = x.template cast(); + ActiveValue av(jac.rows()); + + for (int j=0; j +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ALIGNED_VECTOR3_MODULE_H +#define EIGEN_ALIGNED_VECTOR3_MODULE_H + +#include "../../Eigen/Geometry" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +namespace Eigen { + +/** + * \defgroup AlignedVector3_Module Aligned vector3 module + * + * \code + * #include + * \endcode + */ + //@{ + + +/** \class AlignedVector3 + * + * \brief A vectorization friendly 3D vector + * + * This class represents a 3D vector internally using a 4D vector + * such that vectorization can be seamlessly enabled. Of course, + * the same result can be achieved by directly using a 4D vector. + * This class makes this process simpler. + * + */ +// TODO specialize Cwise +template class AlignedVector3; + +namespace internal { +template struct traits > + : traits > +{ +}; +} + +template class AlignedVector3 + : public MatrixBase > +{ + typedef Matrix CoeffType; + CoeffType m_coeffs; + public: + + typedef MatrixBase > Base; + EIGEN_DENSE_PUBLIC_INTERFACE(AlignedVector3) + using Base::operator*; + + inline Index rows() const { return 3; } + inline Index cols() const { return 1; } + + Scalar* data() { return m_coeffs.data(); } + const Scalar* data() const { return m_coeffs.data(); } + Index innerStride() const { return 1; } + Index outerStride() const { return 3; } + + inline const Scalar& coeff(Index row, Index col) const + { return m_coeffs.coeff(row, col); } + + inline Scalar& coeffRef(Index row, Index col) + { return m_coeffs.coeffRef(row, col); } + + inline const Scalar& coeff(Index index) const + { return m_coeffs.coeff(index); } + + inline Scalar& coeffRef(Index index) + { return m_coeffs.coeffRef(index);} + + + inline AlignedVector3() + {} + + inline AlignedVector3(const Scalar& x, const Scalar& y, const Scalar& z) + : m_coeffs(x, y, z, Scalar(0)) + {} + + inline AlignedVector3(const AlignedVector3& other) + : Base(), m_coeffs(other.m_coeffs) + {} + + template + struct generic_assign_selector {}; + + template struct generic_assign_selector + { + inline static void run(AlignedVector3& dest, const XprType& src) + { + dest.m_coeffs = src; + } + }; + + template struct generic_assign_selector + { + inline static void run(AlignedVector3& dest, const XprType& src) + { + dest.m_coeffs.template head<3>() = src; + dest.m_coeffs.w() = Scalar(0); + } + }; + + template + inline AlignedVector3(const MatrixBase& other) + { + generic_assign_selector::run(*this,other.derived()); + } + + inline AlignedVector3& operator=(const AlignedVector3& other) + { m_coeffs = other.m_coeffs; return *this; } + + template + inline AlignedVector3& operator=(const MatrixBase& other) + { + generic_assign_selector::run(*this,other.derived()); + return *this; + } + + inline AlignedVector3 operator+(const AlignedVector3& other) const + { return AlignedVector3(m_coeffs + other.m_coeffs); } + + inline AlignedVector3& operator+=(const AlignedVector3& other) + { m_coeffs += other.m_coeffs; return *this; } + + inline AlignedVector3 operator-(const AlignedVector3& other) const + { return AlignedVector3(m_coeffs - other.m_coeffs); } + + inline AlignedVector3 operator-() const + { return AlignedVector3(-m_coeffs); } + + inline AlignedVector3 operator-=(const AlignedVector3& other) + { m_coeffs -= other.m_coeffs; return *this; } + + inline AlignedVector3 operator*(const Scalar& s) const + { return AlignedVector3(m_coeffs * s); } + + inline friend AlignedVector3 operator*(const Scalar& s,const AlignedVector3& vec) + { return AlignedVector3(s * vec.m_coeffs); } + + inline AlignedVector3& operator*=(const Scalar& s) + { m_coeffs *= s; return *this; } + + inline AlignedVector3 operator/(const Scalar& s) const + { return AlignedVector3(m_coeffs / s); } + + inline AlignedVector3& operator/=(const Scalar& s) + { m_coeffs /= s; return *this; } + + inline Scalar dot(const AlignedVector3& other) const + { + eigen_assert(m_coeffs.w()==Scalar(0)); + eigen_assert(other.m_coeffs.w()==Scalar(0)); + return m_coeffs.dot(other.m_coeffs); + } + + inline void normalize() + { + m_coeffs /= norm(); + } + + inline AlignedVector3 normalized() const + { + return AlignedVector3(m_coeffs / norm()); + } + + inline Scalar sum() const + { + eigen_assert(m_coeffs.w()==Scalar(0)); + return m_coeffs.sum(); + } + + inline Scalar squaredNorm() const + { + eigen_assert(m_coeffs.w()==Scalar(0)); + return m_coeffs.squaredNorm(); + } + + inline Scalar norm() const + { + using std::sqrt; + return sqrt(squaredNorm()); + } + + inline AlignedVector3 cross(const AlignedVector3& other) const + { + return AlignedVector3(m_coeffs.cross3(other.m_coeffs)); + } + + template + inline bool isApprox(const MatrixBase& other, const RealScalar& eps=NumTraits::dummy_precision()) const + { + return m_coeffs.template head<3>().isApprox(other,eps); + } + + CoeffType& coeffs() { return m_coeffs; } + const CoeffType& coeffs() const { return m_coeffs; } +}; + +namespace internal { + +template +struct eval, Dense> +{ + typedef const AlignedVector3& type; +}; + +template +struct evaluator > + : evaluator > +{ + typedef AlignedVector3 XprType; + typedef evaluator > Base; + + evaluator(const XprType &m) : Base(m.coeffs()) {} +}; + +} + +//@} + +} + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ALIGNED_VECTOR3_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/ArpackSupport b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/ArpackSupport new file mode 100644 index 0000000000000000000000000000000000000000..b89d8e9ac5fb72c43be3872d7561d88cb6c99aaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/ArpackSupport @@ -0,0 +1,33 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ARPACKSUPPORT_MODULE_H +#define EIGEN_ARPACKSUPPORT_MODULE_H + +#include "../../Eigen/Core" + +/** \defgroup ArpackSupport_Module Arpack support module + * + * This module provides a wrapper to Arpack, a library for sparse eigenvalue decomposition. + * + * \code + * #include + * \endcode + */ + +#include "../../Eigen/SparseCholesky" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "src/Eigenvalues/ArpackSelfAdjointEigenSolver.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ARPACKSUPPORT_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AutoDiff b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AutoDiff new file mode 100644 index 0000000000000000000000000000000000000000..6372e8f8821af76ee0ba57da9766dea06f6b5201 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/AutoDiff @@ -0,0 +1,49 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_AUTODIFF_MODULE_H +#define EIGEN_AUTODIFF_MODULE_H + +#include "../../Eigen/Core" + +namespace Eigen { + +/** + * \defgroup AutoDiff_Module Auto Diff module + * + * This module features forward automatic differentation via a simple + * templated scalar type wrapper AutoDiffScalar. + * + * Warning : this should NOT be confused with numerical differentiation, which + * is a different method and has its own module in Eigen : \ref NumericalDiff_Module. + * + * \code + * #include + * \endcode + */ +//@{ + +} +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "src/AutoDiff/AutoDiffScalar.h" +// #include "src/AutoDiff/AutoDiffVector.h" +#include "src/AutoDiff/AutoDiffJacobian.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + + + +namespace Eigen { +//@} +} + +#endif // EIGEN_AUTODIFF_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/BVH b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/BVH new file mode 100644 index 0000000000000000000000000000000000000000..136ec4d91dbfc0f99b399844a2d6f63181db1501 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/BVH @@ -0,0 +1,97 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Ilya Baran +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BVH_MODULE_H +#define EIGEN_BVH_MODULE_H + +#include "../../Eigen/Core" +#include "../../Eigen/Geometry" +#include "../../Eigen/StdVector" +#include +#include + +namespace Eigen { + +/** + * \defgroup BVH_Module BVH module + * \brief This module provides generic bounding volume hierarchy algorithms + * and reference tree implementations. + * + * + * \code + * #include + * \endcode + * + * A bounding volume hierarchy (BVH) can accelerate many geometric queries. This module provides a generic implementation + * of the two basic algorithms over a BVH: intersection of a query object against all objects in the hierarchy and minimization + * of a function over the objects in the hierarchy. It also provides intersection and minimization over a cartesian product of + * two BVH's. A BVH accelerates intersection by using the fact that if a query object does not intersect a volume, then it cannot + * intersect any object contained in that volume. Similarly, a BVH accelerates minimization because the minimum of a function + * over a volume is no greater than the minimum of a function over any object contained in it. + * + * Some sample queries that can be written in terms of intersection are: + * - Determine all points where a ray intersects a triangle mesh + * - Given a set of points, determine which are contained in a query sphere + * - Given a set of spheres, determine which contain the query point + * - Given a set of disks, determine if any is completely contained in a query rectangle (represent each 2D disk as a point \f$(x,y,r)\f$ + * in 3D and represent the rectangle as a pyramid based on the original rectangle and shrinking in the \f$r\f$ direction) + * - Given a set of points, count how many pairs are \f$d\pm\epsilon\f$ apart (done by looking at the cartesian product of the set + * of points with itself) + * + * Some sample queries that can be written in terms of function minimization over a set of objects are: + * - Find the intersection between a ray and a triangle mesh closest to the ray origin (function is infinite off the ray) + * - Given a polyline and a query point, determine the closest point on the polyline to the query + * - Find the diameter of a point cloud (done by looking at the cartesian product and using negative distance as the function) + * - Determine how far two meshes are from colliding (this is also a cartesian product query) + * + * This implementation decouples the basic algorithms both from the type of hierarchy (and the types of the bounding volumes) and + * from the particulars of the query. To enable abstraction from the BVH, the BVH is required to implement a generic mechanism + * for traversal. To abstract from the query, the query is responsible for keeping track of results. + * + * To be used in the algorithms, a hierarchy must implement the following traversal mechanism (see KdBVH for a sample implementation): \code + typedef Volume //the type of bounding volume + typedef Object //the type of object in the hierarchy + typedef Index //a reference to a node in the hierarchy--typically an int or a pointer + typedef VolumeIterator //an iterator type over node children--returns Index + typedef ObjectIterator //an iterator over object (leaf) children--returns const Object & + Index getRootIndex() const //returns the index of the hierarchy root + const Volume &getVolume(Index index) const //returns the bounding volume of the node at given index + void getChildren(Index index, VolumeIterator &outVBegin, VolumeIterator &outVEnd, + ObjectIterator &outOBegin, ObjectIterator &outOEnd) const + //getChildren takes a node index and makes [outVBegin, outVEnd) range over its node children + //and [outOBegin, outOEnd) range over its object children + \endcode + * + * To use the hierarchy, call BVIntersect or BVMinimize, passing it a BVH (or two, for cartesian product) and a minimizer or intersector. + * For an intersection query on a single BVH, the intersector encapsulates the query and must provide two functions: + * \code + bool intersectVolume(const Volume &volume) //returns true if the query intersects the volume + bool intersectObject(const Object &object) //returns true if the intersection search should terminate immediately + \endcode + * The guarantee that BVIntersect provides is that intersectObject will be called on every object whose bounding volume + * intersects the query (but possibly on other objects too) unless the search is terminated prematurely. It is the + * responsibility of the intersectObject function to keep track of the results in whatever manner is appropriate. + * The cartesian product intersection and the BVMinimize queries are similar--see their individual documentation. + * + * The following is a simple but complete example for how to use the BVH to accelerate the search for a closest red-blue point pair: + * \include BVH_Example.cpp + * Output: \verbinclude BVH_Example.out + */ +} + +//@{ + +// IWYU pragma: begin_exports +#include "src/BVH/BVAlgorithms.h" +#include "src/BVH/KdBVH.h" +// IWYU pragma: end_exports + +//@} + +#endif // EIGEN_BVH_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/Tensor b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/Tensor new file mode 100644 index 0000000000000000000000000000000000000000..f2636eceae57bed495264196af4124439f68b08f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/Tensor @@ -0,0 +1,141 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +//#ifndef EIGEN_CXX11_TENSOR_MODULE_H +#define EIGEN_CXX11_TENSOR_MODULE_H + +#include "../../../Eigen/Core" + +#include "../SpecialFunctions" + +#include "../../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "../../../Eigen/src/Core/util/Meta.h" +#include "../../../Eigen/src/Core/util/MaxSizeVector.h" +// IWYU pragma: end_exports + +/** \defgroup CXX11_Tensor_Module Tensor Module + * + * This module provides a Tensor class for storing arbitrarily indexed + * objects. + * + * \code + * #include + * \endcode + * + * Much of the documentation can be found \ref eigen_tensors "here". + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(EIGEN_USE_THREADS) || defined(EIGEN_USE_SYCL) +#include "ThreadPool" +#endif + +#ifdef EIGEN_USE_GPU + #include + #if defined(EIGEN_USE_HIP) + #include + #else + #include + #endif +#endif + +// IWYU pragma: begin_exports +#include "src/Tensor/TensorMacros.h" +#include "src/Tensor/TensorForwardDeclarations.h" +#include "src/Tensor/TensorMeta.h" +#include "src/Tensor/TensorFunctors.h" +#include "src/Tensor/TensorCostModel.h" +#include "src/Tensor/TensorDeviceDefault.h" +#include "src/Tensor/TensorDeviceThreadPool.h" +#include "src/Tensor/TensorDeviceGpu.h" +#ifndef gpu_assert +#define gpu_assert(x) +#endif +#include "src/Tensor/TensorDeviceSycl.h" +#include "src/Tensor/TensorIndexList.h" +#include "src/Tensor/TensorDimensionList.h" +#include "src/Tensor/TensorDimensions.h" +#include "src/Tensor/TensorInitializer.h" +#include "src/Tensor/TensorTraits.h" +#include "src/Tensor/TensorRandom.h" +#include "src/Tensor/TensorUInt128.h" +#include "src/Tensor/TensorIntDiv.h" +#include "src/Tensor/TensorGlobalFunctions.h" + +#include "src/Tensor/TensorIO.h" + +#include "src/Tensor/TensorBase.h" +#include "src/Tensor/TensorBlock.h" + +#include "src/Tensor/TensorEvaluator.h" +#include "src/Tensor/TensorExpr.h" +#include "src/Tensor/TensorReduction.h" +#include "src/Tensor/TensorReductionGpu.h" +#include "src/Tensor/TensorArgMax.h" +#include "src/Tensor/TensorConcatenation.h" +#include "src/Tensor/TensorContractionMapper.h" +#include "src/Tensor/TensorContractionBlocking.h" +#include "src/Tensor/TensorContraction.h" +#include "src/Tensor/TensorContractionThreadPool.h" +#include "src/Tensor/TensorContractionGpu.h" +#include "src/Tensor/TensorConversion.h" +#include "src/Tensor/TensorConvolution.h" +#include "src/Tensor/TensorFFT.h" +#include "src/Tensor/TensorPatch.h" +#include "src/Tensor/TensorImagePatch.h" +#include "src/Tensor/TensorVolumePatch.h" +#include "src/Tensor/TensorBroadcasting.h" +#include "src/Tensor/TensorChipping.h" +#include "src/Tensor/TensorInflation.h" +#include "src/Tensor/TensorLayoutSwap.h" +#include "src/Tensor/TensorMorphing.h" +#include "src/Tensor/TensorPadding.h" +#include "src/Tensor/TensorReverse.h" +#include "src/Tensor/TensorShuffling.h" +#include "src/Tensor/TensorStriding.h" +#include "src/Tensor/TensorCustomOp.h" +#include "src/Tensor/TensorEvalTo.h" +#include "src/Tensor/TensorForcedEval.h" +#include "src/Tensor/TensorGenerator.h" +#include "src/Tensor/TensorAssign.h" +#include "src/Tensor/TensorScan.h" +#include "src/Tensor/TensorTrace.h" + +#ifdef EIGEN_USE_SYCL +#include "src/Tensor/TensorReductionSycl.h" +#include "src/Tensor/TensorConvolutionSycl.h" +#include "src/Tensor/TensorContractionSycl.h" +#include "src/Tensor/TensorScanSycl.h" +#endif + +#include "src/Tensor/TensorExecutor.h" +#include "src/Tensor/TensorDevice.h" + +#include "src/Tensor/TensorStorage.h" +#include "src/Tensor/Tensor.h" +#include "src/Tensor/TensorFixedSize.h" +#include "src/Tensor/TensorMap.h" +#include "src/Tensor/TensorRef.h" +// IWYU pragma: end_exports + +#include "../../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +//#endif // EIGEN_CXX11_TENSOR_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry new file mode 100644 index 0000000000000000000000000000000000000000..f559c26a6329ccd11250f26d3dda15a124ce17b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/TensorSymmetry @@ -0,0 +1,40 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSORSYMMETRY_MODULE_H +#define EIGEN_CXX11_TENSORSYMMETRY_MODULE_H + +#include "Tensor" + +#include "../../../Eigen/src/Core/util/DisableStupidWarnings.h" + +#include "src/util/CXX11Meta.h" + +/** \defgroup CXX11_TensorSymmetry_Module Tensor Symmetry Module + * + * This module provides a classes that allow for the definition of + * symmetries w.r.t. tensor indices. + * + * Including this module will implicitly include the Tensor module. + * + * \code + * #include + * \endcode + */ + +// IWYU pragma: begin_exports +#include "src/TensorSymmetry/util/TemplateGroupTheory.h" +#include "src/TensorSymmetry/Symmetry.h" +#include "src/TensorSymmetry/StaticSymmetry.h" +#include "src/TensorSymmetry/DynamicSymmetry.h" +// IWYU pragma: end_exports + +#include "../../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CXX11_TENSORSYMMETRY_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/ThreadPool b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/ThreadPool new file mode 100644 index 0000000000000000000000000000000000000000..9cdf2c0431a310309260be0b7d712e35170dddf2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/ThreadPool @@ -0,0 +1 @@ +#include "../../../Eigen/ThreadPool" \ No newline at end of file diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..9e4c1ed9c373d3199037937ed3a91dfb0bbac8cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_CXX11_TENSOR_MODULE_H +#error "Please include unsupported/Eigen/CXX11/Tensor instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..f873f2b9f68d62d2d2792630ffe6b3214a6d466c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/Tensor.h @@ -0,0 +1,465 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_H +#define EIGEN_CXX11_TENSOR_TENSOR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class Tensor + * \ingroup CXX11_Tensor_Module + * + * \brief The tensor class. + * + * The %Tensor class is the work-horse for all \em dense tensors within Eigen. + * + * The %Tensor class encompasses only dynamic-size objects so far. + * + * The first two template parameters are required: + * \tparam Scalar_ Numeric type, e.g. float, double, int or `std::complex`. + * User defined scalar types are supported as well (see \ref user_defined_scalars "here"). + * \tparam NumIndices_ Number of indices (i.e. rank of the tensor) + * + * The remaining template parameters are optional -- in most cases you don't have to worry about them. + * \tparam Options_ A combination of either \b #RowMajor or \b #ColMajor, and of either + * \b #AutoAlign or \b #DontAlign. + * The former controls \ref TopicStorageOrders "storage order", and defaults to column-major. The latter controls alignment, which is required + * for vectorization. It defaults to aligning tensors. Note that tensors currently do not support any operations that profit from vectorization. + * Support for such operations (i.e. adding two tensors etc.) is planned. + * + * You can access elements of tensors using normal subscripting: + * + * \code + * Eigen::Tensor t(10, 10, 10, 10); + * t(0, 1, 2, 3) = 42.0; + * \endcode + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_TENSOR_PLUGIN, + * \c EIGEN_TENSORBASE_PLUGIN, and \c EIGEN_READONLY_TENSORBASE_PLUGIN. + * + * Some notes: + * + *
+ *
Relation to other parts of Eigen:
+ *
The midterm development goal for this class is to have a similar hierarchy as Eigen uses for matrices, so that + * taking blocks or using tensors in expressions is easily possible, including an interface with the vector/matrix code + * by providing .asMatrix() and .asVector() (or similar) methods for rank 2 and 1 tensors. However, currently, the %Tensor + * class does not provide any of these features and is only available as a stand-alone class that just allows for + * coefficient access. Also, when fixed-size tensors are implemented, the number of template arguments is likely to + * change dramatically.
+ *
+ * + * \ref TopicStorageOrders + */ + +template +class Tensor : public TensorBase > +{ + public: + typedef Tensor Self; + typedef TensorBase > Base; + typedef typename Eigen::internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + typedef typename Base::CoeffReturnType CoeffReturnType; + + enum { + IsAligned = (EIGEN_MAX_ALIGN_BYTES>0) && !(Options_&DontAlign), + CoordAccess = true, + RawAccess = true + }; + + static constexpr int Layout = Options_ & RowMajor ? RowMajor : ColMajor; + static constexpr int Options = Options_; + static constexpr int NumIndices = NumIndices_; + typedef DSizes Dimensions; + + protected: + TensorStorage m_storage; + + template + struct isOfNormalIndex{ + static const bool is_array = internal::is_base_of, CustomIndices>::value; + static const bool is_int = NumTraits::IsInteger; + static const bool value = is_array | is_int; + }; + + public: + // Metadata + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rank() const { return NumIndices; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index dimension(std::size_t n) const { return m_storage.dimensions()[n]; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_storage.dimensions(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_storage.size(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar *data() { return m_storage.data(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar *data() const { return m_storage.data(); } + + // This makes EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + // work, because that uses base().coeffRef() - and we don't yet + // implement a similar class hierarchy + inline Self& base() { return *this; } + inline const Self& base() const { return *this; } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeff(array{{firstIndex, secondIndex, otherIndices...}}); + } + + // normal indices + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(const array& indices) const + { + eigen_internal_assert(checkIndexRange(indices)); + return m_storage.data()[linearizedIndex(indices)]; + } + + // custom indices + template::value) ) + > + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(CustomIndices& indices) const + { + return coeff(internal::customIndices2Array(indices)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff() const + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return m_storage.data()[0]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(Index index) const + { + eigen_internal_assert(index >= 0 && index < size()); + return m_storage.data()[index]; + } + + template + inline Scalar& coeffRef(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeffRef(array{{firstIndex, secondIndex, otherIndices...}}); + } + + // normal indices + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(const array& indices) + { + eigen_internal_assert(checkIndexRange(indices)); + return m_storage.data()[linearizedIndex(indices)]; + } + + // custom indices + template::value) ) + > + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(CustomIndices& indices) + { + return coeffRef(internal::customIndices2Array(indices)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return m_storage.data()[0]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) + { + eigen_internal_assert(index >= 0 && index < size()); + return m_storage.data()[index]; + } + + template + inline const Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return this->operator()(array{{firstIndex, secondIndex, otherIndices...}}); + } + + // custom indices + template::value) ) + > + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(CustomIndices& indices) const + { + return coeff(internal::customIndices2Array(indices)); + } + + // normal indices + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(const array& indices) const + { + return coeff(indices); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(Index index) const + { + eigen_internal_assert(index >= 0 && index < size()); + return coeff(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()() const + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeff(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator[](Index index) const + { + // The bracket operator is only for vectors, use the parenthesis operator instead. + EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeff(index); + } + + template + inline Scalar& operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return operator()(array{{firstIndex, secondIndex, otherIndices...}}); + } + + // normal indices + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(const array& indices) + { + return coeffRef(indices); + } + + // custom indices + template::value) ) + > + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(CustomIndices& indices) + { + return coeffRef(internal::customIndices2Array(indices)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(Index index) + { + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeffRef(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator[](Index index) + { + // The bracket operator is only for vectors, use the parenthesis operator instead + EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeffRef(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor() + : m_storage() + { + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor(const Self& other) + : Base(other), m_storage(other.m_storage) + { + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Tensor(Index firstDimension, IndexTypes... otherDimensions) + : m_storage(firstDimension, otherDimensions...) + { + // The number of dimensions used to construct a tensor must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherDimensions) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + } + + /** Normal Dimension */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit Tensor(const array& dimensions) + : m_storage(internal::array_prod(dimensions), dimensions) + { + EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor(const TensorBase& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other.derived()); + resize(TensorEvaluator(assign, DefaultDevice()).dimensions()); + internal::TensorExecutor::run(assign, DefaultDevice()); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor(const TensorBase& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other.derived()); + resize(TensorEvaluator(assign, DefaultDevice()).dimensions()); + internal::TensorExecutor::run(assign, DefaultDevice()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor(Self&& other) + : m_storage(std::move(other.m_storage)) + { + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor& operator=(Self&& other) + { + m_storage = std::move(other.m_storage); + return *this; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor& operator=(const Tensor& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other); + resize(TensorEvaluator(assign, DefaultDevice()).dimensions()); + internal::TensorExecutor::run(assign, DefaultDevice()); + return *this; + } + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Tensor& operator=(const OtherDerived& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other); + resize(TensorEvaluator(assign, DefaultDevice()).dimensions()); + internal::TensorExecutor::run(assign, DefaultDevice()); + return *this; + } + + template EIGEN_DEVICE_FUNC + void resize(Index firstDimension, IndexTypes... otherDimensions) + { + // The number of dimensions used to resize a tensor must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherDimensions) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + resize(array{{firstDimension, otherDimensions...}}); + } + + /** Normal Dimension */ + EIGEN_DEVICE_FUNC void resize(const array& dimensions) + { + int i; + Index size = Index(1); + for (i = 0; i < NumIndices; i++) { + internal::check_rows_cols_for_overflow::run(size, dimensions[i]); + size *= dimensions[i]; + } + #ifdef EIGEN_INITIALIZE_COEFFS + bool size_changed = size != this->size(); + m_storage.resize(size, dimensions); + if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + #else + m_storage.resize(size, dimensions); + #endif + } + + // Why this overload, DSizes is derived from array ??? // + EIGEN_DEVICE_FUNC void resize(const DSizes& dimensions) { + array dims; + for (int i = 0; i < NumIndices; ++i) { + dims[i] = dimensions[i]; + } + resize(dims); + } + + EIGEN_DEVICE_FUNC + void resize() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + // Nothing to do: rank 0 tensors have fixed size + } + + template + EIGEN_DEVICE_FUNC + void resize(const Eigen::IndexList& dimensions) { + array dims; + for (int i = 0; i < NumIndices; ++i) { + dims[i] = static_cast(dimensions[i]); + } + resize(dims); + } + + /** Custom Dimension */ + template::value) ) + > + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(CustomDimension& dimensions) + { + resize(internal::customIndices2Array(dimensions)); + } + +#ifndef EIGEN_EMULATE_CXX11_META_H + template + EIGEN_DEVICE_FUNC + void resize(const Sizes& dimensions) { + array dims; + for (int i = 0; i < NumIndices; ++i) { + dims[i] = static_cast(dimensions[i]); + } + resize(dims); + } +#else + template + EIGEN_DEVICE_FUNC + void resize(const Sizes& dimensions) { + array dims; + for (int i = 0; i < NumIndices; ++i) { + dims[i] = static_cast(dimensions[i]); + } + resize(dims); + } +#endif + + #ifdef EIGEN_TENSOR_PLUGIN + #include EIGEN_TENSOR_PLUGIN + #endif + + protected: + + bool checkIndexRange(const array& indices) const + { + using internal::array_apply_and_reduce; + using internal::array_zip_and_reduce; + using internal::greater_equal_zero_op; + using internal::logical_and_op; + using internal::lesser_op; + + return + // check whether the indices are all >= 0 + array_apply_and_reduce(indices) && + // check whether the indices fit in the dimensions + array_zip_and_reduce(indices, m_storage.dimensions()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index linearizedIndex(const array& indices) const + { + if (Options&RowMajor) { + return m_storage.dimensions().IndexOfRowMajor(indices); + } else { + return m_storage.dimensions().IndexOfColMajor(indices); + } + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h new file mode 100644 index 0000000000000000000000000000000000000000..1b642312a0743425e75cf8d69e1d27f143b4152b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h @@ -0,0 +1,318 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Eugene Brevdo +// Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H +#define EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +/** \class TensorIndexPair + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor + Index Pair class. + * + * + */ +template +struct traits > : public traits +{ + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef Pair Scalar; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorIndexPairOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, + typename eval >::type> +{ + typedef TensorIndexPairOp type; +}; + +} // end namespace internal + +template +class TensorIndexPairOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + typedef Pair CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorIndexPairOp(const XprType& expr) + : m_xpr(expr) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorIndexPairOp XprType; + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + typedef typename TensorEvaluator::Dimensions Dimensions; + static constexpr int NumDims = internal::array_size::value; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + enum { + IsAligned = /*TensorEvaluator::IsAligned*/ false, + PacketAccess = /*TensorEvaluator::PacketAccess*/ false, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + static constexpr int Layout = TensorEvaluator::Layout; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device) { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { + return m_impl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return CoeffReturnType(index, m_impl.coeff(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, 1); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + protected: + TensorEvaluator m_impl; +}; + +namespace internal { + +/** \class TensorPairIndex + * \ingroup CXX11_Tensor_Module + * + * \brief Converts to Tensor > and reduces to Tensor. + * + */ +template +struct traits > : public traits +{ + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef Index Scalar; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions - array_size::value; + static constexpr int Layout = XprTraits::Layout; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorPairReducerOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, + typename eval >::type> +{ + typedef TensorPairReducerOp type; +}; + +} // end namespace internal + +template +class TensorPairReducerOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + typedef Index CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorPairReducerOp(const XprType& expr, + const ReduceOp& reduce_op, + const Index return_dim, + const Dims& reduce_dims) + : m_xpr(expr), m_reduce_op(reduce_op), m_return_dim(return_dim), m_reduce_dims(reduce_dims) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_DEVICE_FUNC + const ReduceOp& reduce_op() const { return m_reduce_op; } + + EIGEN_DEVICE_FUNC + const Dims& reduce_dims() const { return m_reduce_dims; } + + EIGEN_DEVICE_FUNC + Index return_dim() const { return m_return_dim; } + + protected: + typename XprType::Nested m_xpr; + const ReduceOp m_reduce_op; + const Index m_return_dim; + const Dims m_reduce_dims; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorPairReducerOp XprType; + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename TensorIndexPairOp::CoeffReturnType PairType; + typedef typename TensorEvaluator >, Device>::Dimensions Dimensions; + typedef typename TensorEvaluator , Device>::Dimensions InputDimensions; + static constexpr int NumDims = internal::array_size::value; + typedef array StrideDims; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + typedef StorageMemory PairStorageMem; + + enum { + IsAligned = /*TensorEvaluator::IsAligned*/ false, + PacketAccess = /*TensorEvaluator::PacketAccess*/ false, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + static constexpr int Layout = TensorEvaluator>, Device>::Layout; + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_orig_impl(op.expression(), device), + m_impl(op.expression().index_pairs().reduce(op.reduce_dims(), op.reduce_op()), device), + m_return_dim(op.return_dim()) + { + gen_strides(m_orig_impl.dimensions(), m_strides); + if (Layout == static_cast(ColMajor)) { + const Index total_size = internal::array_prod(m_orig_impl.dimensions()); + m_stride_mod = (m_return_dim < NumDims - 1) ? m_strides[m_return_dim + 1] : total_size; + } else { + const Index total_size = internal::array_prod(m_orig_impl.dimensions()); + m_stride_mod = (m_return_dim > 0) ? m_strides[m_return_dim - 1] : total_size; + } + // If m_return_dim is not a valid index, returns 1 or this can crash on Windows. + m_stride_div = ((m_return_dim >= 0) && + (m_return_dim < static_cast(m_strides.size()))) + ? m_strides[m_return_dim] : 1; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { + return m_impl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + const PairType v = m_impl.coeff(index); + return (m_return_dim < 0) ? v.first : (v.first % m_stride_mod) / m_stride_div; + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double compute_cost = 1.0 + + (m_return_dim < 0 ? 0.0 : (TensorOpCost::ModCost() + TensorOpCost::DivCost())); + return m_orig_impl.costPerCoeff(vectorized) + + m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost); + } + + private: + EIGEN_DEVICE_FUNC void gen_strides(const InputDimensions& dims, StrideDims& strides) { + if (m_return_dim < 0) { + return; // Won't be using the strides. + } + eigen_assert(m_return_dim < NumDims && + "Asking to convert index to a dimension outside of the rank"); + + // Calculate m_stride_div and m_stride_mod, which are used to + // calculate the value of an index w.r.t. the m_return_dim. + if (Layout == static_cast(ColMajor)) { + strides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + strides[i] = strides[i-1] * dims[i-1]; + } + } else { + strides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + strides[i] = strides[i+1] * dims[i+1]; + } + } + } + + protected: + TensorEvaluator, Device> m_orig_impl; + TensorEvaluator >, Device> m_impl; + const Index m_return_dim; + StrideDims m_strides; + Index m_stride_mod; + Index m_stride_div; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_ARG_MAX_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h new file mode 100644 index 0000000000000000000000000000000000000000..d2f6ee258dafe7ea9214458412480dc89b6f4ced --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h @@ -0,0 +1,241 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H +#define EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorAssign + * \ingroup CXX11_Tensor_Module + * + * \brief The tensor assignment class. + * + * This class is represents the assignment of the values resulting from the evaluation of + * the rhs expression to the memory locations denoted by the lhs expression. + */ +namespace internal { +template +struct traits > +{ + typedef typename LhsXprType::Scalar Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename LhsXprType::Nested LhsNested; + typedef typename RhsXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + static constexpr std::size_t NumDimensions = internal::traits::NumDimensions; + static constexpr int Layout = internal::traits::Layout; + typedef typename traits::PointerType PointerType; + + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorAssignOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorAssignOp type; +}; + +} // end namespace internal + + + +template +class TensorAssignOp : public TensorBase > +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename LhsXprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + static constexpr int NumDims = Eigen::internal::traits::NumDimensions; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorAssignOp(LhsXprType& lhs, const RhsXprType& rhs) + : m_lhs_xpr(lhs), m_rhs_xpr(rhs) {} + + /** \returns the nested expressions */ + EIGEN_DEVICE_FUNC + internal::remove_all_t& + lhsExpression() const { return *((internal::remove_all_t*)&m_lhs_xpr); } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + rhsExpression() const { return m_rhs_xpr; } + + protected: + internal::remove_all_t& m_lhs_xpr; + const internal::remove_all_t& m_rhs_xpr; +}; + + +template +struct TensorEvaluator, Device> +{ + typedef TensorAssignOp XprType; + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int PacketSize = PacketType::size; + static constexpr int NumDims = XprType::NumDims; + static constexpr int Layout = TensorEvaluator::Layout; + + enum { + IsAligned = int(TensorEvaluator::IsAligned) & + int(TensorEvaluator::IsAligned), + PacketAccess = int(TensorEvaluator::PacketAccess) & + int(TensorEvaluator::PacketAccess), + BlockAccess = int(TensorEvaluator::BlockAccess) & + int(TensorEvaluator::BlockAccess), + PreferBlockAccess = int(TensorEvaluator::PreferBlockAccess) | + int(TensorEvaluator::PreferBlockAccess), + RawAccess = TensorEvaluator::RawAccess + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + RightTensorBlock; + //===--------------------------------------------------------------------===// + + TensorEvaluator(const XprType& op, const Device& device) : + m_leftImpl(op.lhsExpression(), device), + m_rightImpl(op.rhsExpression(), device) + { + EIGEN_STATIC_ASSERT( + (static_cast(TensorEvaluator::Layout) == + static_cast(TensorEvaluator::Layout)), + YOU_MADE_A_PROGRAMMING_MISTAKE); + } + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const + { + // The dimensions of the lhs and the rhs tensors should be equal to prevent + // overflows and ensure the result is fully initialized. + // TODO: use left impl instead if right impl dimensions are known at compile time. + return m_rightImpl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + eigen_assert(dimensions_match(m_leftImpl.dimensions(), m_rightImpl.dimensions())); + m_leftImpl.evalSubExprsIfNeeded(NULL); + // If the lhs provides raw access to its storage area (i.e. if m_leftImpl.data() returns a non + // null value), attempt to evaluate the rhs expression in place. Returns true iff in place + // evaluation isn't supported and the caller still needs to manually assign the values generated + // by the rhs to the lhs. + return m_rightImpl.evalSubExprsIfNeeded(m_leftImpl.data()); + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_leftImpl.evalSubExprsIfNeededAsync(nullptr, [this, done](bool) { + m_rightImpl.evalSubExprsIfNeededAsync( + m_leftImpl.data(), [done](bool need_assign) { done(need_assign); }); + }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_leftImpl.cleanup(); + m_rightImpl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalScalar(Index i) const { + m_leftImpl.coeffRef(i) = m_rightImpl.coeff(i); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalPacket(Index i) const { + + const int LhsStoreMode = TensorEvaluator::IsAligned ? Aligned : Unaligned; + const int RhsLoadMode = TensorEvaluator::IsAligned ? Aligned : Unaligned; + m_leftImpl.template writePacket(i, m_rightImpl.template packet(i)); + } + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_leftImpl.coeff(index); + } + template + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const + { + return m_leftImpl.template packet(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + // We assume that evalPacket or evalScalar is called to perform the + // assignment and account for the cost of the write here, but reduce left + // cost by one load because we are using m_leftImpl.coeffRef. + TensorOpCost left = m_leftImpl.costPerCoeff(vectorized); + return m_rightImpl.costPerCoeff(vectorized) + + TensorOpCost( + numext::maxi(0.0, left.bytes_loaded() - sizeof(CoeffReturnType)), + left.bytes_stored(), left.compute_cycles()) + + TensorOpCost(0, sizeof(CoeffReturnType), 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return internal::TensorBlockResourceRequirements::merge( + m_leftImpl.getResourceRequirements(), + m_rightImpl.getResourceRequirements()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalBlock( + TensorBlockDesc& desc, TensorBlockScratch& scratch) { + if (TensorEvaluator::RawAccess && + m_leftImpl.data() != NULL) { + // If destination has raw data access, we pass it as a potential + // destination for a block descriptor evaluation. + desc.template AddDestinationBuffer( + /*dst_base=*/m_leftImpl.data() + desc.offset(), + /*dst_strides=*/internal::strides(m_leftImpl.dimensions())); + } + + RightTensorBlock block = m_rightImpl.block(desc, scratch, /*root_of_expr_ast=*/true); + // If block was evaluated into a destination, there is no need to do assignment. + if (block.kind() != internal::TensorBlockKind::kMaterializedInOutput) { + m_leftImpl.writeBlock(desc, block); + } + block.cleanup(); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_leftImpl.data(); } + + private: + TensorEvaluator m_leftImpl; + TensorEvaluator m_rightImpl; +}; + +} + + +#endif // EIGEN_CXX11_TENSOR_TENSOR_ASSIGN_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h new file mode 100644 index 0000000000000000000000000000000000000000..9ca9ca183f7e03888ca6534da9e5eaf98e4dfc8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBase.h @@ -0,0 +1,1222 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_BASE_H +#define EIGEN_CXX11_TENSOR_TENSOR_BASE_H + +// clang-format off + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorBase + * \ingroup CXX11_Tensor_Module + * + * \brief The tensor base class. + * + * This class is the common parent of the Tensor and TensorMap class, thus + * making it possible to use either class interchangeably in expressions. + */ +#ifndef EIGEN_PARSED_BY_DOXYGEN +// FIXME Doxygen does not like the inheritance with different template parameters +// Since there is no doxygen documentation inside, we disable it for now +template +class TensorBase +{ + public: + typedef internal::traits DerivedTraits; + typedef typename DerivedTraits::Scalar Scalar; + typedef typename DerivedTraits::Index Index; + typedef std::remove_const_t CoeffReturnType; + static constexpr int NumDimensions = DerivedTraits::NumDimensions; + + // Generic nullary operation support. + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseNullaryOp + nullaryExpr(const CustomNullaryOp& func) const { + return TensorCwiseNullaryOp(derived(), func); + } + + // Coefficient-wise nullary operators + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseNullaryOp, const Derived> + constant(const Scalar& value) const { + return nullaryExpr(internal::scalar_constant_op(value)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseNullaryOp, const Derived> + random() const { + return nullaryExpr(internal::UniformRandomGenerator()); + } + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseNullaryOp + random(const RandomGenerator& gen = RandomGenerator()) const { + return nullaryExpr(gen); + } + + // Tensor generation + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorGeneratorOp + generate(const Generator& generator) const { + return TensorGeneratorOp(derived(), generator); + } + + // Generic unary operation support. + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp + unaryExpr(const CustomUnaryOp& func) const { + return TensorCwiseUnaryOp(derived(), func); + } + + // Coefficient-wise unary operators + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + operator-() const { + return unaryExpr(internal::scalar_opposite_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + sqrt() const { + return unaryExpr(internal::scalar_sqrt_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + sign() const { + return unaryExpr(internal::scalar_sign_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + rsqrt() const { + return unaryExpr(internal::scalar_rsqrt_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + square() const { + return unaryExpr(internal::scalar_square_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + cube() const { + return unaryExpr(internal::scalar_cube_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + inverse() const { + return unaryExpr(internal::scalar_inverse_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + tanh() const { + return unaryExpr(internal::scalar_tanh_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + lgamma() const { + return unaryExpr(internal::scalar_lgamma_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + digamma() const { + return unaryExpr(internal::scalar_digamma_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_i0() const { + return unaryExpr(internal::scalar_bessel_i0_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_i0e() const { + return unaryExpr(internal::scalar_bessel_i0e_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_i1() const { + return unaryExpr(internal::scalar_bessel_i1_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_i1e() const { + return unaryExpr(internal::scalar_bessel_i1e_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_j0() const { + return unaryExpr(internal::scalar_bessel_j0_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_y0() const { + return unaryExpr(internal::scalar_bessel_y0_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_j1() const { + return unaryExpr(internal::scalar_bessel_j1_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_y1() const { + return unaryExpr(internal::scalar_bessel_y1_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_k0() const { + return unaryExpr(internal::scalar_bessel_k0_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_k0e() const { + return unaryExpr(internal::scalar_bessel_k0e_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_k1() const { + return unaryExpr(internal::scalar_bessel_k1_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + bessel_k1e() const { + return unaryExpr(internal::scalar_bessel_k1e_op()); + } + + // igamma(a = this, x = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + igamma(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_igamma_op()); + } + + // igamma_der_a(a = this, x = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + igamma_der_a(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_igamma_der_a_op()); + } + + // gamma_sample_der_alpha(alpha = this, sample = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + gamma_sample_der_alpha(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_gamma_sample_der_alpha_op()); + } + + // igammac(a = this, x = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + igammac(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_igammac_op()); + } + + // zeta(x = this, q = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + zeta(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_zeta_op()); + } + + // polygamma(n = this, x = other) + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + polygamma(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_polygamma_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + erf() const { + return unaryExpr(internal::scalar_erf_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + erfc() const { + return unaryExpr(internal::scalar_erfc_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + ndtri() const { + return unaryExpr(internal::scalar_ndtri_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + sigmoid() const { + return unaryExpr(internal::scalar_logistic_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + exp() const { + return unaryExpr(internal::scalar_exp_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + expm1() const { + return unaryExpr(internal::scalar_expm1_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + log() const { + return unaryExpr(internal::scalar_log_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + log1p() const { + return unaryExpr(internal::scalar_log1p_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + log2() const { + return unaryExpr(internal::scalar_log2_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + abs() const { + return unaryExpr(internal::scalar_abs_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + arg() const { + return unaryExpr(internal::scalar_arg_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + clip(Scalar min, Scalar max) const { + return unaryExpr(internal::scalar_clamp_op(min, max)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const std::conditional_t::IsComplex, + TensorCwiseUnaryOp, const Derived>, + Derived> + conjugate() const { + return choose(Cond::IsComplex>(), unaryExpr(internal::scalar_conjugate_op()), derived()); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const std::enable_if_t::Real>::value, + TensorCwiseUnaryOp, const Derived>> + pow(ScalarExponent exponent) const + { + return unaryExpr(internal::scalar_unary_pow_op(exponent)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + real() const { + return unaryExpr(internal::scalar_real_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + imag() const { + return unaryExpr(internal::scalar_imag_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp >, const Derived> + operator+ (Scalar rhs) const { + return unaryExpr(internal::bind2nd_op >(rhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE friend + const TensorCwiseUnaryOp >, const Derived> + operator+ (Scalar lhs, const Derived& rhs) { + return rhs.unaryExpr(internal::bind1st_op >(lhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp >, const Derived> + operator- (Scalar rhs) const { + EIGEN_STATIC_ASSERT((NumTraits::IsSigned || internal::is_same >::value), YOU_MADE_A_PROGRAMMING_MISTAKE); + return unaryExpr(internal::bind2nd_op >(rhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE friend + const TensorCwiseUnaryOp >, const Derived> + operator- (Scalar lhs, const Derived& rhs) { + return rhs.unaryExpr(internal::bind1st_op >(lhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp >, const Derived> + operator* (Scalar rhs) const { + return unaryExpr(internal::bind2nd_op >(rhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE friend + const TensorCwiseUnaryOp >, const Derived> + operator* (Scalar lhs, const Derived& rhs) { + return rhs.unaryExpr(internal::bind1st_op >(lhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp >, const Derived> + operator/ (Scalar rhs) const { + return unaryExpr(internal::bind2nd_op >(rhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE friend + const TensorCwiseUnaryOp >, const Derived> + operator/ (Scalar lhs, const Derived& rhs) { + return rhs.unaryExpr(internal::bind1st_op >(lhs)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + operator% (Scalar rhs) const { + EIGEN_STATIC_ASSERT(NumTraits::IsInteger, YOU_MADE_A_PROGRAMMING_MISTAKE_TRY_MOD); + return unaryExpr(internal::scalar_mod_op(rhs)); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + cwiseMax(Scalar threshold) const { + return cwiseMax(constant(threshold)); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + cwiseMin(Scalar threshold) const { + return cwiseMin(constant(threshold)); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const std::conditional_t::value, + Derived, + TensorConversionOp > + cast() const { + return choose(Cond::value>(), derived(), TensorConversionOp(derived())); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + round() const { + return unaryExpr(internal::scalar_round_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + rint() const { + return unaryExpr(internal::scalar_rint_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + ceil() const { + return unaryExpr(internal::scalar_ceil_op()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + floor() const { + return unaryExpr(internal::scalar_floor_op()); + } + + // Generic binary operation support. + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp + binaryExpr(const OtherDerived& other, const CustomBinaryOp& func) const { + return TensorCwiseBinaryOp(derived(), other, func); + } + + // Coefficient-wise binary operators. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator+(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_sum_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator-(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_difference_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator*(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_product_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator/(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_quotient_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + cwiseMax(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_max_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + cwiseMin(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_min_op()); + } + + // logical operators + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator&&(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_boolean_and_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator||(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_boolean_or_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator&(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_bitwise_and_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator|(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_bitwise_or_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator^(const OtherDerived& other) const { + return binaryExpr(other.derived(), internal::scalar_bitwise_xor_op()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseUnaryOp, const Derived> + operator!() const { + return unaryExpr(internal::scalar_boolean_not_op()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseUnaryOp, const Derived> + operator~() const { + return unaryExpr(internal::scalar_bitwise_not_op()); + } + + // Comparisons and tests. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator<(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator<=(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator>(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator>=(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator==(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCwiseBinaryOp, const Derived, const OtherDerived> + operator!=(const TensorBase& other) const { + return binaryExpr(other.derived(), internal::scalar_cmp_op()); + } + + // comparisons and tests for Scalars + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator<(Scalar threshold) const { + return operator<(constant(threshold)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator<=(Scalar threshold) const { + return operator<=(constant(threshold)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator>(Scalar threshold) const { + return operator>(constant(threshold)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator>=(Scalar threshold) const { + return operator>=(constant(threshold)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator==(Scalar threshold) const { + return operator==(constant(threshold)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseBinaryOp, const Derived, const TensorCwiseNullaryOp, const Derived> > + operator!=(Scalar threshold) const { + return operator!=(constant(threshold)); + } + + // Predicates. + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorConversionOp, const Derived>> + (isnan)() const { + return unaryExpr(internal::scalar_isnan_op()).template cast(); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + (isinf)() const { + return unaryExpr(internal::scalar_isinf_op()); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const TensorCwiseUnaryOp, const Derived> + (isfinite)() const { + return unaryExpr(internal::scalar_isfinite_op()); + } + + // Coefficient-wise ternary operators. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorSelectOp + select(const ThenDerived& thenTensor, const ElseDerived& elseTensor) const { + return TensorSelectOp(derived(), thenTensor.derived(), elseTensor.derived()); + } + + // Contractions. + typedef Eigen::IndexPair DimensionPair; + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorContractionOp + contract(const OtherDerived& other, const Dimensions& dims) const { + return TensorContractionOp(derived(), other.derived(), dims); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorContractionOp + contract(const OtherDerived& other, const Dimensions& dims, const OutputKernel& output_kernel) const { + return TensorContractionOp(derived(), other.derived(), dims, output_kernel); + } + + // Convolutions. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorConvolutionOp + convolve(const KernelDerived& kernel, const Dimensions& dims) const { + return TensorConvolutionOp(derived(), kernel.derived(), dims); + } + + // Fourier transforms + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorFFTOp + fft(const FFT& dims) const { + return TensorFFTOp(derived(), dims); + } + + // Scan. + typedef TensorScanOp, const Derived> TensorScanSumOp; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorScanSumOp + cumsum(const Index& axis, bool exclusive = false) const { + return TensorScanSumOp(derived(), axis, exclusive); + } + + typedef TensorScanOp, const Derived> TensorScanProdOp; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorScanProdOp + cumprod(const Index& axis, bool exclusive = false) const { + return TensorScanProdOp(derived(), axis, exclusive); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorScanOp + scan(const Index& axis, const Reducer& reducer, bool exclusive = false) const { + return TensorScanOp(derived(), axis, exclusive, reducer); + } + + // Reductions. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const Dims, const Derived> + sum(const Dims& dims) const { + return TensorReductionOp, const Dims, const Derived>(derived(), dims, internal::SumReducer()); + } + + const TensorReductionOp, const DimensionList, const Derived> + sum() const { + DimensionList in_dims; + return TensorReductionOp, const DimensionList, const Derived>(derived(), in_dims, internal::SumReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const Dims, const Derived> + mean(const Dims& dims) const { + return TensorReductionOp, const Dims, const Derived>(derived(), dims, internal::MeanReducer()); + } + + const TensorReductionOp, const DimensionList, const Derived> + mean() const { + DimensionList in_dims; + return TensorReductionOp, const DimensionList, const Derived>(derived(), in_dims, internal::MeanReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const Dims, const Derived> + prod(const Dims& dims) const { + return TensorReductionOp, const Dims, const Derived>(derived(), dims, internal::ProdReducer()); + } + + const TensorReductionOp, const DimensionList, const Derived> + prod() const { + DimensionList in_dims; + return TensorReductionOp, const DimensionList, const Derived>(derived(), in_dims, internal::ProdReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const Dims, const Derived> + maximum(const Dims& dims) const { + return TensorReductionOp, const Dims, const Derived>(derived(), dims, internal::MaxReducer()); + } + + template + const TensorReductionOp, const DimensionList, const Derived> + maximum() const { + DimensionList in_dims; + return TensorReductionOp, const DimensionList, const Derived>(derived(), in_dims, internal::MaxReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const Dims, const Derived> + minimum(const Dims& dims) const { + return TensorReductionOp, const Dims, const Derived>(derived(), dims, internal::MinReducer()); + } + + template + const TensorReductionOp, const DimensionList, const Derived> + minimum() const { + DimensionList in_dims; + return TensorReductionOp, const DimensionList, const Derived>(derived(), in_dims, internal::MinReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp::value, Derived, TensorConversionOp > > + all(const Dims& dims) const { + return cast().reduce(dims, internal::AndReducer()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const std::conditional_t::value, Derived, TensorConversionOp > > + all() const { + DimensionList in_dims; + return cast().reduce(in_dims, internal::AndReducer()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp::value, Derived, TensorConversionOp > > + any(const Dims& dims) const { + return cast().reduce(dims, internal::OrReducer()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp, const std::conditional_t::value, Derived, TensorConversionOp > > + any() const { + DimensionList in_dims; + return cast().reduce(in_dims, internal::OrReducer()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPairReducerOp< + internal::ArgMaxPairReducer >, + const array, const Derived> + argmax() const { + array in_dims; + for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d; + return TensorPairReducerOp< + internal::ArgMaxPairReducer >, + const array, + const Derived>(derived(), internal::ArgMaxPairReducer >(), -1, in_dims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPairReducerOp< + internal::ArgMinPairReducer >, + const array, const Derived> + argmin() const { + array in_dims; + for (Index d = 0; d < NumDimensions; ++d) in_dims[d] = d; + return TensorPairReducerOp< + internal::ArgMinPairReducer >, + const array, + const Derived>(derived(), internal::ArgMinPairReducer >(), -1, in_dims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPairReducerOp< + internal::ArgMaxPairReducer >, + const array, const Derived> + argmax(const Index return_dim) const { + array in_dims; + in_dims[0] = return_dim; + return TensorPairReducerOp< + internal::ArgMaxPairReducer >, + const array, + const Derived>(derived(), internal::ArgMaxPairReducer >(), return_dim, in_dims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPairReducerOp< + internal::ArgMinPairReducer >, + const array, const Derived> + argmin(const Index return_dim) const { + array in_dims; + in_dims[0] = return_dim; + return TensorPairReducerOp< + internal::ArgMinPairReducer >, + const array, + const Derived>(derived(), internal::ArgMinPairReducer >(), return_dim, in_dims); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReductionOp + reduce(const Dims& dims, const Reducer& reducer) const { + return TensorReductionOp(derived(), dims, reducer); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorTraceOp + trace(const Dims& dims) const { + return TensorTraceOp(derived(), dims); + } + + const TensorTraceOp, const Derived> + trace() const { + DimensionList in_dims; + return TensorTraceOp, const Derived>(derived(), in_dims); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorBroadcastingOp + broadcast(const Broadcast& bcast) const { + return TensorBroadcastingOp(derived(), bcast); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorConcatenationOp + concatenate(const OtherDerived& other, Axis axis) const { + return TensorConcatenationOp(derived(), other.derived(), axis); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPatchOp + extract_patches(const PatchDims& patch_dims) const { + return TensorPatchOp(derived(), patch_dims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorImagePatchOp + extract_image_patches(const Index patch_rows = 1, const Index patch_cols = 1, + const Index row_stride = 1, const Index col_stride = 1, + const Index in_row_stride = 1, const Index in_col_stride = 1, + const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const { + return TensorImagePatchOp(derived(), patch_rows, patch_cols, row_stride, col_stride, + in_row_stride, in_col_stride, 1, 1, padding_type, padding_value); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorImagePatchOp + extract_image_patches(const Index patch_rows, const Index patch_cols, + const Index row_stride, const Index col_stride, + const Index in_row_stride, const Index in_col_stride, + const Index row_inflate_stride, const Index col_inflate_stride, + const Index padding_top, const Index padding_bottom, + const Index padding_left,const Index padding_right, + const Scalar padding_value) const { + return TensorImagePatchOp(derived(), patch_rows, patch_cols, row_stride, col_stride, + in_row_stride, in_col_stride, row_inflate_stride, col_inflate_stride, + padding_top, padding_bottom, padding_left, padding_right, padding_value); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorVolumePatchOp + extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols, + const Index plane_stride = 1, const Index row_stride = 1, const Index col_stride = 1, + const PaddingType padding_type = PADDING_SAME, const Scalar padding_value = Scalar(0)) const { + return TensorVolumePatchOp(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, 1, 1, 1, padding_type, padding_value); + } + + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorVolumePatchOp + extract_volume_patches(const Index patch_planes, const Index patch_rows, const Index patch_cols, + const Index plane_stride, const Index row_stride, const Index col_stride, + const Index plane_inflate_stride, const Index row_inflate_stride, const Index col_inflate_stride, + const Index padding_top_z, const Index padding_bottom_z, + const Index padding_top, const Index padding_bottom, + const Index padding_left, const Index padding_right, const Scalar padding_value = Scalar(0)) const { + return TensorVolumePatchOp(derived(), patch_planes, patch_rows, patch_cols, plane_stride, row_stride, col_stride, 1, 1, 1, plane_inflate_stride, row_inflate_stride, col_inflate_stride, padding_top_z, padding_bottom_z, padding_top, padding_bottom, padding_left, padding_right, padding_value); + } + + // Morphing operators. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorLayoutSwapOp + swap_layout() const { + return TensorLayoutSwapOp(derived()); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReshapingOp + reshape(const NewDimensions& newDimensions) const { + return TensorReshapingOp(derived(), newDimensions); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorSlicingOp + slice(const StartIndices& startIndices, const Sizes& sizes) const { + return TensorSlicingOp(derived(), startIndices, sizes); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorStridingSlicingOp + stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const { + return TensorStridingSlicingOp(derived(), startIndices, stopIndices, strides); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorChippingOp + chip(const Index offset) const { + return TensorChippingOp(derived(), offset, DimId); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorChippingOp + chip(const Index offset, const Index dim) const { + return TensorChippingOp(derived(), offset, dim); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReverseOp + reverse(const ReverseDimensions& rev) const { + return TensorReverseOp(derived(), rev); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPaddingOp + pad(const PaddingDimensions& padding) const { + return TensorPaddingOp(derived(), padding, internal::scalar_cast_op()(0)); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorPaddingOp + pad(const PaddingDimensions& padding, const Scalar padding_value) const { + return TensorPaddingOp(derived(), padding, padding_value); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorShufflingOp + shuffle(const Shuffle& shfl) const { + return TensorShufflingOp(derived(), shfl); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorStridingOp + stride(const Strides& strides) const { + return TensorStridingOp(derived(), strides); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorInflationOp + inflate(const Strides& strides) const { + return TensorInflationOp(derived(), strides); + } + + // Returns a tensor containing index/value pairs + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorIndexPairOp + index_pairs() const { + return TensorIndexPairOp(derived()); + } + + // Support for custom unary and binary operations + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCustomUnaryOp customOp(const CustomUnaryFunc& op) const { + return TensorCustomUnaryOp(derived(), op); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorCustomBinaryOp customOp(const OtherDerived& other, const CustomBinaryFunc& op) const { + return TensorCustomBinaryOp(derived(), other, op); + } + + // Force the evaluation of the expression. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorForcedEvalOp eval() const { + return TensorForcedEvalOp(derived()); + } + + // Returns a formatted tensor ready for printing to a stream + inline const TensorWithFormat format(const TensorIOFormat& fmt) const { + return TensorWithFormat(derived(), fmt); + } + + #ifdef EIGEN_READONLY_TENSORBASE_PLUGIN + #include EIGEN_READONLY_TENSORBASE_PLUGIN + #endif + + protected: + template friend class Tensor; + template friend class TensorFixedSize; + // the Eigen:: prefix is required to workaround a compilation issue with nvcc 9.0 + template friend class Eigen::TensorBase; + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast(this); } +}; + +template::value> +class TensorBase : public TensorBase { + public: + typedef TensorBase Base; + typedef internal::traits DerivedTraits; + typedef typename DerivedTraits::Scalar Scalar; + typedef typename DerivedTraits::Index Index; + typedef Scalar CoeffReturnType; + static constexpr int NumDimensions = DerivedTraits::NumDimensions; + + template friend class Tensor; + template friend class TensorFixedSize; + // the Eigen:: prefix is required to workaround a compilation issue with nvcc 9.0 + template friend class Eigen::TensorBase; + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& setZero() { + return setConstant(Scalar(0)); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& setConstant(const Scalar& val) { + return derived() = this->constant(val); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& setRandom() { + return derived() = this->random(); + } + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& setRandom() { + return derived() = this->template random(); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& setValues( + const typename internal::Initializer::InitList& vals) { + TensorEvaluator eval(derived(), DefaultDevice()); + internal::initialize_tensor(eval, vals); + return derived(); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator+=(const OtherDerived& other) { + return derived() = derived() + other.derived(); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator-=(const OtherDerived& other) { + return derived() = derived() - other.derived(); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator*=(const OtherDerived& other) { + return derived() = derived() * other.derived(); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator/=(const OtherDerived& other) { + return derived() = derived() / other.derived(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorLayoutSwapOp + swap_layout() const { + return TensorLayoutSwapOp(derived()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorLayoutSwapOp + swap_layout() { + return TensorLayoutSwapOp(derived()); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorConcatenationOp + concatenate(const OtherDerived& other, const Axis& axis) const { + return TensorConcatenationOp(derived(), other, axis); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorConcatenationOp + concatenate(const OtherDerived& other, const Axis& axis) { + return TensorConcatenationOp(derived(), other, axis); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReshapingOp + reshape(const NewDimensions& newDimensions) const { + return TensorReshapingOp(derived(), newDimensions); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorReshapingOp + reshape(const NewDimensions& newDimensions) { + return TensorReshapingOp(derived(), newDimensions); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorSlicingOp + slice(const StartIndices& startIndices, const Sizes& sizes) const { + return TensorSlicingOp(derived(), startIndices, sizes); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorSlicingOp + slice(const StartIndices& startIndices, const Sizes& sizes) { + return TensorSlicingOp(derived(), startIndices, sizes); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorStridingSlicingOp + stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) const { + return TensorStridingSlicingOp(derived(), startIndices, stopIndices, strides); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorStridingSlicingOp + stridedSlice(const StartIndices& startIndices, const StopIndices& stopIndices, const Strides& strides) { + return TensorStridingSlicingOp(derived(), startIndices, stopIndices, strides); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorChippingOp + chip(const Index offset) const { + return TensorChippingOp(derived(), offset, DimId); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorChippingOp + chip(const Index offset) { + return TensorChippingOp(derived(), offset, DimId); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorChippingOp + chip(const Index offset, const Index dim) const { + return TensorChippingOp(derived(), offset, dim); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorChippingOp + chip(const Index offset, const Index dim) { + return TensorChippingOp(derived(), offset, dim); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorReverseOp + reverse(const ReverseDimensions& rev) const { + return TensorReverseOp(derived(), rev); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorReverseOp + reverse(const ReverseDimensions& rev) { + return TensorReverseOp(derived(), rev); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorShufflingOp + shuffle(const Shuffle& shfl) const { + return TensorShufflingOp(derived(), shfl); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorShufflingOp + shuffle(const Shuffle& shfl) { + return TensorShufflingOp(derived(), shfl); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const TensorStridingOp + stride(const Strides& strides) const { + return TensorStridingOp(derived(), strides); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorStridingOp + stride(const Strides& strides) { + return TensorStridingOp(derived(), strides); + } + + // Select the device on which to evaluate the expression. + template + TensorDevice device(const DeviceType& dev) { + return TensorDevice(dev, derived()); + } + + // Select the async device on which to evaluate the expression. + template + TensorAsyncDevice device(const DeviceType& dev, DoneCallback done) { + return TensorAsyncDevice(dev, derived(), std::move(done)); + } + + #ifdef EIGEN_TENSORBASE_PLUGIN + #include EIGEN_TENSORBASE_PLUGIN + #endif + + protected: + EIGEN_DEFAULT_EMPTY_CONSTRUCTOR_AND_DESTRUCTOR(TensorBase) + EIGEN_DEFAULT_COPY_CONSTRUCTOR(TensorBase) + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& operator=(const OtherDerived& other) + { + typedef TensorAssignOp Assign; + Assign assign(derived(), other.derived()); + internal::TensorExecutor::run(assign, DefaultDevice()); + return derived(); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& derived() { return *static_cast(this); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Derived& derived() const { return *static_cast(this); } +}; +#endif // EIGEN_PARSED_BY_DOXYGEN +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_BASE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h new file mode 100644 index 0000000000000000000000000000000000000000..7e9248796f4cceafd0f0d6d469d09bedc6f25bb9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h @@ -0,0 +1,1607 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H +#define EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +// -------------------------------------------------------------------------- // +// Forward declarations for templates defined below. +template +class TensorBlockIO; + +// -------------------------------------------------------------------------- // +// Helper function to compute strides for densely stored buffer of given +// dimensions. + +// TODO(ezhulenev): We compute strides 1000 times in different evaluators, use +// this function instead everywhere. +template +EIGEN_ALWAYS_INLINE DSizes strides( + const DSizes& dimensions) { + DSizes strides; + if (NumDims == 0) return strides; + + // TODO(ezhulenev): Use templates to unroll this loop (similar to + // h_array_reduce in CXX11meta.h)? Benchmark it. + if (static_cast(Layout) == static_cast(ColMajor)) { + strides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + strides[i] = strides[i - 1] * dimensions[i - 1]; + } + } else { + strides[NumDims - 1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + strides[i] = strides[i + 1] * dimensions[i + 1]; + } + } + + return strides; +} + +template +EIGEN_ALWAYS_INLINE DSizes strides( + const Eigen::array& dimensions) { + return strides(DSizes(dimensions)); +} + +template +EIGEN_STRONG_INLINE DSizes strides( + const Sizes& sizes) { + return strides(DSizes(sizes)); +} + +// -------------------------------------------------------------------------- // + +// Tensor block shape type defines what are the shape preference for the blocks +// extracted from the larger tensor. +// +// Example: blocks of 100 elements from the large 100x100 tensor: +// - tensor: 100x100 +// - target_block_size: 100 +// +// TensorBlockShapeType: +// - kUniformAllDims: 100 blocks of size 10x10 +// - kSkewedInnerDims: 100 blocks of size 100x1 (or 1x100 depending on a column +// or row major layout) +enum class TensorBlockShapeType { kUniformAllDims, kSkewedInnerDims }; + +struct TensorBlockResourceRequirements { + TensorBlockShapeType shape_type; // target block shape + size_t size; // target block size + TensorOpCost cost_per_coeff; // cost of computing a single block element + +#ifdef EIGEN_HIPCC + // For HIPCC, we need to explicitly declare as a "device fun", the constructor + // which is implicitly invoked in the "merge" / "any" routines. else HIPCC + // errors out complaining about the lack of a matching constructor + EIGEN_DEVICE_FUNC + TensorBlockResourceRequirements(TensorBlockShapeType shape_type_, size_t size_, + TensorOpCost cost_) + : shape_type(shape_type_), size(size_), cost_per_coeff(cost_) + {} +#endif + + template + EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements withShapeAndSize( + TensorBlockShapeType shape_type, size_t size_in_bytes, + TensorOpCost cost) { + const size_t size = numext::maxi(size_t(1), size_in_bytes / sizeof(Scalar)); + return {shape_type, size, cost}; + } + + template + EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements withShapeAndSize( + TensorBlockShapeType shape_type, size_t size_in_bytes) { + // This default cost per coefficient is valid for most materialized tensor + // block evaluation implementations, because they typically just read + // coefficients from the underlying tensor storage, and write to the tensor + // block buffer (scratch or destination memory, reads and writes have linear + // access pattern). We ignore the fixed cost of block evaluation, because in + // practice it should negligible. + // + // Lazy block evaluation adds the cost of calling a functor for each + // coefficient. + // + // All non-trivial block evaluation implementations must provide their own + // cost approximation (e.g. shuffling inner dimension has a much higher cost + // because it reads memory randomly, although the total number of moved + // bytes is the same). + return withShapeAndSize(shape_type, size_in_bytes, + {/*bytes_loaded=*/sizeof(Scalar), + /*bytes_stored=*/sizeof(Scalar), + /*compute_cycles=*/0}); + } + + template + EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements skewed( + size_t size_in_bytes) { + return withShapeAndSize(TensorBlockShapeType::kSkewedInnerDims, + size_in_bytes); + } + + template + EIGEN_DEVICE_FUNC static TensorBlockResourceRequirements uniform( + size_t size_in_bytes) { + return withShapeAndSize(TensorBlockShapeType::kUniformAllDims, + size_in_bytes); + } + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE TensorBlockResourceRequirements + merge(const TensorBlockResourceRequirements& lhs, + const TensorBlockResourceRequirements& rhs) { + return {merge(lhs.shape_type, rhs.shape_type), // shape_type + merge(lhs.size, rhs.size), // size + merge(lhs.cost_per_coeff, rhs.cost_per_coeff)}; // cost_per_coeff + } + + EIGEN_DEVICE_FUNC TensorBlockResourceRequirements& addCostPerCoeff( + TensorOpCost cost) { + cost_per_coeff += cost; + return *this; + } + + // This is a resource requirement that should be returned from expressions + // that do not have any block evaluation preference (e.g. default tensor + // expression with raw buffer access). + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE TensorBlockResourceRequirements any() { + return {TensorBlockShapeType::kUniformAllDims, 1, {0, 0, 0}}; + } + + private: + using Requirements = TensorBlockResourceRequirements; + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE size_t merge(size_t lhs_size, size_t rhs_size) { + return numext::maxi(lhs_size, rhs_size); + } + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE TensorBlockShapeType + merge(TensorBlockShapeType lhs, TensorBlockShapeType rhs) { + return (lhs == TensorBlockShapeType::kSkewedInnerDims || + rhs == TensorBlockShapeType::kSkewedInnerDims) + ? TensorBlockShapeType::kSkewedInnerDims + : TensorBlockShapeType::kUniformAllDims; + } + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE TensorOpCost merge(TensorOpCost lhs_cost, + TensorOpCost rhs_cost) { + return lhs_cost + rhs_cost; + } +}; + +// -------------------------------------------------------------------------- // +// TensorBlockDescriptor specifies a block offset within a tensor and the block +// sizes along each of the tensor dimensions. + +template +class TensorBlockDescriptor { + public: + typedef DSizes Dimensions; + + // If we evaluate a Tensor assignment, and expression on the left, already has + // a memory buffer, then we might do performance optimization, and evaluate + // the root expression directly into the final output memory. Some time it's + // possible to reuse it for materializing subexpressions inside an expression + // tree, to to avoid dynamic memory allocation. + // + // The pointer type of the underlying storage is erased, because passing + // Scalar type through all the expression evaluation layers is way too many + // templates. In practice destination buffer type should always match the + // evaluated expression scalar type. + class DestinationBuffer { + public: + enum DestinationBufferKind : int { + // The above explicit specification of "int" as the enum basetype is + // needed to get around a HIPCC link error ("the field type is not + // amp-compatible") + // which is issued for class members with the enum type. + // TODO(rocm): + // remove the "int" basetype once HIPCC has been fixed to not error out + // in the above scenario. + + // Destination buffer is not defined (`m_data` == nullptr). + kEmpty, + + // Tensor block defined by an owning tensor block descriptor can fit + // contiguously into the destination buffer. In this case it's safe to + // materialize tensor block in the destination buffer, wrap it in a + // TensorMap, and use to build Eigen expression on top of it. + kContiguous, + + // Destination buffer strides do not match strides of the contiguously + // stored block, and it's impossible to define a TensorMap over this + // buffer. However if we are evaluating a root of an expression tree, we + // still can materialize an output into this destination, because we can + // guarantee that no one will ever access it through block API. + // + // In theory it is possible to build valid TensorStriding + // expression on top of this destination buffer, however it has + // inefficient coeff/packet access, and defeats the purpose of fast block + // evaluation API. + kStrided + }; + + template + Scalar* data() const { + eigen_assert(m_data_type_size == sizeof(Scalar)); + return static_cast(m_data); + } + + const Dimensions& strides() const { return m_strides; } + const DestinationBufferKind& kind() const { return m_kind; } + + private: + friend class TensorBlockDescriptor; + + DestinationBuffer() : m_data(NULL), m_data_type_size(0), m_kind(kEmpty) {} + + template + DestinationBuffer(Scalar* data, const Dimensions& strides, + DestinationBufferKind kind) + : m_data(static_cast(data)), + m_data_type_size(sizeof(Scalar)), + m_strides(strides), + m_kind(kind) {} + + template + static DestinationBuffer make(const TensorBlockDescriptor& desc, + Scalar* data, const Dimensions& strides) { + return DestinationBuffer(data, strides, kind(desc, strides)); + } + + template + static DestinationBufferKind kind(const TensorBlockDescriptor& desc, + const Dimensions& strides) { + const Dimensions& desc_dims = desc.dimensions(); + const Dimensions& desc_strides = internal::strides(desc_dims); + for (int i = 0; i < NumDims; ++i) { + if (desc_dims[i] == 1) continue; + if (desc_strides[i] != strides[i]) return kStrided; + } + return kContiguous; + } + + // Storage pointer is type erased, to reduce template bloat, but we still + // keep the size of the underlying element type for error checking. + void* m_data; + size_t m_data_type_size; + + // Destination buffer dimensions always match the dimensions of a tensor + // block descriptor it belongs to, however strides might be different. + Dimensions m_strides; + + DestinationBufferKind m_kind; + }; + + TensorBlockDescriptor(const IndexType offset, const Dimensions& dimensions, + const DestinationBuffer& destination) + : m_offset(offset), + m_dimensions(dimensions), + m_destination(destination) {} + + TensorBlockDescriptor(const IndexType offset, const Dimensions& dimensions) + : m_offset(offset), + m_dimensions(dimensions), + m_destination(DestinationBuffer()) {} + + IndexType offset() const { return m_offset; } + const Dimensions& dimensions() const { return m_dimensions; } + IndexType dimension(int index) const { return m_dimensions[index]; } + IndexType size() const { return array_prod(m_dimensions); } + + const DestinationBuffer& destination() const { return m_destination; } + + template + void AddDestinationBuffer(Scalar* dst_base, const Dimensions& dst_strides) { + eigen_assert(dst_base != NULL); + m_destination = + DestinationBuffer::template make(*this, dst_base, dst_strides); + } + + template + void AddDestinationBuffer( + Scalar* dst_base, + const DSizes& dst_strides) { + // DSizes constructor will do index type promotion if it's safe. + AddDestinationBuffer(dst_base, Dimensions(dst_strides)); + } + + TensorBlockDescriptor& DropDestinationBuffer() { + m_destination.m_data = NULL; + m_destination.m_kind = DestinationBuffer::kEmpty; + return *this; + } + + bool HasDestinationBuffer() const { + return m_destination.kind() != DestinationBuffer::kEmpty; + } + + // Returns a copy of `*this` with updated offset. + TensorBlockDescriptor WithOffset(IndexType offset) const { + return TensorBlockDescriptor(offset, m_dimensions, m_destination); + } + + private: + // Offset and dimensions are immutable after construction. Block descriptor + // can only be mutated by adding or dropping destination. + const IndexType m_offset; + const Dimensions m_dimensions; + DestinationBuffer m_destination; +}; + +// -------------------------------------------------------------------------- // +// TensorBlockMapper is responsible for iterating over the blocks of a tensor. + +template +class TensorBlockMapper { + typedef TensorBlockDescriptor BlockDescriptor; + + public: + typedef DSizes Dimensions; + + TensorBlockMapper() = default; + TensorBlockMapper(const DSizes& dimensions, + const TensorBlockResourceRequirements& requirements) + : m_tensor_dimensions(dimensions), m_requirements(requirements) { + // Compute block dimensions and the total number of blocks. + InitializeBlockDimensions(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockCount() const { + return m_total_block_count; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockTotalSize() const { + return m_block_dimensions.TotalSize(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const DSizes& + blockDimensions() const { + return m_block_dimensions; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockDescriptor + blockDescriptor(IndexType block_index) const { + static const bool isColMajor = Layout == static_cast(ColMajor); + + IndexType offset = 0; + DSizes dimensions; + + if (NumDims == 0) return BlockDescriptor(offset, dimensions); + + // Iterate outer -> inner dimensions. + for (int i = NumDims - 1; i >= 0; --i) { + const int dim = isColMajor ? i : NumDims - i - 1; + + const IndexType idx = block_index / m_block_strides[dim]; + block_index -= idx * m_block_strides[dim]; + + const IndexType coord = idx * m_block_dimensions[dim]; + dimensions[dim] = numext::mini(m_tensor_dimensions[dim] - coord, + m_block_dimensions[dim]); + offset += coord * m_tensor_strides[dim]; + } + + return {offset, dimensions}; + } + + private: + void InitializeBlockDimensions() { + // Requested block shape and size. + const TensorBlockShapeType shape_type = m_requirements.shape_type; + IndexType target_block_size = + numext::maxi(1, static_cast(m_requirements.size)); + + IndexType tensor_size = m_tensor_dimensions.TotalSize(); + + // Corner case: one of the dimensions is zero. Logic below is too complex + // to handle this case on a general basis, just use unit block size. + // Note: we must not yield blocks with zero dimensions (recipe for + // overflows/underflows, divisions by zero and NaNs later). + if (tensor_size == 0) { + for (int i = 0; i < NumDims; ++i) { + m_block_dimensions[i] = 1; + } + m_total_block_count = 0; + return; + } + + // If tensor fits into a target block size, evaluate it as a single block. + if (tensor_size <= target_block_size) { + m_block_dimensions = m_tensor_dimensions; + m_total_block_count = 1; + // The only valid block index is `0`, and in this case we do not need + // to compute real strides for tensor or blocks (see blockDescriptor). + for (int i = 0; i < NumDims; ++i) { + m_tensor_strides[i] = 0; + m_block_strides[i] = 1; + } + return; + } + + static const bool isColMajor = Layout == static_cast(ColMajor); + + // Block shape skewed towards inner dimension. + if (shape_type == TensorBlockShapeType::kSkewedInnerDims) { + IndexType coeff_to_allocate = target_block_size; + + for (int i = 0; i < NumDims; ++i) { + const int dim = isColMajor ? i : NumDims - i - 1; + m_block_dimensions[dim] = + numext::mini(coeff_to_allocate, m_tensor_dimensions[dim]); + coeff_to_allocate = divup( + coeff_to_allocate, + numext::maxi(static_cast(1), m_block_dimensions[dim])); + } + eigen_assert(coeff_to_allocate == 1); + + } else if (shape_type == TensorBlockShapeType::kUniformAllDims) { + // Tensor will not fit within 'target_block_size' budget: calculate tensor + // block dimension sizes based on "square" dimension size target. + const IndexType dim_size_target = convert_index( + std::pow(static_cast(target_block_size), + 1.0f / static_cast(m_block_dimensions.rank()))); + + for (int i = 0; i < NumDims; ++i) { + // TODO(andydavis) Adjust the inner most 'block_dim_size' to make it + // a multiple of the packet size. Note that reducing + // 'block_dim_size' in this manner can increase the number of + // blocks, and so will amplify any per-block overhead. + m_block_dimensions[i] = + numext::mini(dim_size_target, m_tensor_dimensions[i]); + } + + // Add any un-allocated coefficients to inner dimension(s). + IndexType total_size = m_block_dimensions.TotalSize(); + for (int i = 0; i < NumDims; ++i) { + const int dim = isColMajor ? i : NumDims - i - 1; + + if (m_block_dimensions[dim] < m_tensor_dimensions[dim]) { + const IndexType total_size_other_dims = + total_size / m_block_dimensions[dim]; + const IndexType alloc_avail = + divup(target_block_size, total_size_other_dims); + if (alloc_avail == m_block_dimensions[dim]) { + // Insufficient excess coefficients to allocate. + break; + } + m_block_dimensions[dim] = + numext::mini(m_tensor_dimensions[dim], alloc_avail); + total_size = total_size_other_dims * m_block_dimensions[dim]; + } + } + + } else { + eigen_assert(false); // unknown block shape + } + + eigen_assert(m_block_dimensions.TotalSize() >= + numext::mini(target_block_size, + m_tensor_dimensions.TotalSize())); + + // Calculate block counts by dimension and total block count. + DSizes block_count; + for (int i = 0; i < NumDims; ++i) { + block_count[i] = divup(m_tensor_dimensions[i], m_block_dimensions[i]); + } + m_total_block_count = array_prod(block_count); + + // Calculate block strides (used for enumerating blocks). + m_tensor_strides = strides(m_tensor_dimensions); + m_block_strides = strides(block_count); + } + + DSizes m_tensor_dimensions; + TensorBlockResourceRequirements m_requirements; + + DSizes m_block_dimensions; + IndexType m_total_block_count; + + DSizes m_tensor_strides; + DSizes m_block_strides; +}; + +// -------------------------------------------------------------------------- // +// TensorBlockScratchAllocator is responsible for allocating temporary buffers +// for block evaluation (output or input block materialization). Given that +// Eigen expression traversal order is deterministic, all temporary allocations +// are happening in the same order, and usually have exactly the same size. +// Scratch allocator keeps a trace of all dynamic allocations, and after the +// first block evaluation is completed, we should be able to reuse all the +// temporary buffers for the next block evaluation. + +template +class TensorBlockScratchAllocator { + public: + explicit TensorBlockScratchAllocator(const Device& device) + : m_device(device), m_allocation_index(0) {} + + ~TensorBlockScratchAllocator() { + for (size_t i = 0; i < m_allocations.size(); ++i) { + m_device.deallocate(m_allocations[i].ptr); + } + } + + void* allocate(size_t size) { + // TODO(ezhulenev): Remove when replaced with inlined vector. + if (m_allocations.capacity() == 0) m_allocations.reserve(8); + + // Check if we already have an existing allocation att current index. + const int num_allocations = static_cast(m_allocations.size()); + const bool has_allocation = m_allocation_index < num_allocations; + + // Allocation index can't be larger than the number of allocations. + eigen_assert(m_allocation_index <= num_allocations); + + // If we have existing allocation, and its size is larger or equal to + // requested size, we do nothing. + + // If current allocation can't fit requested size, we deallocate it, and + // replace with a larger allocation. + if (has_allocation && m_allocations[m_allocation_index].size < size) { + m_device.deallocate(m_allocations[m_allocation_index].ptr); + m_allocations[m_allocation_index].ptr = m_device.allocate(size); + m_allocations[m_allocation_index].size = size; + } + + // Make a new allocation if we don't have and existing one. + if (!has_allocation) { + Allocation allocation; + allocation.ptr = m_device.allocate(size); + allocation.size = size; + m_allocations.push_back(allocation); + } + + eigen_assert(m_allocations[m_allocation_index].ptr != NULL); + eigen_assert(m_allocations[m_allocation_index].size >= size); + + return m_allocations[m_allocation_index++].ptr; + } + + void reset() { m_allocation_index = 0; } + + private: + struct Allocation { + void* ptr; + size_t size; + }; + + const Device& m_device; + int m_allocation_index; + // TODO(ezhulenev): This should be an inlined vector. + std::vector m_allocations; +}; + +// -------------------------------------------------------------------------- // +// TensorBlockKind represents all possible block kinds, that can be produced by +// TensorEvaluator::evalBlock function. +enum TensorBlockKind { + // Tensor block that is a lazy expression that must be assigned to a + // destination using TensorBlockAssign. + kExpr, + + // Tensor block that is a view into a memory buffer owned by an underlying + // Tensor expression (e.g. it can be a view into a Tensor buffer). + kView, + + // Tensor block that was materialized in a scratch memory buffer, allocated + // with TensorBlockScratchAllocator. This block must be copied to a + // destination, similar to a block of `kExpr` type. + kMaterializedInScratch, + + // Tensor block that was materialized directly into the final output memory + // buffer. For example if the left side of an assignment is a Tensor, we can + // directly materialize the block in the destination memory. + // + // If strides in the output buffer do not match tensor block strides, the + // Tensor expression will be invalid, and should not be used by + // TensorBlockAssign or for constructing another block expression. + kMaterializedInOutput +}; + +// -------------------------------------------------------------------------- // +// TensorBlockNotImplemented should be used to defined TensorBlock typedef in +// TensorEvaluators that do not support block evaluation. + +class TensorBlockNotImplemented { + public: + typedef void XprType; +}; + +// -------------------------------------------------------------------------- // +// XprScalar extracts Scalar type from the Eigen expressions (if expression type +// is not void). It's required to be able to define lazy block expression for +// argument types, that do not support block evaluation. + +template +struct XprScalar { + typedef typename XprType::Scalar type; +}; +template <> +struct XprScalar { + typedef void type; +}; + +// -------------------------------------------------------------------------- // +// TensorMaterializedBlock is a fully evaluated block of the original tensor, +// and XprType is just a TensorMap over the data. This block type is typically +// used to materialize blocks of tensor expressions, that can't be efficiently +// represented as lazy Tensor expressions with fast coeff/packet operations, +// e.g. we materialize all broadcasts into evaluated blocks. +// +// TensorMaterializedBlock does not own its memory buffer, it's either a memory +// buffer that backs the original expression (e.g. block is just a view into a +// Tensor), or a memory buffer allocated with scratch allocator, and in this +// case the scratch allocator will deallocate it at the end of block based +// expression execution. +// +// If the block was evaluated directly into the output buffer, and strides in +// the output buffer do not match block strides, the TensorMap expression will +// be invalid, and should never be used in block assignment or any other tensor +// expression. + +template +class TensorMaterializedBlock { + public: + typedef DSizes Dimensions; + typedef TensorMap > XprType; + + TensorMaterializedBlock(TensorBlockKind kind, const Scalar* data, + const Dimensions& dimensions, bool valid_expr = true) + : m_kind(kind), + m_data(data), + m_dimensions(dimensions), + m_expr(m_data, m_dimensions), + m_valid_expr(valid_expr) { + eigen_assert(m_kind == internal::TensorBlockKind::kView || + m_kind == internal::TensorBlockKind::kMaterializedInScratch || + m_kind == internal::TensorBlockKind::kMaterializedInOutput); + } + + TensorBlockKind kind() const { return m_kind; } + // NOTE(ezhulenev): Returning XprType by value like in other block types + // causes asan failures. The theory is that XprType::Nested doesn't work + // properly for TensorMap. + const XprType& expr() const { + eigen_assert(m_valid_expr); + return m_expr; + } + const Scalar* data() const { return m_data; } + void cleanup() {} + + typedef internal::TensorBlockDescriptor TensorBlockDesc; + + // TensorMaterializedBlock can be backed by different types of storage: + // + // (1) Contiguous block of memory allocated with scratch allocator. + // (2) Contiguous block of memory reused from tensor block descriptor + // destination buffer. + // (3) Strided block of memory reused from tensor block descriptor + // destination buffer. + // + class Storage { + public: + Scalar* data() const { return m_data; } + const Dimensions& dimensions() const { return m_dimensions; } + const Dimensions& strides() const { return m_strides; } + + TensorMaterializedBlock AsTensorMaterializedBlock() const { + return TensorMaterializedBlock( + m_materialized_in_output + ? internal::TensorBlockKind::kMaterializedInOutput + : internal::TensorBlockKind::kMaterializedInScratch, + m_data, m_dimensions, !m_strided_storage); + } + + private: + friend class TensorMaterializedBlock; + + Storage(Scalar* data, const Dimensions& dimensions, + const Dimensions& strides, bool materialized_in_output, + bool strided_storage) + : m_data(data), + m_dimensions(dimensions), + m_strides(strides), + m_materialized_in_output(materialized_in_output), + m_strided_storage(strided_storage) {} + + Scalar* m_data; + Dimensions m_dimensions; + Dimensions m_strides; + bool m_materialized_in_output; + bool m_strided_storage; + }; + + // Creates a storage for materialized block either from the block descriptor + // destination buffer, or allocates a new buffer with scratch allocator. + template + EIGEN_STRONG_INLINE static Storage prepareStorage( + TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool allow_strided_storage = false) { + // Try to reuse destination as an output block buffer. + typedef typename TensorBlockDesc::DestinationBuffer DestinationBuffer; + + if (desc.destination().kind() == DestinationBuffer::kContiguous) { + Scalar* buffer = desc.destination().template data(); + desc.DropDestinationBuffer(); + return Storage(buffer, desc.dimensions(), + internal::strides(desc.dimensions()), + /*materialized_in_output=*/true, + /*strided_storage=*/false); + + } else if (desc.destination().kind() == DestinationBuffer::kStrided && + allow_strided_storage) { + Scalar* buffer = desc.destination().template data(); + desc.DropDestinationBuffer(); + return Storage(buffer, desc.dimensions(), desc.destination().strides(), + /*materialized_in_output=*/true, /*strided_storage=*/true); + + } else { + void* mem = scratch.allocate(desc.size() * sizeof(Scalar)); + return Storage(static_cast(mem), desc.dimensions(), + internal::strides(desc.dimensions()), + /*materialized_in_output=*/false, + /*strided_storage=*/false); + } + } + + // Creates a materialized block for the given descriptor from a memory buffer. + template + EIGEN_STRONG_INLINE static TensorMaterializedBlock materialize( + const Scalar* data, const DataDimensions& data_dims, + TensorBlockDesc& desc, TensorBlockScratch& scratch) { + eigen_assert(array_size::value == desc.dimensions().size()); + + // If a tensor block dimensions covers a contiguous block of the underlying + // memory, we can skip block buffer memory allocation, and construct a block + // from existing `data` memory buffer. + // + // Example: (RowMajor layout) + // data_dims: [11, 12, 13, 14] + // desc.dimensions(): [1, 1, 3, 14] + // + // In this case we can construct a TensorBlock starting at + // `data + desc.offset()`, with a `desc.dimensions()` block sizes. + static const bool is_col_major = Layout == ColMajor; + + // Find out how many inner dimensions have a matching size. + int num_matching_inner_dims = 0; + for (int i = 0; i < NumDims; ++i) { + int dim = is_col_major ? i : NumDims - i - 1; + if (data_dims[dim] != desc.dimensions()[dim]) break; + ++num_matching_inner_dims; + } + + // All the outer dimensions must be of size `1`, except a single dimension + // before the matching inner dimension (`3` in the example above). + bool can_use_direct_access = true; + for (int i = num_matching_inner_dims + 1; i < NumDims; ++i) { + int dim = is_col_major ? i : NumDims - i - 1; + if (desc.dimension(dim) != 1) { + can_use_direct_access = false; + break; + } + } + + if (can_use_direct_access) { + const Scalar* block_start = data + desc.offset(); + return TensorMaterializedBlock(internal::TensorBlockKind::kView, + block_start, desc.dimensions()); + + } else { + // Reuse destination buffer or allocate new buffer with scratch allocator. + const Storage storage = prepareStorage(desc, scratch); + + typedef internal::TensorBlockIO + TensorBlockIO; + typedef typename TensorBlockIO::Dst TensorBlockIODst; + typedef typename TensorBlockIO::Src TensorBlockIOSrc; + + TensorBlockIOSrc src(internal::strides(Dimensions(data_dims)), + data, desc.offset()); + TensorBlockIODst dst(storage.dimensions(), storage.strides(), + storage.data()); + + TensorBlockIO::Copy(dst, src); + return storage.AsTensorMaterializedBlock(); + } + } + + private: + TensorBlockKind m_kind; + const Scalar* m_data; + Dimensions m_dimensions; + XprType m_expr; + bool m_valid_expr; +}; + +// -------------------------------------------------------------------------- // +// TensorCwiseUnaryBlock is a lazy tensor expression block that applies UnaryOp +// functor to the blocks produced by the underlying Tensor expression. + +template +class TensorCwiseUnaryBlock { + static constexpr bool NoArgBlockAccess = + internal::is_void::value; + + public: + typedef std::conditional_t< + NoArgBlockAccess, void, + TensorCwiseUnaryOp > + XprType; + + typedef typename XprScalar::type Scalar; + + TensorCwiseUnaryBlock(const ArgTensorBlock& arg_block, const UnaryOp& functor) + : m_arg_block(arg_block), m_functor(functor) {} + + TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; } + + XprType expr() const { return XprType(m_arg_block.expr(), m_functor); } + const Scalar* data() const { return NULL; } + void cleanup() { m_arg_block.cleanup(); } + + private: + ArgTensorBlock m_arg_block; + UnaryOp m_functor; +}; + +// -------------------------------------------------------------------------- // +// TensorCwiseUnaryBlock is a lazy tensor expression block that applies BinaryOp +// functor to the blocks produced by the underlying Tensor expression. + +template +class TensorCwiseBinaryBlock { + static constexpr bool NoArgBlockAccess = + internal::is_void::value || + internal::is_void::value; + + public: + typedef std::conditional_t< + NoArgBlockAccess, void, + TensorCwiseBinaryOp > + XprType; + + typedef typename XprScalar::type Scalar; + + TensorCwiseBinaryBlock(const LhsTensorBlock& left_block, + const RhsTensorBlock& right_block, + const BinaryOp& functor) + : m_left_block(left_block), + m_right_block(right_block), + m_functor(functor) {} + + TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; } + + XprType expr() const { + return XprType(m_left_block.expr(), m_right_block.expr(), m_functor); + } + + const Scalar* data() const { return NULL; } + + void cleanup() { + m_left_block.cleanup(); + m_right_block.cleanup(); + } + + private: + LhsTensorBlock m_left_block; + RhsTensorBlock m_right_block; + BinaryOp m_functor; +}; + +// -------------------------------------------------------------------------- // +// TensorUnaryExprBlock is a lazy tensor expression block that can construct +// an arbitrary tensor expression from a block of the underlying type (this is a +// generalization of the TensorCwiseUnaryBlock for arbitrary expressions). + +template +class TensorUnaryExprBlock { + typedef typename ArgTensorBlock::XprType ArgXprType; + static constexpr bool NoArgBlockAccess = internal::is_void::value; + + public: + typedef std::conditional_t< + NoArgBlockAccess, void, + typename BlockFactory::template XprType::type> XprType; + + typedef typename XprScalar::type Scalar; + + TensorUnaryExprBlock(const ArgTensorBlock& arg_block, + const BlockFactory& factory) + : m_arg_block(arg_block), m_factory(factory) {} + + TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; } + XprType expr() const { return m_factory.expr(m_arg_block.expr()); } + const Scalar* data() const { return NULL; } + void cleanup() { m_arg_block.cleanup(); } + + private: + ArgTensorBlock m_arg_block; + BlockFactory m_factory; +}; + +// -------------------------------------------------------------------------- // +// TensorTernaryExprBlock is a lazy tensor expression block that can construct +// an arbitrary tensor expression from three blocks of the underlying type. + +template +class TensorTernaryExprBlock { + typedef typename Arg1TensorBlock::XprType Arg1XprType; + typedef typename Arg2TensorBlock::XprType Arg2XprType; + typedef typename Arg3TensorBlock::XprType Arg3XprType; + + static constexpr bool NoArgBlockAccess = internal::is_void::value || + internal::is_void::value || + internal::is_void::value; + + public: + typedef std::conditional_t< + NoArgBlockAccess, void, + typename BlockFactory::template XprType::type> XprType; + + typedef typename XprScalar::type Scalar; + + TensorTernaryExprBlock(const Arg1TensorBlock& arg1_block, + const Arg2TensorBlock& arg2_block, + const Arg3TensorBlock& arg3_block, + const BlockFactory& factory) + : m_arg1_block(arg1_block), + m_arg2_block(arg2_block), + m_arg3_block(arg3_block), + m_factory(factory) {} + + TensorBlockKind kind() const { return internal::TensorBlockKind::kExpr; } + XprType expr() const { + return m_factory.expr(m_arg1_block.expr(), m_arg2_block.expr(), + m_arg3_block.expr()); + } + const Scalar* data() const { return NULL; } + void cleanup() { + m_arg1_block.cleanup(); + m_arg2_block.cleanup(); + m_arg3_block.cleanup(); + } + + private: + Arg1TensorBlock m_arg1_block; + Arg2TensorBlock m_arg2_block; + Arg3TensorBlock m_arg3_block; + BlockFactory m_factory; +}; + +// -------------------------------------------------------------------------- // +// StridedLinearBufferCopy provides a method to copy data between two linear +// buffers with different strides, with optimized paths for scatter/gather. + +template +class StridedLinearBufferCopy { + typedef typename packet_traits::type Packet; + typedef typename unpacket_traits::half HalfPacket; + enum { + Vectorizable = packet_traits::Vectorizable, + PacketSize = packet_traits::size, + HalfPacketSize = unpacket_traits::size, + HasHalfPacket = static_cast(HalfPacketSize) < static_cast(PacketSize) + }; + + public: + // Specifying linear copy kind statically gives ~30% speedup for small sizes. + enum class Kind { + Linear = 0, // src_stride == 1 && dst_stride == 1 + Scatter = 1, // src_stride == 1 && dst_stride != 1 + FillLinear = 2, // src_stride == 0 && dst_stride == 1 + FillScatter = 3, // src_stride == 0 && dst_stride != 1 + Gather = 4, // dst_stride == 1 + Random = 5 // everything else + }; + + struct Dst { + Dst(IndexType o, IndexType s, Scalar* d) : offset(o), stride(s), data(d) {} + + IndexType offset; + IndexType stride; + Scalar* data; + }; + + struct Src { + Src(IndexType o, IndexType s, const Scalar* d) + : offset(o), stride(s), data(d) {} + + IndexType offset; + IndexType stride; + const Scalar* data; + }; + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run(const Dst& dst, + const Src& src, + const size_t count) { + Run(count, dst.offset, dst.stride, dst.data, src.offset, src.stride, + src.data); + } + + private: + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run( + const IndexType count, const IndexType dst_offset, + const IndexType dst_stride, Scalar* EIGEN_RESTRICT dst_data, + const IndexType src_offset, const IndexType src_stride, + const Scalar* EIGEN_RESTRICT src_data) { + const Scalar* src = &src_data[src_offset]; + Scalar* dst = &dst_data[dst_offset]; + + if (!Vectorizable) { + for (Index i = 0; i < count; ++i) { + dst[i * dst_stride] = src[i * src_stride]; + } + return; + } + + const IndexType vectorized_size = count - PacketSize; + IndexType i = 0; + + if (kind == StridedLinearBufferCopy::Kind::Linear) { + // ******************************************************************** // + // Linear copy from `src` to `dst`. + const IndexType unrolled_size = count - 4 * PacketSize; + eigen_assert(src_stride == 1 && dst_stride == 1); + for (; i <= unrolled_size; i += 4 * PacketSize) { + for (int j = 0; j < 4; ++j) { + Packet p = ploadu(src + i + j * PacketSize); + pstoreu(dst + i + j * PacketSize, p); + } + } + for (; i <= vectorized_size; i += PacketSize) { + Packet p = ploadu(src + i); + pstoreu(dst + i, p); + } + if (HasHalfPacket) { + const IndexType vectorized_half_size = count - HalfPacketSize; + if (i <= vectorized_half_size) { + HalfPacket p = ploadu(src + i); + pstoreu(dst + i, p); + i += HalfPacketSize; + } + } + for (; i < count; ++i) { + dst[i] = src[i]; + } + // ******************************************************************** // + } else if (kind == StridedLinearBufferCopy::Kind::Scatter) { + // Scatter from `src` to `dst`. + eigen_assert(src_stride == 1 && dst_stride != 1); + for (; i <= vectorized_size; i += PacketSize) { + Packet p = ploadu(src + i); + pscatter(dst + i * dst_stride, p, dst_stride); + } + if (HasHalfPacket) { + const IndexType vectorized_half_size = count - HalfPacketSize; + if (i <= vectorized_half_size) { + HalfPacket p = ploadu(src + i); + pscatter(dst + i * dst_stride, p, dst_stride); + i += HalfPacketSize; + } + } + for (; i < count; ++i) { + dst[i * dst_stride] = src[i]; + } + // ******************************************************************** // + } else if (kind == StridedLinearBufferCopy::Kind::FillLinear) { + // Fill `dst` with value at `*src`. + eigen_assert(src_stride == 0 && dst_stride == 1); + const IndexType unrolled_size = count - 4 * PacketSize; + Scalar s = *src; + Packet p = pset1(s); + for (; i <= unrolled_size; i += 4 * PacketSize) { + for (int j = 0; j < 4; ++j) { + pstoreu(dst + i + j * PacketSize, p); + } + } + for (; i <= vectorized_size; i += PacketSize) { + pstoreu(dst + i, p); + } + if (HasHalfPacket) { + const IndexType vectorized_half_size = count - HalfPacketSize; + if (i <= vectorized_half_size) { + HalfPacket hp = pset1(s); + pstoreu(dst + i, hp); + i += HalfPacketSize; + } + } + for (; i < count; ++i) { + dst[i] = s; + } + // ******************************************************************** // + } else if (kind == StridedLinearBufferCopy::Kind::FillScatter) { + // Scatter `*src` into `dst`. + eigen_assert(src_stride == 0 && dst_stride != 1); + Scalar s = *src; + Packet p = pset1(s); + for (; i <= vectorized_size; i += PacketSize) { + pscatter(dst + i * dst_stride, p, dst_stride); + } + if (HasHalfPacket) { + const IndexType vectorized_half_size = count - HalfPacketSize; + if (i <= vectorized_half_size) { + HalfPacket hp = pset1(s); + pscatter(dst + i * dst_stride, hp, dst_stride); + i += HalfPacketSize; + } + } + for (; i < count; ++i) { + dst[i * dst_stride] = s; + } + // ******************************************************************** // + } else if (kind == StridedLinearBufferCopy::Kind::Gather) { + // Gather from `src` into `dst`. + eigen_assert(dst_stride == 1); + for (; i <= vectorized_size; i += PacketSize) { + Packet p = pgather(src + i * src_stride, src_stride); + pstoreu(dst + i, p); + } + if (HasHalfPacket) { + const IndexType vectorized_half_size = count - HalfPacketSize; + if (i <= vectorized_half_size) { + HalfPacket p = + pgather(src + i * src_stride, src_stride); + pstoreu(dst + i, p); + i += HalfPacketSize; + } + } + for (; i < count; ++i) { + dst[i] = src[i * src_stride]; + } + // ******************************************************************** // + } else if (kind == StridedLinearBufferCopy::Kind::Random) { + // Random. + for (; i < count; ++i) { + dst[i * dst_stride] = src[i * src_stride]; + } + } else { + eigen_assert(false); + } + } +}; + +// -------------------------------------------------------------------------- // +// TensorBlockIO copies data from `src` tensor block, to the `dst` tensor block. +// It's possible to specify src->dst dimension mapping for the copy operation. +// Dimensions of `dst` specify how many elements have to be copied, for the +// `src` we need to know only stride to navigate through source memory buffer. + +template +class TensorBlockIO { + static constexpr bool IsColMajor = (Layout == ColMajor); + + typedef StridedLinearBufferCopy LinCopy; + + public: + typedef DSizes Dimensions; + typedef DSizes DimensionsMap; + + struct Dst { + Dst(const Dimensions& dst_dims, const Dimensions& dst_strides, Scalar* dst, + IndexType dst_offset = 0) + : dims(dst_dims), strides(dst_strides), data(dst), offset(dst_offset) {} + + Dimensions dims; + Dimensions strides; + Scalar* data; + IndexType offset; + }; + + struct Src { + Src(const Dimensions& src_strides, const Scalar* src, + IndexType src_offset = 0) + : strides(src_strides), data(src), offset(src_offset) {} + + Dimensions strides; + const Scalar* data; + IndexType offset; + }; + + // Copies data to `dst` from `src`, using provided dimensions mapping: + // + // src_dimension_index = dst_to_src_dim_map[dst_dimension_index] + // + // Returns the number of copied elements. + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType Copy( + const Dst& dst, const Src& src, const DimensionsMap& dst_to_src_dim_map) { + // Copy single scalar value from `src` to `dst`. + if (NumDims == 0) { + *(dst.data + dst.offset) = *(src.data + src.offset); + return 1; + } + + // Both `dst` and `src` must have contiguous innermost dimension. We also + // accept the special case with stride '0', because it's used as a trick to + // implement broadcasting. + { + int inner_dim = IsColMajor ? 0 : NumDims - 1; + EIGEN_UNUSED_VARIABLE(inner_dim); + eigen_assert(dst.strides[inner_dim] == 1 || dst.strides[inner_dim] == 0); + eigen_assert(src.strides[inner_dim] == 1 || src.strides[inner_dim] == 0); + } + + // Give a shorter name to `dst_to_src_dim_map`. + const DimensionsMap& dim_map = dst_to_src_dim_map; + + // Do not squeeze reordered inner dimensions. + int num_squeezable_dims = NumSqueezableInnerDims(dim_map); + + // NOTE: We find the innermost dimension (contiguous in memory) in the dst + // block, and we write data linearly into that dimension, reading it from + // the src. If dimensions are reordered, we might end up reading data from + // the src with `stride != 1`. + // + // NOTE: Random-Read/Linear-Write can be up to ~2X faster than + // Linear-Read/Random-Write: https://stackoverflow.com/a/54935680 + + // Find the innermost dimension in the dst whose size is not 1. This is the + // effective inner dim. + int num_size_one_inner_dims = 0; + for (int i = 0; i < num_squeezable_dims; ++i) { + const int dst_dim = IsColMajor ? i : NumDims - i - 1; + if (dst.dims[dst_dim] != 1) break; + num_size_one_inner_dims++; + } + + // If all dimensions are of size 1, just copy a scalar from `src` to `dst`. + if (num_size_one_inner_dims == NumDims) { + *(dst.data + dst.offset) = *(src.data + src.offset); + return 1; + } + + // Outermost dimension in the dst with `stride == 1` (contiguous in memory). + const int dst_stride1_dim = IsColMajor + ? num_size_one_inner_dims + : NumDims - num_size_one_inner_dims - 1; + + // Dimension in the src that corresponds to the dst innermost dimension. + const int src_dim_for_dst_stride1_dim = + NumDims == 0 ? 1 : dim_map[dst_stride1_dim]; + + // Size of the innermost dimension (length of contiguous blocks of memory). + IndexType dst_inner_dim_size = NumDims == 0 ? 1 : dst.dims[dst_stride1_dim]; + + // Squeeze multiple inner dims into one if they are contiguous in `dst` and + // `src` memory, so we can do less linear copy calls. + for (int i = num_size_one_inner_dims + 1; i < num_squeezable_dims; ++i) { + const int dst_dim = IsColMajor ? i : NumDims - i - 1; + const IndexType dst_stride = dst.strides[dst_dim]; + const IndexType src_stride = src.strides[dim_map[dst_dim]]; + if (dst_inner_dim_size == dst_stride && dst_stride == src_stride) { + dst_inner_dim_size *= dst.dims[dst_dim]; + ++num_size_one_inner_dims; + } else { + break; + } + } + + // Setup strides to read data from `src` and write to `dst`. + IndexType input_offset = src.offset; + IndexType output_offset = dst.offset; + IndexType input_stride = + NumDims == 0 ? 1 : src.strides[src_dim_for_dst_stride1_dim]; + IndexType output_stride = NumDims == 0 ? 1 : dst.strides[dst_stride1_dim]; + + const int at_least_1_dim = NumDims <= 1 ? 1 : NumDims - 1; + array it; + + // Initialize block iterator state. Squeeze away any dimension of size 1. + int idx = 0; // currently initialized iterator state index + for (int i = num_size_one_inner_dims; i < NumDims - 1; ++i) { + const int dst_dim = IsColMajor ? i + 1 : NumDims - i - 2; + if (dst.dims[dst_dim] == 1) continue; + + it[idx].size = dst.dims[dst_dim]; + it[idx].input_stride = src.strides[dim_map[dst_dim]]; + it[idx].output_stride = dst.strides[dst_dim]; + + it[idx].input_span = it[idx].input_stride * (it[idx].size - 1); + it[idx].output_span = it[idx].output_stride * (it[idx].size - 1); + + idx++; + } + + // Iterate copying data from src to dst. + const IndexType block_total_size = NumDims == 0 ? 1 : dst.dims.TotalSize(); + +#define COPY_INNER_DIM(KIND) \ + IndexType num_copied = 0; \ + for (num_copied = 0; num_copied < block_total_size; \ + num_copied += dst_inner_dim_size) { \ + LinCopy::template Run( \ + typename LinCopy::Dst(output_offset, output_stride, dst.data), \ + typename LinCopy::Src(input_offset, input_stride, src.data), \ + dst_inner_dim_size); \ + \ + for (int j = 0; j < idx; ++j) { \ + if (++it[j].count < it[j].size) { \ + input_offset += it[j].input_stride; \ + output_offset += it[j].output_stride; \ + break; \ + } \ + it[j].count = 0; \ + input_offset -= it[j].input_span; \ + output_offset -= it[j].output_span; \ + } \ + } \ + return num_copied; + + if (input_stride == 1 && output_stride == 1) { + COPY_INNER_DIM(LinCopy::Kind::Linear); + } else if (input_stride == 1 && output_stride != 1) { + COPY_INNER_DIM(LinCopy::Kind::Scatter); + } else if (input_stride == 0 && output_stride == 1) { + COPY_INNER_DIM(LinCopy::Kind::FillLinear); + } else if (input_stride == 0 && output_stride != 1) { + COPY_INNER_DIM(LinCopy::Kind::FillScatter); + } else if (output_stride == 1) { + COPY_INNER_DIM(LinCopy::Kind::Gather); + } else { + COPY_INNER_DIM(LinCopy::Kind::Random); + } + +#undef COPY_INNER_DIM + } + + // Copy from `src` to `dst` with an identity src->dst dimension map. Returns + // the number of copied elements. + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE IndexType Copy(const Dst& dst, + const Src& src) { + DimensionsMap dst_to_src_map; + for (int i = 0; i < NumDims; ++i) dst_to_src_map[i] = i; + return Copy(dst, src, dst_to_src_map); + } + + private: + struct BlockIteratorState { + BlockIteratorState() + : size(0), + count(0), + input_stride(0), + output_stride(0), + input_span(0), + output_span(0) {} + + IndexType size; + IndexType count; + IndexType input_stride; + IndexType output_stride; + IndexType input_span; + IndexType output_span; + }; + + // Compute how many inner dimensions it's allowed to squeeze when doing IO + // between two tensor blocks. It's safe to squeeze inner dimensions, only + // if they are not reordered. + static int NumSqueezableInnerDims(const DimensionsMap& dim_map) { + int num_squeezable_dims = 0; + for (int i = 0; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + if (dim_map[dim] != dim) break; + num_squeezable_dims++; + } + return num_squeezable_dims; + } +}; + +// -------------------------------------------------------------------------- // +// TensorBlockAssignment assigns a block expression of type `TensorBlockExpr` to +// a Tensor block defined by `desc`, backed by a memory buffer at `target`. +// +// Currently there is no way to write from a Tensor expression to a block of +// memory, if dimensions are reordered. If you need to do that, you should +// materialize a Tensor block expression into a memory buffer, and then use +// TensorBlockIO to copy data between two memory buffers with a custom +// `target->src` dimension map (see definition above). +// +// Also currently the innermost dimension of `target` must have a stride '1' +// (contiguous in memory). This restriction could be lifted with a `pscatter`, +// but in practice it's never needed, and there is a similar TensorBlockIO +// workaround for that. +// +// TODO(ezhulenev): TensorBlockAssignment is a special case of TensorBlockIO +// where `src` is a tensor expression. Explore if it is possible to rewrite IO +// to use expressions instead of pointers, and after that TensorBlockAssignment +// will become an alias to IO. +template +class TensorBlockAssignment { + // We will use coeff/packet path to evaluate block expressions. + typedef TensorEvaluator + TensorBlockEvaluator; + + typedef DSizes Dimensions; + + enum { + Vectorizable = packet_traits::Vectorizable, + PacketSize = packet_traits::size + }; + + template + struct InnerDimAssign { + EIGEN_ALWAYS_INLINE static void Run(Scalar* target, IndexType count, + const Evaluator& eval, + IndexType eval_offset) { + for (IndexType i = 0; i < count; ++i) { + target[i] = eval.coeff(eval_offset + i); + } + } + }; + + template + struct InnerDimAssign { + EIGEN_ALWAYS_INLINE static void Run(Scalar* target, IndexType count, + const Evaluator& eval, + IndexType eval_offset) { + typedef typename packet_traits::type Packet; + + const IndexType unrolled_size = count - 4 * PacketSize; + const IndexType vectorized_size = count - PacketSize; + IndexType i = 0; + + for (; i <= unrolled_size; i += 4 * PacketSize) { + for (int j = 0; j < 4; ++j) { + const IndexType idx = eval_offset + i + j * PacketSize; + Packet p = eval.template packet(idx); + pstoreu(target + i + j * PacketSize, p); + } + } + + for (; i <= vectorized_size; i += PacketSize) { + Packet p = eval.template packet(eval_offset + i); + pstoreu(target + i, p); + } + + for (; i < count; ++i) { + target[i] = eval.coeff(eval_offset + i); + } + } + }; + + public: + struct Target { + Target(const Dimensions& target_dims, const Dimensions& target_strides, + Scalar* target_data, IndexType target_offset = 0) + : dims(target_dims), + strides(target_strides), + data(target_data), + offset(target_offset) {} + + Dimensions dims; + Dimensions strides; + Scalar* data; + IndexType offset; + }; + + static Target target(const Dimensions& target_dims, + const Dimensions& target_strides, Scalar* target_data, + IndexType target_offset = 0) { + return Target(target_dims, target_strides, target_data, target_offset); + } + + template + static Target target( + const DSizes& target_dims, + const DSizes& target_strides, + Scalar* target_data, IndexType target_offset = 0) { + // DSizes constructor will do index type promotion if it's safe. + return Target(Dimensions(target_dims), Dimensions(target_strides), + target_data, target_offset); + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run( + const Target& target, const TensorBlockExpr& expr) { + // Prepare evaluator for block expression. + DefaultDevice default_device; + TensorBlockEvaluator eval(expr, default_device); + + // Tensor block expression dimension should match destination dimensions. + eigen_assert(dimensions_match(target.dims, eval.dimensions())); + + static const int Layout = TensorBlockEvaluator::Layout; + static const bool is_col_major = Layout == ColMajor; + + // Initialize output inner dimension size based on a layout. + const IndexType output_size = NumDims == 0 ? 1 : target.dims.TotalSize(); + const int inner_dim_idx = is_col_major ? 0 : NumDims - 1; + IndexType output_inner_dim_size = target.dims[inner_dim_idx]; + + // Target inner dimension stride must be '1'. + eigen_assert(target.strides[inner_dim_idx] == 1); + + // Squeeze multiple inner dims into one if they are contiguous in `target`. + IndexType num_squeezed_dims = 0; + for (Index i = 1; i < NumDims; ++i) { + const Index dim = is_col_major ? i : NumDims - i - 1; + const IndexType target_stride = target.strides[dim]; + + if (output_inner_dim_size == target_stride) { + output_inner_dim_size *= target.dims[dim]; + num_squeezed_dims++; + } else { + break; + } + } + + // Initialize output block iterator state. Dimension in this array are + // always in inner_most -> outer_most order (col major layout). + array it; + + int idx = 0; // currently initialized iterator state index + for (Index i = num_squeezed_dims; i < NumDims - 1; ++i) { + const Index dim = is_col_major ? i + 1 : NumDims - i - 2; + + it[idx].count = 0; + it[idx].size = target.dims[dim]; + it[idx].output_stride = target.strides[dim]; + it[idx].output_span = it[idx].output_stride * (it[idx].size - 1); + idx++; + } + + // We read block expression from the beginning, and start writing data to + // `target` at given offset. + IndexType input_offset = 0; + IndexType output_offset = target.offset; + + // Iterate copying data from `eval` to `target`. + for (IndexType i = 0; i < output_size; i += output_inner_dim_size) { + // Assign to `target` at current offset. + InnerDimAssign::Run(target.data + output_offset, + output_inner_dim_size, eval, + input_offset); + + // Move input offset forward by the number of assigned coefficients. + input_offset += output_inner_dim_size; + + // Update index. + for (int j = 0; j < idx; ++j) { + if (++it[j].count < it[j].size) { + output_offset += it[j].output_stride; + break; + } + it[j].count = 0; + output_offset -= it[j].output_span; + } + } + } + + private: + struct BlockIteratorState { + BlockIteratorState() + : count(0), size(0), output_stride(0), output_span(0) {} + + IndexType count; + IndexType size; + IndexType output_stride; + IndexType output_span; + }; +}; + +// -------------------------------------------------------------------------- // + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_BLOCK_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h new file mode 100644 index 0000000000000000000000000000000000000000..5ae0d8172b44938cae1093d1cb02bbd7eb4b0a3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h @@ -0,0 +1,1080 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H +#define EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorBroadcasting + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor broadcasting class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorBroadcastingOp EIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorBroadcastingOp type; +}; + +template +struct is_input_scalar { + static const bool value = false; +}; +template <> +struct is_input_scalar > { + static const bool value = true; +}; +#ifndef EIGEN_EMULATE_CXX11_META_H +template +struct is_input_scalar > { + static const bool value = (Sizes::total_size == 1); +}; +#endif + +} // end namespace internal + + + +template +class TensorBroadcastingOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBroadcastingOp(const XprType& expr, const Broadcast& broadcast) + : m_xpr(expr), m_broadcast(broadcast) {} + + EIGEN_DEVICE_FUNC + const Broadcast& broadcast() const { return m_broadcast; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const Broadcast m_broadcast; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorBroadcastingOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename TensorEvaluator::Dimensions InputDimensions; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + protected: // all the non-static fields must have the same access control, otherwise the TensorEvaluator won't be standard layout; + bool isCopy, nByOne, oneByN; + public: + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::BlockAccess, + PreferBlockAccess = true, + RawAccess = false + }; + static constexpr int Layout = TensorEvaluator::Layout; + + typedef std::remove_const_t ScalarNoConst; + + // We do block based broadcasting using a trick with 2x tensor rank and 0 + // strides. See block method implementation for details. + typedef DSizes BroadcastDimensions; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : isCopy(false), nByOne(false), oneByN(false), + m_device(device), m_broadcast(op.broadcast()), m_impl(op.expression(), device) + { + + // The broadcasting op doesn't change the rank of the tensor. One can't broadcast a scalar + // and store the result in a scalar. Instead one should reshape the scalar into a N-D + // tensor with N >= 1 of 1 element first and then broadcast. + EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + const InputDimensions& input_dims = m_impl.dimensions(); + isCopy = true; + for (int i = 0; i < NumDims; ++i) { + eigen_assert(input_dims[i] > 0); + m_dimensions[i] = input_dims[i] * m_broadcast[i]; + if (m_broadcast[i] != 1) { + isCopy = false; + } + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputStrides[0] = 1; + m_outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1]; + } + } else { + m_inputStrides[NumDims-1] = 1; + m_outputStrides[NumDims-1] = 1; + for (int i = NumDims-2; i >= 0; --i) { + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + m_outputStrides[i] = m_outputStrides[i+1] * m_dimensions[i+1]; + } + } + + if (input_dims[0] == 1) { + oneByN = true; + for (int i = 1; i < NumDims; ++i) { + if (m_broadcast[i] != 1) { + oneByN = false; + break; + } + } + } else if (input_dims[NumDims-1] == 1) { + nByOne = true; + for (int i = 0; i < NumDims-1; ++i) { + if (m_broadcast[i] != 1) { + nByOne = false; + break; + } + } + } + + // Handle special format like NCHW, its input shape is '[1, N..., 1]' and + // broadcast shape is '[N, 1..., N]' + if (!oneByN && !nByOne) { + if (input_dims[0] == 1 && input_dims[NumDims-1] == 1 && NumDims > 2) { + nByOne = true; + oneByN = true; + for (int i = 1; i < NumDims-1; ++i) { + if (m_broadcast[i] != 1) { + nByOne = false; + oneByN = false; + break; + } + } + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffReturnType coeff(Index index) const + { + if (internal::is_input_scalar>::value) { + return m_impl.coeff(0); + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + if (isCopy) { + return m_impl.coeff(index); + } else { + return coeffColMajor(index); + } + } else { + if (isCopy) { + return m_impl.coeff(index); + } else { + return coeffRowMajor(index); + } + } + } + + // TODO: attempt to speed this up. The integer divisions and modulo are slow + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexColMajor(Index index) const { + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx < m_impl.dimensions()[i]); + inputIndex += idx * m_inputStrides[i]; + } else { + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx % m_impl.dimensions()[i] == 0); + } else { + inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i]; + } + } + index -= idx * m_outputStrides[i]; + } + if (internal::index_statically_eq(0, 1)) { + eigen_assert(index < m_impl.dimensions()[0]); + inputIndex += index; + } else { + if (internal::index_statically_eq(0, 1)) { + eigen_assert(index % m_impl.dimensions()[0] == 0); + } else { + inputIndex += (index % m_impl.dimensions()[0]); + } + } + return inputIndex; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffColMajor(Index index) const + { + return m_impl.coeff(indexColMajor(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexRowMajor(Index index) const { + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStrides[i]; + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx < m_impl.dimensions()[i]); + inputIndex += idx * m_inputStrides[i]; + } else { + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx % m_impl.dimensions()[i] == 0); + } else { + inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i]; + } + } + index -= idx * m_outputStrides[i]; + } + if (internal::index_statically_eq(NumDims - 1, 1)) { + eigen_assert(index < m_impl.dimensions()[NumDims - 1]); + inputIndex += index; + } else { + if (internal::index_statically_eq(NumDims - 1, 1)) { + eigen_assert(index % m_impl.dimensions()[NumDims - 1] == 0); + } else { + inputIndex += (index % m_impl.dimensions()[NumDims - 1]); + } + } + return inputIndex; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffRowMajor(Index index) const + { + return m_impl.coeff(indexRowMajor(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketReturnType packet(Index index) const + { + if (internal::is_input_scalar>::value) { + return internal::pset1(m_impl.coeff(0)); + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + if (isCopy) { + #ifdef EIGEN_GPU_COMPILE_PHASE + // See PR 437: on NVIDIA P100 and K20m we observed a x3-4 speed up by enforcing + // unaligned loads here. The reason is unclear though. + return m_impl.template packet(index); + #else + return m_impl.template packet(index); + #endif + } else if (oneByN && !nByOne) { + return packetNByOne(index); + } else if (!oneByN && nByOne) { + return packetOneByN(index); + } else if (oneByN && nByOne) { + return packetOneByNByOne(index); + } else { + return packetColMajor(index); + } + } else { + if (isCopy) { + #ifdef EIGEN_GPU_COMPILE_PHASE + // See above. + return m_impl.template packet(index); + #else + return m_impl.template packet(index); + #endif + } else if (oneByN && !nByOne) { + return packetOneByN(index); + } else if (!oneByN && nByOne) { + return packetNByOne(index); + } else if (oneByN && nByOne) { + return packetOneByNByOne(index); + } else { + return packetRowMajor(index); + } + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByNByOne + (Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + Index startDim, endDim; + Index inputIndex, outputOffset, batchedIndex; + + if (static_cast(Layout) == static_cast(ColMajor)) { + startDim = NumDims - 1; + endDim = 1; + } else { + startDim = 0; + endDim = NumDims - 2; + } + + batchedIndex = index % m_outputStrides[startDim]; + inputIndex = batchedIndex / m_outputStrides[endDim]; + outputOffset = batchedIndex % m_outputStrides[endDim]; + + if (outputOffset + PacketSize <= m_outputStrides[endDim]) { + values[0] = m_impl.coeff(inputIndex); + return internal::pload1(values); + } else { + EIGEN_UNROLL_LOOP + for (int i = 0, cur = 0; i < PacketSize; ++i, ++cur) { + if (outputOffset + cur < m_outputStrides[endDim]) { + values[i] = m_impl.coeff(inputIndex); + } else { + ++inputIndex; + inputIndex = (inputIndex == m_inputStrides[startDim] ? 0 : inputIndex); + values[i] = m_impl.coeff(inputIndex); + outputOffset = 0; + cur = 0; + } + } + return internal::pload(values); + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByN(Index index) const + { + // Consider the flattened tensor [v0, ..., vN], + // Concatenates m_broadcast[dim] copies, + // [v0, ..., vN, v0, ..., vN, ... ] + // with dim == NumDims - 1 for col-major, dim == 0 for row-major. + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + // Size of flattened tensor. + const Index M = (static_cast(Layout) == static_cast(ColMajor)) ? + m_inputStrides[NumDims - 1] : m_inputStrides[0]; + Index inputIndex = index % M; + if (inputIndex + PacketSize <= M) { + return m_impl.template packet(inputIndex); + } else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + if (inputIndex > M - 1) { + inputIndex = 0; + } + values[i] = m_impl.coeff(inputIndex++); + } + return internal::pload(values); + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetNByOne(Index index) const + { + // Consider the flattened tensor [v0, ..., vN], + // Interleaves m_broadcast[dim] copies, + // [v0, v0, ..., v1, v1, ..., vN, vN, ... ] + // with dim == 0 for col-major, dim == NumDims - 1 for row-major. + eigen_assert(index + PacketSize-1 < dimensions().TotalSize()); + + const Index M = (static_cast(Layout) == static_cast(ColMajor)) ? + m_broadcast[0] : m_broadcast[NumDims - 1]; + + Index inputIndex = index / M; + Index outputOffset = index % M; + if (outputOffset + PacketSize <= M) { + return internal::pset1(m_impl.coeff(inputIndex)); + } else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + if (outputOffset < M) { + values[i] = m_impl.coeff(inputIndex); + ++outputOffset; + } else { + values[i] = m_impl.coeff(++inputIndex); + outputOffset = 1; // Next offset. + } + } + return internal::pload(values); + } + } + + // Ignore the LoadMode and always use unaligned loads since we can't guarantee + // the alignment at compile time. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetColMajor(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + const Index originalIndex = index; + + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx < m_impl.dimensions()[i]); + inputIndex += idx * m_inputStrides[i]; + } else { + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx % m_impl.dimensions()[i] == 0); + } else { + inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i]; + } + } + index -= idx * m_outputStrides[i]; + } + Index innermostLoc; + if (internal::index_statically_eq(0, 1)) { + eigen_assert(index < m_impl.dimensions()[0]); + innermostLoc = index; + } else { + if (internal::index_statically_eq(0, 1)) { + eigen_assert(index % m_impl.dimensions()[0] == 0); + innermostLoc = 0; + } else { + innermostLoc = index % m_impl.dimensions()[0]; + } + } + inputIndex += innermostLoc; + + // Todo: this could be extended to the second dimension if we're not + // broadcasting alongside the first dimension, and so on. + if (innermostLoc + PacketSize <= m_impl.dimensions()[0]) { + return m_impl.template packet(inputIndex); + } else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + values[0] = m_impl.coeff(inputIndex); + EIGEN_UNROLL_LOOP + for (int i = 1; i < PacketSize; ++i) { + if (innermostLoc + i < m_impl.dimensions()[0]) { + values[i] = m_impl.coeff(inputIndex+i); + } else { + values[i] = coeffColMajor(originalIndex+i); + } + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetRowMajor(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + const Index originalIndex = index; + + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStrides[i]; + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx < m_impl.dimensions()[i]); + inputIndex += idx * m_inputStrides[i]; + } else { + if (internal::index_statically_eq(i, 1)) { + eigen_assert(idx % m_impl.dimensions()[i] == 0); + } else { + inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i]; + } + } + index -= idx * m_outputStrides[i]; + } + Index innermostLoc; + if (internal::index_statically_eq(NumDims-1, 1)) { + eigen_assert(index < m_impl.dimensions()[NumDims-1]); + innermostLoc = index; + } else { + if (internal::index_statically_eq(NumDims-1, 1)) { + eigen_assert(index % m_impl.dimensions()[NumDims-1] == 0); + innermostLoc = 0; + } else { + innermostLoc = index % m_impl.dimensions()[NumDims-1]; + } + } + inputIndex += innermostLoc; + + // Todo: this could be extended to the second dimension if we're not + // broadcasting alongside the first dimension, and so on. + if (innermostLoc + PacketSize <= m_impl.dimensions()[NumDims-1]) { + return m_impl.template packet(inputIndex); + } else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + values[0] = m_impl.coeff(inputIndex); + EIGEN_UNROLL_LOOP + for (int i = 1; i < PacketSize; ++i) { + if (innermostLoc + i < m_impl.dimensions()[NumDims-1]) { + values[i] = m_impl.coeff(inputIndex+i); + } else { + values[i] = coeffRowMajor(originalIndex+i); + } + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + double compute_cost = TensorOpCost::AddCost(); + if (!isCopy && NumDims > 0) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + compute_cost += TensorOpCost::DivCost(); + if (internal::index_statically_eq(i, 1)) { + compute_cost += + TensorOpCost::MulCost() + TensorOpCost::AddCost(); + } else { + if (!internal::index_statically_eq(i, 1)) { + compute_cost += TensorOpCost::MulCost() + + TensorOpCost::ModCost() + + TensorOpCost::AddCost(); + } + } + compute_cost += + TensorOpCost::MulCost() + TensorOpCost::AddCost(); + } + } + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + // TODO(wuke): Targeting L1 size is 30% faster than targeting L{-1} on large + // tensors. But this might need further tuning. + const size_t target_size = m_device.firstLevelCacheSize(); + return internal::TensorBlockResourceRequirements::merge( + m_impl.getResourceRequirements(), + internal::TensorBlockResourceRequirements::skewed(target_size)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + BlockBroadcastingParams params = blockBroadcastingParams(desc); + + if (params.inner_dim_size == 0 || params.bcast_dim_size == 0) { + return emptyBlock(); + } + + // Prepare storage for the materialized broadcasting result. + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage(desc, scratch); + ScalarNoConst* materialized_output = block_storage.data(); + + // We potentially will need to materialize input blocks. + size_t materialized_input_size = 0; + ScalarNoConst* materialized_input = NULL; + + // Initialize block broadcating iterator state for outer dimensions (outer + // with regard to bcast dimension). Dimension in this array are always in + // inner_most -> outer_most order (col major layout). + array it; + int idx = 0; + + for (int i = params.inner_dim_count + 1; i < NumDims; ++i) { + const Index dim = IsColMajor ? i : NumDims - 1 - i; + it[idx].size = params.output_dims[dim]; + it[idx].count = 0; + it[idx].output_stride = m_outputStrides[dim]; + it[idx].output_span = it[idx].output_stride * (it[idx].size - 1); + idx++; + } + + // Write output into the beginning of `materialized_output`. + Index output_offset = 0; + + // We will fill output block by broadcasting along the bcast dim, and + // iterating over outer dimension. + const Index output_size = NumDims == 0 ? 1 : params.output_dims.TotalSize(); + + for (Index num_output_coeffs = 0; num_output_coeffs < output_size;) { + ScalarNoConst* bcast_output = materialized_output + num_output_coeffs; + Index bcast_offset = desc.offset() + output_offset; + + // Broadcast along the bcast dimension. + num_output_coeffs += BroadcastBlockAlongBcastDim( + params, bcast_offset, scratch, bcast_output, &materialized_input, + &materialized_input_size); + + // Switch to the next outer dimension. + for (int j = 0; j < idx; ++j) { + if (++it[j].count < it[j].size) { + output_offset += it[j].output_stride; + break; + } + it[j].count = 0; + output_offset -= it[j].output_span; + } + } + + return block_storage.AsTensorMaterializedBlock(); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + const TensorEvaluator& impl() const { return m_impl; } + + Broadcast functor() const { return m_broadcast; } + private: + static constexpr bool IsColMajor = + static_cast(Layout) == static_cast(ColMajor); + + // We will build a general case block broadcasting on top of broadcasting + // primitive that will do broadcasting only for the inner dimension(s) along + // the first dimension smaller than the input size (it's called `bcast_dim`). + // + // Example: + // dim: 0 1 2 (ColMajor) + // input size: [9, 3, 6] + // block size: [9, 2, 6] + // + // We will compute broadcasted block by iterating over the outer dimensions + // before `bcast_dim` (only dimension `2` in this example) and computing + // broadcasts along the `bcast_dim` (dimension `1` in this example). + + // BlockBroadcastingParams holds precomputed parameters for broadcasting a + // single block along the broadcasting dimension. Sizes and strides along the + // `bcast_dim` might be invalid, they will be adjusted later in + // `BroadcastBlockAlongBcastDim`. + struct BlockBroadcastingParams { + Dimensions input_dims; // input expression dimensions + Dimensions output_dims; // output block sizes + Dimensions output_strides; // output block strides + + int inner_dim_count; // count inner dimensions matching in size + int bcast_dim; // broadcasting dimension index + Index bcast_dim_size; // broadcasting dimension size + Index inner_dim_size; // inner dimensions size + + // Block sizes and strides for the input block where all dimensions before + // `bcast_dim` are equal to `1`. + Dimensions input_block_sizes; + Dimensions input_block_strides; + + // Block sizes and strides for blocks with extra dimensions and strides `0`. + BroadcastDimensions bcast_block_sizes; + BroadcastDimensions bcast_block_strides; + BroadcastDimensions bcast_input_strides; + }; + + struct BlockBroadcastingIteratorState { + Index size; + Index count; + Index output_stride; + Index output_span; + }; + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE BlockBroadcastingParams + blockBroadcastingParams(TensorBlockDesc& desc) const { + BlockBroadcastingParams params; + + params.input_dims = Dimensions(m_impl.dimensions()); + + // Output block sizes and strides. + params.output_dims = desc.dimensions(); + params.output_strides = internal::strides(params.output_dims); + + // Find the broadcasting dimension (first dimension with output size smaller + // that the input size). + params.bcast_dim = 0; + params.bcast_dim_size = 1; + params.inner_dim_size = 1; + + // Count the number of inner dimensions that have the same size in the block + // and in the broadcast expression. + params.inner_dim_count = 0; + + for (int i = 0; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + + if (params.output_dims[dim] == m_dimensions[dim]) { + params.inner_dim_size *= params.output_dims[dim]; + ++params.inner_dim_count; + continue; + } + + // First non-matching dimension is the broadcasting dimension. + eigen_assert(params.output_dims[dim] < m_dimensions[dim]); + params.bcast_dim = dim; + params.bcast_dim_size = params.output_dims[dim]; + break; + } + + // Calculate the input block size for looking into the input. + for (int i = 0; i < params.inner_dim_count; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + params.input_block_sizes[dim] = params.input_dims[dim]; + } + for (int i = params.inner_dim_count; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + params.input_block_sizes[dim] = 1; + } + params.input_block_strides = + internal::strides(params.input_block_sizes); + + // Broadcast with the 0-stride trick: Create 1 extra dim for each + // broadcast, set the input stride to 0. + // + // When ColMajor: + // + // - bcast_block_sizes: + // [d_0, b_0, d_1, b_1, ...] + // + // - bcast_block_strides: + // [output_block_strides[0], output_block_strides[0] * d_0, + // output_block_strides[1], output_block_strides[1] * d_1, + // ...] + // + // - bcast_input_strides: + // [input_block_strides[0], 0, + // input_block_strides[1], 0, + // ...]. + // + for (int i = 0; i < params.inner_dim_count; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + + const int copy_dim = IsColMajor ? 2 * i : 2 * NumDims - 2 * i - 1; + const int broadcast_dim = IsColMajor ? copy_dim + 1 : copy_dim - 1; + + params.bcast_block_sizes[copy_dim] = params.input_dims[dim]; + params.bcast_block_sizes[broadcast_dim] = m_broadcast[dim]; + params.bcast_block_strides[copy_dim] = params.output_strides[dim]; + params.bcast_block_strides[broadcast_dim] = + params.output_strides[dim] * params.input_dims[dim]; + params.bcast_input_strides[copy_dim] = params.input_block_strides[dim]; + params.bcast_input_strides[broadcast_dim] = 0; + } + + for (int i = 2 * params.inner_dim_count; i < 2 * NumDims; ++i) { + const int dim = IsColMajor ? i : 2 * NumDims - i - 1; + params.bcast_block_sizes[dim] = 1; + params.bcast_block_strides[dim] = 0; + params.bcast_input_strides[dim] = 0; + } + + return params; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock emptyBlock() const { + DSizes dimensions; + for (int i = 0; i < NumDims; ++i) dimensions[i] = 0; + return TensorBlock(internal::TensorBlockKind::kView, NULL, dimensions); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlockAlongBcastDim( + BlockBroadcastingParams params, Index bcast_offset, + TensorBlockScratch& scratch, ScalarNoConst* materialized_output, + ScalarNoConst** materialized_input, + size_t* materialized_input_size) const { + if (params.bcast_dim_size == 1) { + // We just need one block read using the ready-set values above. + return BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, 0, scratch, + materialized_output, materialized_input, materialized_input_size); + + } else if (params.input_dims[params.bcast_dim] == 1) { + // Broadcast bcast dimension (< NumDims) by bcast_dim_size. + const int broadcast_bcast_dim = + IsColMajor ? 2 * params.inner_dim_count + 1 + : 2 * NumDims - 2 * params.inner_dim_count - 2; + + params.bcast_block_sizes[broadcast_bcast_dim] = params.bcast_dim_size; + params.bcast_input_strides[broadcast_bcast_dim] = 0; + params.bcast_block_strides[broadcast_bcast_dim] = + params.output_strides[params.bcast_dim]; + + return BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, 0, scratch, + materialized_output, materialized_input, materialized_input_size); + + } else { + // Keep track of the total number of the coefficients written to the + // output block. + Index num_output_coeffs = 0; + + // The general case. Let's denote the output block as + // + // x[..., a:a+bcast_dim_size, :, ..., :] + // + // where a:a+bcast_dim_size is a slice on the bcast_dim dimension + // (< NumDims). We need to split the a:a+bcast_dim_size into possibly 3 + // sub-blocks: + // + // (1) a:b, where b is the smallest multiple of + // input_dims[bcast_dim_start] in [a, a+bcast_dim_size]. + // + // (2) b:c, where c is the largest multiple of input_dims[bcast_dim_start] + // in [a, a+bcast_dim_size]. + // + // (3) c:a+bcast_dim_size . + // + // Or, when b and c do not exist, we just need to process the whole block + // together. + + // Find a. + const Index bcast_dim_left_index = + bcast_offset / m_outputStrides[params.bcast_dim]; + + // Find b and c. + const Index input_bcast_dim_size = params.input_dims[params.bcast_dim]; + + // First multiple after a. This is b when <= bcast_dim_left_index + + // bcast_dim_size. + const Index first_multiple = + divup(bcast_dim_left_index, input_bcast_dim_size) * + input_bcast_dim_size; + + if (first_multiple <= bcast_dim_left_index + params.bcast_dim_size) { + // b exists, so does c. Find it. + const Index last_multiple = + (bcast_dim_left_index + params.bcast_dim_size) / + input_bcast_dim_size * input_bcast_dim_size; + const int copy_bcast_dim = + IsColMajor ? 2 * params.inner_dim_count + : 2 * NumDims - 2 * params.inner_dim_count - 1; + const int broadcast_bcast_dim = + IsColMajor ? 2 * params.inner_dim_count + 1 + : 2 * NumDims - 2 * params.inner_dim_count - 2; + + if (first_multiple > bcast_dim_left_index) { + const Index head_size = first_multiple - bcast_dim_left_index; + params.input_block_sizes[params.bcast_dim] = head_size; + params.bcast_block_sizes[copy_bcast_dim] = head_size; + params.bcast_input_strides[copy_bcast_dim] = + params.input_block_strides[params.bcast_dim]; + params.bcast_block_strides[copy_bcast_dim] = + params.output_strides[params.bcast_dim]; + params.bcast_block_sizes[broadcast_bcast_dim] = 1; + params.bcast_input_strides[broadcast_bcast_dim] = 0; + params.bcast_block_strides[broadcast_bcast_dim] = + params.output_strides[params.bcast_dim] * + params.input_dims[params.bcast_dim]; + + num_output_coeffs += BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, 0, scratch, + materialized_output, materialized_input, materialized_input_size); + } + if (first_multiple < last_multiple) { + params.input_block_sizes[params.bcast_dim] = input_bcast_dim_size; + params.bcast_block_sizes[copy_bcast_dim] = input_bcast_dim_size; + params.bcast_input_strides[copy_bcast_dim] = + params.input_block_strides[params.bcast_dim]; + params.bcast_block_strides[copy_bcast_dim] = + params.output_strides[params.bcast_dim]; + params.bcast_block_sizes[broadcast_bcast_dim] = + (last_multiple - first_multiple) / input_bcast_dim_size; + params.bcast_input_strides[broadcast_bcast_dim] = 0; + params.bcast_block_strides[broadcast_bcast_dim] = + params.output_strides[params.bcast_dim] * + params.input_dims[params.bcast_dim]; + const Index offset = (first_multiple - bcast_dim_left_index) * + m_outputStrides[params.bcast_dim]; + + num_output_coeffs += BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, offset, scratch, + materialized_output, materialized_input, materialized_input_size); + } + if (last_multiple < bcast_dim_left_index + params.bcast_dim_size) { + const Index tail_size = + bcast_dim_left_index + params.bcast_dim_size - last_multiple; + params.input_block_sizes[params.bcast_dim] = tail_size; + params.bcast_block_sizes[copy_bcast_dim] = tail_size; + params.bcast_input_strides[copy_bcast_dim] = + params.input_block_strides[params.bcast_dim]; + params.bcast_block_strides[copy_bcast_dim] = + params.output_strides[params.bcast_dim]; + params.bcast_block_sizes[broadcast_bcast_dim] = 1; + params.bcast_input_strides[broadcast_bcast_dim] = 0; + params.bcast_block_strides[broadcast_bcast_dim] = + params.output_strides[params.bcast_dim] * + params.input_dims[params.bcast_dim]; + const Index offset = (last_multiple - bcast_dim_left_index) * + m_outputStrides[params.bcast_dim]; + + num_output_coeffs += BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, offset, scratch, + materialized_output, materialized_input, materialized_input_size); + } + } else { + // b and c do not exist. + const int copy_bcast_dim = + IsColMajor ? 2 * params.inner_dim_count + : 2 * NumDims - 2 * params.inner_dim_count - 1; + params.input_block_sizes[params.bcast_dim] = params.bcast_dim_size; + params.bcast_block_sizes[copy_bcast_dim] = params.bcast_dim_size; + params.bcast_input_strides[copy_bcast_dim] = + params.input_block_strides[params.bcast_dim]; + params.bcast_block_strides[copy_bcast_dim] = + params.output_strides[params.bcast_dim]; + + num_output_coeffs += BroadcastBlock( + params.input_block_sizes, params.input_block_strides, + params.bcast_block_sizes, params.bcast_block_strides, + params.bcast_input_strides, bcast_offset, 0, scratch, + materialized_output, materialized_input, materialized_input_size); + } + + return num_output_coeffs; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlock( + const Dimensions& input_block_sizes, + const Dimensions& input_block_strides, + const BroadcastDimensions& bcast_block_sizes, + const BroadcastDimensions& bcast_block_strides, + const BroadcastDimensions& bcast_input_strides, Index bcast_offset, + Index offset, TensorBlockScratch& scratch, + ScalarNoConst* materialized_output, ScalarNoConst** materialized_input, + size_t* materialized_input_size) const { + // ---------------------------------------------------------------------- // + // Tensor block descriptor for reading block from the input. + const Index input_offset = bcast_offset + offset; + TensorBlockDesc input_desc( + IsColMajor ? indexColMajor(input_offset) : indexRowMajor(input_offset), + input_block_sizes); + + ArgTensorBlock input_block = m_impl.block(input_desc, scratch); + + // ---------------------------------------------------------------------- // + // Materialize input block into a temporary memory buffer only if it's not + // already available in the arg block. + const ScalarNoConst* input_buffer = NULL; + + if (input_block.data() != NULL) { + // Input block already has raw data, there is no need to materialize it. + input_buffer = input_block.data(); + + } else { + // Otherwise we have to do block assignment into a temporary buffer. + + // Maybe reuse previously allocated buffer, or allocate a new one with a + // scratch allocator. + const size_t input_total_size = input_block_sizes.TotalSize(); + if (*materialized_input == NULL || + *materialized_input_size < input_total_size) { + *materialized_input_size = input_total_size; + void* mem = scratch.allocate(*materialized_input_size * sizeof(Scalar)); + *materialized_input = static_cast(mem); + } + + typedef internal::TensorBlockAssignment< + ScalarNoConst, NumDims, typename ArgTensorBlock::XprType, Index> + TensorBlockAssignment; + + TensorBlockAssignment::Run( + TensorBlockAssignment::target(input_block_sizes, input_block_strides, + *materialized_input), + input_block.expr()); + + input_buffer = *materialized_input; + } + + // ---------------------------------------------------------------------- // + // Copy data from materialized input block to the materialized output, using + // given broadcast strides (strides with zeroes). + typedef internal::TensorBlockIO + TensorBlockIO; + + typename TensorBlockIO::Src src(bcast_input_strides, input_buffer); + typename TensorBlockIO::Dst dst(bcast_block_sizes, bcast_block_strides, + materialized_output + offset); + + return TensorBlockIO::Copy(dst, src); + } + +protected: + const Device EIGEN_DEVICE_REF m_device; + const std::remove_reference_t m_broadcast; + Dimensions m_dimensions; + array m_outputStrides; + array m_inputStrides; + TensorEvaluator m_impl; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_BROADCASTING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h new file mode 100644 index 0000000000000000000000000000000000000000..dc3fc18477ad956992275e2a4f3c6f49503ca584 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h @@ -0,0 +1,511 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H +#define EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorKChippingReshaping + * \ingroup CXX11_Tensor_Module + * + * \brief A chip is a thin slice, corresponding to a column or a row in a 2-d tensor. + * + * + */ + +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions - 1; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorChippingOp EIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorChippingOp type; +}; + +template +struct DimensionId +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) { + EIGEN_UNUSED_VARIABLE(dim); + eigen_assert(dim == DimId); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const { + return DimId; + } +}; +template <> +struct DimensionId +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) : actual_dim(dim) { + eigen_assert(dim >= 0); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const { + return actual_dim; + } + private: + const DenseIndex actual_dim; +}; + + +} // end namespace internal + + + +template +class TensorChippingOp : public TensorBase > +{ + public: + typedef TensorBase > Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorChippingOp(const XprType& expr, const Index offset, const Index dim) + : m_xpr(expr), m_offset(offset), m_dim(dim) { + } + + EIGEN_DEVICE_FUNC + const Index offset() const { return m_offset; } + EIGEN_DEVICE_FUNC + const Index dim() const { return m_dim.actualDim(); } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorChippingOp) + + protected: + typename XprType::Nested m_xpr; + const Index m_offset; + const internal::DimensionId m_dim; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorChippingOp XprType; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + static constexpr int NumDims = NumInputDims-1; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + static constexpr int Layout = TensorEvaluator::Layout; + + enum { + // Alignment can't be guaranteed at compile time since it depends on the + // slice offsets. + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::BlockAccess, + // Chipping of outer-most dimension is a trivial operation, because we can + // read and write directly from the underlying tensor using single offset. + IsOuterChipping = (Layout == ColMajor && DimId == NumInputDims - 1) || + (Layout == RowMajor && DimId == 0), + // Chipping inner-most dimension. + IsInnerChipping = (Layout == ColMajor && DimId == 0) || + (Layout == RowMajor && DimId == NumInputDims - 1), + // Prefer block access if the underlying expression prefers it, otherwise + // only if chipping is not trivial. + PreferBlockAccess = TensorEvaluator::PreferBlockAccess || + !IsOuterChipping, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef internal::TensorBlockDescriptor + ArgTensorBlockDesc; + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_dim(op.dim()), m_device(device) + { + EIGEN_STATIC_ASSERT((NumInputDims >= 1), YOU_MADE_A_PROGRAMMING_MISTAKE); + eigen_assert(NumInputDims > m_dim.actualDim()); + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + eigen_assert(op.offset() < input_dims[m_dim.actualDim()]); + + int j = 0; + for (int i = 0; i < NumInputDims; ++i) { + if (i != m_dim.actualDim()) { + m_dimensions[j] = input_dims[i]; + ++j; + } + } + + m_stride = 1; + m_inputStride = 1; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < m_dim.actualDim(); ++i) { + m_stride *= input_dims[i]; + m_inputStride *= input_dims[i]; + } + } else { + for (int i = NumInputDims-1; i > m_dim.actualDim(); --i) { + m_stride *= input_dims[i]; + m_inputStride *= input_dims[i]; + } + } + m_inputStride *= input_dims[m_dim.actualDim()]; + m_inputOffset = m_stride * op.offset(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_impl.coeff(srcCoeff(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + if (isInnerChipping()) { + // m_stride is equal to 1, so let's avoid the integer division. + eigen_assert(m_stride == 1); + Index inputIndex = index * m_inputStride + m_inputOffset; + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = m_impl.coeff(inputIndex); + inputIndex += m_inputStride; + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } else if (isOuterChipping()) { + // m_stride is always greater than index, so let's avoid the integer division. + eigen_assert(m_stride > index); + return m_impl.template packet(index + m_inputOffset); + } else { + const Index idx = index / m_stride; + const Index rem = index - idx * m_stride; + if (rem + PacketSize <= m_stride) { + Index inputIndex = idx * m_inputStride + m_inputOffset + rem; + return m_impl.template packet(inputIndex); + } else { + // Cross the stride boundary. Fallback to slow path. + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index); + ++index; + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + double cost = 0; + if ((static_cast(Layout) == static_cast(ColMajor) && + m_dim.actualDim() == 0) || + (static_cast(Layout) == static_cast(RowMajor) && + m_dim.actualDim() == NumInputDims - 1)) { + cost += TensorOpCost::MulCost() + TensorOpCost::AddCost(); + } else if ((static_cast(Layout) == static_cast(ColMajor) && + m_dim.actualDim() == NumInputDims - 1) || + (static_cast(Layout) == static_cast(RowMajor) && + m_dim.actualDim() == 0)) { + cost += TensorOpCost::AddCost(); + } else { + cost += 3 * TensorOpCost::MulCost() + TensorOpCost::DivCost() + + 3 * TensorOpCost::AddCost(); + } + + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + const size_t target_size = m_device.lastLevelCacheSize(); + return internal::TensorBlockResourceRequirements::merge( + internal::TensorBlockResourceRequirements::skewed(target_size), + m_impl.getResourceRequirements()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool root_of_expr_ast = false) const { + const Index chip_dim = m_dim.actualDim(); + + DSizes input_block_dims; + for (int i = 0; i < NumInputDims; ++i) { + input_block_dims[i] + = i < chip_dim ? desc.dimension(i) + : i > chip_dim ? desc.dimension(i - 1) + : 1; + } + + ArgTensorBlockDesc arg_desc(srcCoeff(desc.offset()), input_block_dims); + + // Try to reuse destination buffer for materializing argument block. + if (desc.HasDestinationBuffer()) { + DSizes arg_destination_strides; + for (int i = 0; i < NumInputDims; ++i) { + arg_destination_strides[i] + = i < chip_dim ? desc.destination().strides()[i] + : i > chip_dim ? desc.destination().strides()[i - 1] + : 0; // for dimensions of size `1` stride should never be used. + } + + arg_desc.template AddDestinationBuffer( + desc.destination().template data(), + arg_destination_strides); + } + + ArgTensorBlock arg_block = m_impl.block(arg_desc, scratch, root_of_expr_ast); + if (!arg_desc.HasDestinationBuffer()) desc.DropDestinationBuffer(); + + if (arg_block.data() != NULL) { + // Forward argument block buffer if possible. + return TensorBlock(arg_block.kind(), arg_block.data(), + desc.dimensions()); + + } else { + // Assign argument block expression to a buffer. + + // Prepare storage for the materialized chipping result. + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage(desc, scratch); + + typedef internal::TensorBlockAssignment< + ScalarNoConst, NumInputDims, typename ArgTensorBlock::XprType, Index> + TensorBlockAssignment; + + TensorBlockAssignment::Run( + TensorBlockAssignment::target( + arg_desc.dimensions(), + internal::strides(arg_desc.dimensions()), + block_storage.data()), + arg_block.expr()); + + return block_storage.AsTensorMaterializedBlock(); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const { + typename Storage::Type result = constCast(m_impl.data()); + if (isOuterChipping() && result) { + return result + m_inputOffset; + } else { + return NULL; + } + } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const + { + Index inputIndex; + if (isInnerChipping()) { + // m_stride is equal to 1, so let's avoid the integer division. + eigen_assert(m_stride == 1); + inputIndex = index * m_inputStride + m_inputOffset; + } else if (isOuterChipping()) { + // m_stride is always greater than index, so let's avoid the integer + // division. + eigen_assert(m_stride > index); + inputIndex = index + m_inputOffset; + } else { + const Index idx = index / m_stride; + inputIndex = idx * m_inputStride + m_inputOffset; + index -= idx * m_stride; + inputIndex += index; + } + return inputIndex; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isInnerChipping() const { + return IsInnerChipping || + (static_cast(Layout) == ColMajor && m_dim.actualDim() == 0) || + (static_cast(Layout) == RowMajor && m_dim.actualDim() == NumInputDims - 1); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isOuterChipping() const { + return IsOuterChipping || + (static_cast(Layout) == ColMajor && m_dim.actualDim() == NumInputDims-1) || + (static_cast(Layout) == RowMajor && m_dim.actualDim() == 0); + } + + Dimensions m_dimensions; + Index m_stride; + Index m_inputOffset; + Index m_inputStride; + TensorEvaluator m_impl; + const internal::DimensionId m_dim; + const Device EIGEN_DEVICE_REF m_device; +}; + + +// Eval as lvalue +template +struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + typedef TensorChippingOp XprType; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + static constexpr int NumDims = NumInputDims-1; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::RawAccess, + Layout = TensorEvaluator::Layout, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + return this->m_impl.coeffRef(this->srcCoeff(index)); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + if (this->isInnerChipping()) { + // m_stride is equal to 1, so let's avoid the integer division. + eigen_assert(this->m_stride == 1); + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + internal::pstore(values, x); + Index inputIndex = index * this->m_inputStride + this->m_inputOffset; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + this->m_impl.coeffRef(inputIndex) = values[i]; + inputIndex += this->m_inputStride; + } + } else if (this->isOuterChipping()) { + // m_stride is always greater than index, so let's avoid the integer division. + eigen_assert(this->m_stride > index); + this->m_impl.template writePacket(index + this->m_inputOffset, x); + } else { + const Index idx = index / this->m_stride; + const Index rem = index - idx * this->m_stride; + if (rem + PacketSize <= this->m_stride) { + const Index inputIndex = idx * this->m_inputStride + this->m_inputOffset + rem; + this->m_impl.template writePacket(inputIndex, x); + } else { + // Cross stride boundary. Fallback to slow path. + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + internal::pstore(values, x); + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + this->coeffRef(index) = values[i]; + ++index; + } + } + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock( + const TensorBlockDesc& desc, const TensorBlock& block) { + eigen_assert(this->m_impl.data() != NULL); + + const Index chip_dim = this->m_dim.actualDim(); + + DSizes input_block_dims; + for (int i = 0; i < NumInputDims; ++i) { + input_block_dims[i] = i < chip_dim ? desc.dimension(i) + : i > chip_dim ? desc.dimension(i - 1) + : 1; + } + + typedef TensorReshapingOp, + const typename TensorBlock::XprType> + TensorBlockExpr; + + typedef internal::TensorBlockAssignment + TensorBlockAssign; + + TensorBlockAssign::Run( + TensorBlockAssign::target( + input_block_dims, + internal::strides(this->m_impl.dimensions()), + this->m_impl.data(), this->srcCoeff(desc.offset())), + block.expr().reshape(input_block_dims)); + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h new file mode 100644 index 0000000000000000000000000000000000000000..2be7692a703e5221a61235888d2c2bf48c60dcca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h @@ -0,0 +1,371 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorConcatenationOp + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor concatenation class. + * + * + */ +namespace internal { +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef typename promote_storage_type::ret Scalar; + typedef typename promote_storage_type::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename LhsXprType::Nested LhsNested; + typedef typename RhsXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = traits::Layout; + enum { Flags = 0 }; + typedef std::conditional_t::val, + typename traits::PointerType, typename traits::PointerType> PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorConcatenationOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorConcatenationOp type; +}; + +} // end namespace internal + + +template +class TensorConcatenationOp : public TensorBase, WriteAccessors> +{ + public: + typedef TensorBase, WriteAccessors> Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef typename internal::nested::type Nested; + typedef typename internal::promote_storage_type::ret CoeffReturnType; + typedef typename NumTraits::Real RealScalar; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConcatenationOp(const LhsXprType& lhs, const RhsXprType& rhs, Axis axis) + : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_axis(axis) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + lhsExpression() const { return m_lhs_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + rhsExpression() const { return m_rhs_xpr; } + + EIGEN_DEVICE_FUNC const Axis& axis() const { return m_axis; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorConcatenationOp) + protected: + typename LhsXprType::Nested m_lhs_xpr; + typename RhsXprType::Nested m_rhs_xpr; + const Axis m_axis; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorConcatenationOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + static constexpr int RightNumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_leftImpl(op.lhsExpression(), device), m_rightImpl(op.rhsExpression(), device), m_axis(op.axis()) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout) || NumDims == 1), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT((NumDims == RightNumDims), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + + eigen_assert(0 <= m_axis && m_axis < NumDims); + const Dimensions& lhs_dims = m_leftImpl.dimensions(); + const Dimensions& rhs_dims = m_rightImpl.dimensions(); + { + int i = 0; + for (; i < m_axis; ++i) { + eigen_assert(lhs_dims[i] > 0); + eigen_assert(lhs_dims[i] == rhs_dims[i]); + m_dimensions[i] = lhs_dims[i]; + } + eigen_assert(lhs_dims[i] > 0); // Now i == m_axis. + eigen_assert(rhs_dims[i] > 0); + m_dimensions[i] = lhs_dims[i] + rhs_dims[i]; + for (++i; i < NumDims; ++i) { + eigen_assert(lhs_dims[i] > 0); + eigen_assert(lhs_dims[i] == rhs_dims[i]); + m_dimensions[i] = lhs_dims[i]; + } + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_leftStrides[0] = 1; + m_rightStrides[0] = 1; + m_outputStrides[0] = 1; + + for (int j = 1; j < NumDims; ++j) { + m_leftStrides[j] = m_leftStrides[j-1] * lhs_dims[j-1]; + m_rightStrides[j] = m_rightStrides[j-1] * rhs_dims[j-1]; + m_outputStrides[j] = m_outputStrides[j-1] * m_dimensions[j-1]; + } + } else { + m_leftStrides[NumDims - 1] = 1; + m_rightStrides[NumDims - 1] = 1; + m_outputStrides[NumDims - 1] = 1; + + for (int j = NumDims - 2; j >= 0; --j) { + m_leftStrides[j] = m_leftStrides[j+1] * lhs_dims[j+1]; + m_rightStrides[j] = m_rightStrides[j+1] * rhs_dims[j+1]; + m_outputStrides[j] = m_outputStrides[j+1] * m_dimensions[j+1]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + // TODO(phli): Add short-circuit memcpy evaluation if underlying data are linear? + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) + { + m_leftImpl.evalSubExprsIfNeeded(NULL); + m_rightImpl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() + { + m_leftImpl.cleanup(); + m_rightImpl.cleanup(); + } + + // TODO(phli): attempt to speed this up. The integer divisions and modulo are slow. + // See CL/76180724 comments for more ideas. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + // Collect dimension-wise indices (subs). + array subs; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + subs[i] = index / m_outputStrides[i]; + index -= subs[i] * m_outputStrides[i]; + } + subs[0] = index; + } else { + for (int i = 0; i < NumDims - 1; ++i) { + subs[i] = index / m_outputStrides[i]; + index -= subs[i] * m_outputStrides[i]; + } + subs[NumDims - 1] = index; + } + + const Dimensions& left_dims = m_leftImpl.dimensions(); + if (subs[m_axis] < left_dims[m_axis]) { + Index left_index; + if (static_cast(Layout) == static_cast(ColMajor)) { + left_index = subs[0]; + EIGEN_UNROLL_LOOP + for (int i = 1; i < NumDims; ++i) { + left_index += (subs[i] % left_dims[i]) * m_leftStrides[i]; + } + } else { + left_index = subs[NumDims - 1]; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 2; i >= 0; --i) { + left_index += (subs[i] % left_dims[i]) * m_leftStrides[i]; + } + } + return m_leftImpl.coeff(left_index); + } else { + subs[m_axis] -= left_dims[m_axis]; + const Dimensions& right_dims = m_rightImpl.dimensions(); + Index right_index; + if (static_cast(Layout) == static_cast(ColMajor)) { + right_index = subs[0]; + EIGEN_UNROLL_LOOP + for (int i = 1; i < NumDims; ++i) { + right_index += (subs[i] % right_dims[i]) * m_rightStrides[i]; + } + } else { + right_index = subs[NumDims - 1]; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 2; i >= 0; --i) { + right_index += (subs[i] % right_dims[i]) * m_rightStrides[i]; + } + } + return m_rightImpl.coeff(right_index); + } + } + + // TODO(phli): Add a real vectorization. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + const int packetSize = PacketType::size; + EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index + packetSize - 1 < dimensions().TotalSize()); + + EIGEN_ALIGN_MAX CoeffReturnType values[packetSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < packetSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double compute_cost = NumDims * (2 * TensorOpCost::AddCost() + + 2 * TensorOpCost::MulCost() + + TensorOpCost::DivCost() + + TensorOpCost::ModCost()); + const double lhs_size = m_leftImpl.dimensions().TotalSize(); + const double rhs_size = m_rightImpl.dimensions().TotalSize(); + return (lhs_size / (lhs_size + rhs_size)) * + m_leftImpl.costPerCoeff(vectorized) + + (rhs_size / (lhs_size + rhs_size)) * + m_rightImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + protected: + Dimensions m_dimensions; + array m_outputStrides; + array m_leftStrides; + array m_rightStrides; + TensorEvaluator m_leftImpl; + TensorEvaluator m_rightImpl; + const Axis m_axis; +}; + +// Eval as lvalue +template + struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + typedef TensorConcatenationOp XprType; + typedef typename Base::Dimensions Dimensions; + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(XprType& op, const Device& device) + : Base(op, device) + { + EIGEN_STATIC_ASSERT((static_cast(Layout) == static_cast(ColMajor)), YOU_MADE_A_PROGRAMMING_MISTAKE); + } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + // Collect dimension-wise indices (subs). + array subs; + for (int i = Base::NumDims - 1; i > 0; --i) { + subs[i] = index / this->m_outputStrides[i]; + index -= subs[i] * this->m_outputStrides[i]; + } + subs[0] = index; + + const Dimensions& left_dims = this->m_leftImpl.dimensions(); + if (subs[this->m_axis] < left_dims[this->m_axis]) { + Index left_index = subs[0]; + for (int i = 1; i < Base::NumDims; ++i) { + left_index += (subs[i] % left_dims[i]) * this->m_leftStrides[i]; + } + return this->m_leftImpl.coeffRef(left_index); + } else { + subs[this->m_axis] -= left_dims[this->m_axis]; + const Dimensions& right_dims = this->m_rightImpl.dimensions(); + Index right_index = subs[0]; + for (int i = 1; i < Base::NumDims; ++i) { + right_index += (subs[i] % right_dims[i]) * this->m_rightStrides[i]; + } + return this->m_rightImpl.coeffRef(right_index); + } + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + const int packetSize = PacketType::size; + EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index + packetSize - 1 < this->dimensions().TotalSize()); + + EIGEN_ALIGN_MAX CoeffReturnType values[packetSize]; + internal::pstore(values, x); + for (int i = 0; i < packetSize; ++i) { + coeffRef(index+i) = values[i]; + } + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h new file mode 100644 index 0000000000000000000000000000000000000000..2fa6777b230b7baba7ea91f984ab502628e152d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h @@ -0,0 +1,1018 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorContraction + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor contraction class. + * + * + */ +namespace internal { + +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef typename gebp_traits, + std::remove_const_t>::ResScalar Scalar; + + typedef typename promote_storage_type::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename LhsXprType::Nested LhsNested; + typedef typename RhsXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + + // From NumDims below. + static constexpr int NumDimensions = traits::NumDimensions + traits::NumDimensions - 2 * array_size::value; + static constexpr int Layout = traits::Layout; + typedef std::conditional_t::val, + typename traits::PointerType, + typename traits::PointerType> + PointerType; + + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorContractionOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorContractionOp type; +}; + +template +struct traits, Device_> > { + typedef Indices_ Indices; + typedef LeftArgType_ LeftArgType; + typedef RightArgType_ RightArgType; + typedef OutputKernelType_ OutputKernelType; + typedef Device_ Device; + + // From NumDims below. + static constexpr int NumDimensions = traits::NumDimensions + traits::NumDimensions - 2 * array_size::value; +}; + +// Helper class to allocate and deallocate temporary memory for packed buffers. +template +struct TensorContractionBlockMemAllocator { + typedef void* BlockMemHandle; + + template + EIGEN_DEVICE_FUNC static BlockMemHandle allocate(Device& d, const Index bm, + const Index bk, + const Index bn, + LhsScalar** lhs_block, + RhsScalar** rhs_block) { + eigen_assert(lhs_block); + eigen_assert(rhs_block); + BlockSizes sz = ComputeLhsRhsBlockSizes(bm, bk, bn); + char* block_mem = static_cast(d.allocate(sz.lhs_size + sz.rhs_size)); + *lhs_block = static_cast(static_cast(block_mem)); + *rhs_block = static_cast(static_cast(block_mem + sz.lhs_size)); + return block_mem; + } + + template + EIGEN_DEVICE_FUNC static BlockMemHandle allocateSlices( + Device& d, const Index bm, const Index bk, const Index bn, + const Index num_lhs, const Index num_rhs, const Index num_slices, + std::vector* lhs_blocks, + std::vector* rhs_blocks) { + eigen_assert(num_slices > 0); + eigen_assert(num_lhs >= 0 && num_rhs >= 0); + eigen_assert(num_lhs == 0 || lhs_blocks); + eigen_assert(num_rhs == 0 || rhs_blocks); + BlockSizes sz = ComputeLhsRhsBlockSizes(bm, bk, bn); + void* block_mem = d.allocate( + (num_lhs * sz.lhs_size + num_rhs * sz.rhs_size) * num_slices); + eigen_assert(block_mem); + char* mem = static_cast(block_mem); + + for (Index x = 0; x < num_slices; x++) { + if (num_lhs > 0) lhs_blocks[x].resize(num_lhs); + for (Index m = 0; m < num_lhs; m++) { + lhs_blocks[x][m] = static_cast(static_cast(mem)); + mem += sz.lhs_size; + } + if (num_rhs > 0) rhs_blocks[x].resize(num_rhs); + for (Index n = 0; n < num_rhs; n++) { + rhs_blocks[x][n] = static_cast(static_cast(mem)); + mem += sz.rhs_size; + } + } + + return block_mem; + } + + template + EIGEN_DEVICE_FUNC static void deallocate(Device& d, BlockMemHandle handle) { + d.deallocate(handle); + } + + private: + struct BlockSizes { + Index lhs_size; + Index rhs_size; + }; + EIGEN_DEVICE_FUNC static BlockSizes ComputeLhsRhsBlockSizes(const Index bm, + const Index bk, + const Index bn) { + Index align = numext::maxi(EIGEN_MAX_ALIGN_BYTES, 1); + BlockSizes sz; + sz.lhs_size = divup(bm * bk * sizeof(LhsScalar), align) * align; + sz.rhs_size = divup(bn * bk * sizeof(RhsScalar), align) * align; + return sz; + } +}; + +// WARNING: In this code we assume that Lhs and Rhs tensor expressions are in +// ColMajor storage order. This property is guaranteed by the +// TensorContractionOp evaluator. TensorContractionKernel specifies how we pack +// blocks of Lhs and Rhs tensor expressions, and how we invoke matrix +// multiplication for these blocks. Default tensor contraction uses +// gemm_pack_rhs, gemm_pack_lhs and gebp_kernel from Eigen Core (see +// GeneralBlocPanelKernel.h for details). +// +// By specializing contraction kernels we can use other low level libraries to +// perform matrix multiplication, and still rely on Eigen contraction evaluator. +// This also includes full support in TensorContractionThreadPool, assuming that +// underlying gemm do not use it's own threading. +// +// - ResScalar/LhsScalar/RhsScalar - scalar type for the result of +// multiplication, lhs tensor and rhs tensor respectively. +// +// - StorageIndex - index type for the tensor expressions. In practice almost +// always is Eigen::Index. +// +// - OutputMapper provides access to the memory of the output matrix. In +// practice it's always column major blas_data_mapper (it must be of ResScalar +// type). +// +// - LhsMapper/RhsMapper similarly to blas_data_mapper provide a two dimensional +// view into the Lhs/Rhs tensor expressions. In practice it's +// TensorContractionInputMapper, or some specialization of it based on the +// type of tensor expression (e.g. TensorImagePatchOp has optimized input +// mapper). +template +struct TensorContractionKernel { + // True if `invoke()` supports `beta` in `C <- alpha * A * B + beta * C` + // (otherwise beta should be always equal to 1). + enum { HasBeta = false }; + + EIGEN_DEVICE_FUNC + TensorContractionKernel(StorageIndex m_, StorageIndex k_, StorageIndex n_, + StorageIndex bm_, StorageIndex bk_, StorageIndex bn_) + : m(m_), k(k_), n(n_), bm(bm_), bk(bk_), bn(bn_) {} + + // Pack blocks of Lhs and Rhs into contiguous blocks in memory. + typedef LhsScalar* LhsBlock; + typedef RhsScalar* RhsBlock; + + // Packed Lhs/Rhs block memory allocator. + typedef TensorContractionBlockMemAllocator + BlockMemAllocator; + typedef typename BlockMemAllocator::BlockMemHandle BlockMemHandle; + + typedef typename internal::gebp_traits Traits; + + typedef internal::gemm_pack_lhs< + LhsScalar, StorageIndex, typename LhsMapper::SubMapper, Traits::mr, + Traits::LhsProgress, typename Traits::LhsPacket4Packing, ColMajor> + LhsPacker; + + typedef internal::gemm_pack_rhs + RhsPacker; + + typedef internal::gebp_kernel + GebpKernel; + + template + EIGEN_DEVICE_FUNC BlockMemHandle allocate(Device& d, LhsBlock* lhs_block, + RhsBlock* rhs_block) { + return BlockMemAllocator::allocate(d, bm, bk, bn, lhs_block, rhs_block); + } + + template + EIGEN_DEVICE_FUNC BlockMemHandle allocateSlices( + Device& d, const StorageIndex num_lhs, const StorageIndex num_rhs, + const StorageIndex num_slices, std::vector* lhs_blocks, + std::vector* rhs_blocks) { + return BlockMemAllocator::allocateSlices( + d, bm, bk, bn, num_lhs, num_rhs, num_slices, lhs_blocks, rhs_blocks); + } + + template + EIGEN_DEVICE_FUNC static void deallocate(Device& d, BlockMemHandle handle) { + BlockMemAllocator::deallocate(d, handle); + } + + EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void packLhs( + LhsBlock* lhsBlock, const typename LhsMapper::SubMapper& data_mapper, + const StorageIndex depth, const StorageIndex rows) { + LhsPacker()(*lhsBlock, data_mapper, depth, rows, /*stride*/ 0, + /*offset*/ 0); + } + + EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void packRhs( + RhsBlock* rhsBlock, const typename RhsMapper::SubMapper& data_mapper, + const StorageIndex depth, const StorageIndex cols) { + RhsPacker()(*rhsBlock, data_mapper, depth, cols); + } + + EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE void invoke( + const OutputMapper& output_mapper, const LhsBlock& lhsBlock, + const RhsBlock& rhsBlock, const StorageIndex rows, + const StorageIndex depth, const StorageIndex cols, + const ResScalar alpha, const ResScalar beta) { + // Default GEBP kernel does not support beta. + eigen_assert(beta == ResScalar(1)); + static const int kComputeStrideFromBlockDimensions = -1; + GebpKernel()(output_mapper, lhsBlock, rhsBlock, rows, depth, cols, alpha, + /*strideA*/ kComputeStrideFromBlockDimensions, + /*strideB*/ kComputeStrideFromBlockDimensions, + /*offsetA*/ 0, /*offsetB*/ 0); + } + + private: + // These are dimensions of the original Tensors, and selected block sizes. The + // actual block sizes passed to all function above might be smaller because of + // the partial blocks at the end. + const StorageIndex m; + const StorageIndex k; + const StorageIndex n; + const StorageIndex bm; + const StorageIndex bk; + const StorageIndex bn; +}; + +} // end namespace internal + +// Tensor contraction params that should enable to get from output matrix +// 2-dimensional coordinates to the output tensor dimensions. +struct TensorContractionParams { + // TensorContraction evaluator assumes that both tensors are in ColMajor + // layout, if tensors are in RowMajor evaluator swap lhs with rhs. + bool swapped_arguments; +}; + +// Output kernel allows to fuse operations into the tensor contraction. +// +// Examples: +// 1. Elementwise Relu transformation following Conv2D. +// 2. AddBias to the Conv2D output channels dimension. +// +// The NoOpOutputKernel implements an output kernel that does absolutely nothing. +struct NoOpOutputKernel { + /** + * Tensor contraction evaluator calls this kernel after finishing each block + * of output matrix. Output blocks belong to the 2-dimensional output tensor. + * + * TensorContractionParams contains contraction dimensions information + * required to map output 2-d space into the expected output tensor space + * (potentially higher dimensional). + * + * \param[in] output_mapper Access to output tensor memory + * \param[in] params Tensor contraction parameters + * \param[in] i Index of a first row available through output_mapper + * \param[in] j Index of a first column available through output_mapper + * \param[in] num_rows Number of available rows + * \param[in] num_cols Number of available columns + */ + template + EIGEN_ALWAYS_INLINE void operator()( + const internal::blas_data_mapper& output_mapper, + const TensorContractionParams& params, Index i, + Index j, Index num_rows, Index num_cols) const { + EIGEN_UNUSED_VARIABLE(output_mapper); + EIGEN_UNUSED_VARIABLE(params); + EIGEN_UNUSED_VARIABLE(i); + EIGEN_UNUSED_VARIABLE(j); + EIGEN_UNUSED_VARIABLE(num_rows); + EIGEN_UNUSED_VARIABLE(num_cols); + } +}; + +template +class TensorContractionOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename internal::gebp_traits::ResScalar CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionOp( + const LhsXprType& lhs, const RhsXprType& rhs, const Indices& dims, + const OutputKernelType& output_kernel = OutputKernelType()) + : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_indices(dims), + m_output_kernel(output_kernel) {} + + EIGEN_DEVICE_FUNC + const Indices& indices() const { return m_indices; } + + /** \returns the nested expressions */ + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + lhsExpression() const { return m_lhs_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + rhsExpression() const { return m_rhs_xpr; } + + EIGEN_DEVICE_FUNC + const OutputKernelType& outputKernel() const { return m_output_kernel; } + + protected: + typename LhsXprType::Nested m_lhs_xpr; + typename RhsXprType::Nested m_rhs_xpr; + const Indices m_indices; + const OutputKernelType m_output_kernel; +}; + +template +struct TensorContractionEvaluatorBase { + typedef typename internal::traits::Indices Indices; + typedef typename internal::traits::LeftArgType LeftArgType; + typedef typename internal::traits::RightArgType RightArgType; + typedef typename internal::traits::OutputKernelType OutputKernelType; + typedef typename internal::traits::Device Device; + + typedef TensorContractionOp XprType; + typedef std::remove_const_t Scalar; + typedef typename XprType::Index Index; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = true, + PacketAccess = (PacketType::size > 1), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = true + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + // Most of the code is assuming that both input tensors are ColMajor. If the + // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS: + // If we want to compute A * B = C, where A is LHS and B is RHS, the code + // will pretend B is LHS and A is RHS. + typedef std::conditional_t< + static_cast(Layout) == static_cast(ColMajor), LeftArgType, RightArgType> EvalLeftArgType; + typedef std::conditional_t< + static_cast(Layout) == static_cast(ColMajor), RightArgType, LeftArgType> EvalRightArgType; + + typedef TensorEvaluator LeftEvaluatorType; + typedef TensorEvaluator RightEvaluatorType; + + static constexpr int LDims = + internal::array_size::Dimensions>::value; + static constexpr int RDims = + internal::array_size::Dimensions>::value; + static constexpr int ContractDims = internal::array_size::value; + static constexpr int NumDims = LDims + RDims - 2 * ContractDims; + + typedef array contract_t; + typedef array left_nocontract_t; + typedef array right_nocontract_t; + + typedef DSizes Dimensions; + + EIGEN_STRONG_INLINE + TensorContractionEvaluatorBase(const XprType& op, const Device& device) + : m_leftImpl(choose(Cond(Layout) == static_cast(ColMajor)>(), + op.lhsExpression(), op.rhsExpression()), device), + m_rightImpl(choose(Cond(Layout) == static_cast(ColMajor)>(), + op.rhsExpression(), op.lhsExpression()), device), + m_device(device), + m_output_kernel(op.outputKernel()), + m_result(NULL) { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == + static_cast(TensorEvaluator::Layout)), + YOU_MADE_A_PROGRAMMING_MISTAKE); + + + DSizes eval_left_dims; + DSizes eval_right_dims; + array, ContractDims> eval_op_indices; + if (static_cast(Layout) == static_cast(ColMajor)) { + // For ColMajor, we keep using the existing dimensions + for (int i = 0; i < LDims; i++) { + eval_left_dims[i] = m_leftImpl.dimensions()[i]; + } + for (int i = 0; i < RDims; i++) { + eval_right_dims[i] = m_rightImpl.dimensions()[i]; + } + // We keep the pairs of contracting indices. + for (int i = 0; i < ContractDims; i++) { + eval_op_indices[i].first = op.indices()[i].first; + eval_op_indices[i].second = op.indices()[i].second; + } + } else { + // For RowMajor, we need to reverse the existing dimensions + for (int i = 0; i < LDims; i++) { + eval_left_dims[i] = m_leftImpl.dimensions()[LDims - i - 1]; + } + for (int i = 0; i < RDims; i++) { + eval_right_dims[i] = m_rightImpl.dimensions()[RDims - i - 1]; + } + // We need to flip all the pairs of contracting indices as well as + // reversing the dimensions. + for (int i = 0; i < ContractDims; i++) { + eval_op_indices[i].first = LDims - 1 - op.indices()[ContractDims - 1 - i].second; + eval_op_indices[i].second = RDims - 1 - op.indices()[ContractDims - 1 - i].first; + } + } + + // Check for duplicate axes and make sure the first index in eval_op_indices + // is increasing. Using O(n^2) sorting is OK since ContractDims is small + for (int i = 0; i < ContractDims; i++) { + for (int j = i + 1; j < ContractDims; j++) { + eigen_assert(eval_op_indices[j].first != eval_op_indices[i].first && + eval_op_indices[j].second != eval_op_indices[i].second && + "contraction axes should be unique"); + if (eval_op_indices[j].first < eval_op_indices[i].first) { + numext::swap(eval_op_indices[j], eval_op_indices[i]); + } + } + } + + array lhs_strides; + lhs_strides[0] = 1; + for (int i = 0; i < LDims-1; ++i) { + lhs_strides[i+1] = lhs_strides[i] * eval_left_dims[i]; + } + + array rhs_strides; + rhs_strides[0] = 1; + for (int i = 0; i < RDims-1; ++i) { + rhs_strides[i+1] = rhs_strides[i] * eval_right_dims[i]; + } + + if (m_i_strides.size() > 0) m_i_strides[0] = 1; + if (m_j_strides.size() > 0) m_j_strides[0] = 1; + if (m_k_strides.size() > 0) m_k_strides[0] = 1; + + m_i_size = 1; + m_j_size = 1; + m_k_size = 1; + + // To compute the dimension, we simply concatenate the non-contracting + // dimensions of the left and then the right tensor. Additionally, we also + // compute the strides corresponding to the left non-contracting + // dimensions and right non-contracting dimensions. + m_lhs_inner_dim_contiguous = true; + int dim_idx = 0; + Index nocontract_idx = 0; + + for (int i = 0; i < LDims; i++) { + // find if we are contracting on index i of left tensor + bool contracting = false; + for (int j = 0; j < ContractDims; j++) { + if (eval_op_indices[j].first == i) { + contracting = true; + break; + } + } + if (!contracting) { + // add dimension size to output dimensions + m_dimensions[dim_idx] = eval_left_dims[i]; + m_left_nocontract_strides[nocontract_idx] = lhs_strides[i]; + if (dim_idx != i) { + m_lhs_inner_dim_contiguous = false; + } + if (nocontract_idx+1 < internal::array_size::value) { + m_i_strides[nocontract_idx+1] = + m_i_strides[nocontract_idx] * eval_left_dims[i]; + } else { + m_i_size = m_i_strides[nocontract_idx] * eval_left_dims[i]; + } + dim_idx++; + nocontract_idx++; + } + } + + nocontract_idx = 0; + for (int i = 0; i < RDims; i++) { + bool contracting = false; + // find if we are contracting on index i of right tensor + for (int j = 0; j < ContractDims; j++) { + if (eval_op_indices[j].second == i) { + contracting = true; + break; + } + } + if (!contracting) { + m_dimensions[dim_idx] = eval_right_dims[i]; + if (nocontract_idx+1 < internal::array_size::value) { + m_j_strides[nocontract_idx+1] = + m_j_strides[nocontract_idx] * eval_right_dims[i]; + } else { + m_j_size = m_j_strides[nocontract_idx] * eval_right_dims[i]; + } + m_right_nocontract_strides[nocontract_idx] = rhs_strides[i]; + dim_idx++; + nocontract_idx++; + } + } + + // Now compute the strides corresponding to the contracting dimensions. We + // assumed above that non-contracting axes are represented in the same order + // in the matrix as they are in the tensor. This is not the case for + // contracting axes. As the contracting axes must be of the same size in + // each tensor, we'll only look at the first tensor here. + m_rhs_inner_dim_contiguous = true; + m_rhs_inner_dim_reordered = false; + for (int i = 0; i < ContractDims; i++) { + Index left = eval_op_indices[i].first; + Index right = eval_op_indices[i].second; + + Index size = eval_left_dims[left]; + eigen_assert(size == eval_right_dims[right] && + "Contraction axes must be same size"); + + if (i+1 < static_cast(internal::array_size::value)) { + m_k_strides[i+1] = m_k_strides[i] * size; + } else { + m_k_size = m_k_strides[i] * size; + } + m_left_contracting_strides[i] = lhs_strides[left]; + m_right_contracting_strides[i] = rhs_strides[right]; + + if (i > 0 && right < eval_op_indices[i-1].second) { + m_rhs_inner_dim_reordered = true; + } + if (right != i) { + m_rhs_inner_dim_contiguous = false; + } + } + + // If the layout is RowMajor, we need to reverse the m_dimensions + if (static_cast(Layout) == static_cast(RowMajor)) { + for (int i = 0, j = NumDims - 1; i < j; i++, j--) { + numext::swap(m_dimensions[i], m_dimensions[j]); + } + } + + // A set of parameters that will allow output kernel to get from output + // tensor dimensions (i, j) into the original tensor dimensions. + // TODO(ezhulenev): Add parameters required to infer output tensor index for + // more complex contractions than 2x2 on internal dimension. + m_tensor_contraction_params.swapped_arguments = static_cast(Layout) == RowMajor; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + m_leftImpl.evalSubExprsIfNeeded(NULL); + m_rightImpl.evalSubExprsIfNeeded(NULL); + if (data) { + evalTo(data); + return false; + } else { + m_result = static_cast(m_device.allocate(dimensions().TotalSize() * sizeof(Scalar))); + evalTo(m_result); + return true; + } + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType dest, EvalSubExprsCallback done) { + m_leftImpl.evalSubExprsIfNeededAsync(nullptr, [this, done, dest](bool) { + m_rightImpl.evalSubExprsIfNeededAsync(nullptr, [this, done, dest](bool) { + if (dest) { + evalToAsync(dest, [done]() { done(false); }); + } else { + m_result = static_cast( + m_device.allocate(dimensions().TotalSize() * sizeof(Scalar))); + evalToAsync(m_result, [done]() { done(true); }); + } + }); + }); + } +#endif // EIGEN_USE_THREADS + +#ifndef TENSOR_CONTRACTION_DISPATCH +#define TENSOR_CONTRACTION_DISPATCH(METHOD, ALIGNMENT, ARGS) \ + if (this->m_lhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_reordered) { \ + METHOD ARGS; \ + } else { \ + METHOD ARGS; \ + } \ + } else { \ + if (this->m_rhs_inner_dim_reordered) { \ + METHOD ARGS; \ + } else { \ + METHOD ARGS; \ + } \ + } \ + } else { \ + if (this->m_rhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_reordered) { \ + METHOD ARGS; \ + } else { \ + METHOD ARGS; \ + } \ + } else { \ + if (this->m_rhs_inner_dim_reordered) { \ + METHOD ARGS; \ + } else { \ + METHOD ARGS; \ + } \ + } \ + } +#endif + +#ifndef TENSOR_CONTRACTION_ASYNC_DISPATCH +#define TENSOR_CONTRACTION_ASYNC_DISPATCH(METHOD, DONE, ALIGNMENT, ARGS, FN) \ + if (this->m_lhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_reordered) { \ + (new METHOD ARGS)->FN; \ + } else { \ + (new METHOD ARGS)->FN; \ + } \ + } else { \ + if (this->m_rhs_inner_dim_reordered) { \ + (new METHOD ARGS)->FN; \ + } else { \ + (new METHOD ARGS)->FN; \ + } \ + } \ + } else { \ + if (this->m_rhs_inner_dim_contiguous) { \ + if (this->m_rhs_inner_dim_reordered) { \ + (new METHOD ARGS)->FN; \ + } else { \ + (new METHOD ARGS)->FN; \ + } \ + } else { \ + if (this->m_rhs_inner_dim_reordered) { \ + (new METHOD ARGS)->FN; \ + } else { \ + (new METHOD ARGS)->FN; \ + } \ + } \ + } +#endif + + EIGEN_DEVICE_FUNC void evalTo(Scalar* buffer) const { + static_cast(this)->template evalProduct(buffer); + } + +#ifdef EIGEN_USE_THREADS + template + void evalToAsync(Scalar* buffer, EvalToCallback done) const { + static_cast(this) + ->template evalProductAsync(buffer, + std::move(done)); + } +#endif // EIGEN_USE_THREADS + + template + void evalProductSequential(Scalar* buffer) const { + if (this->m_j_size == 1) { + this->template evalGemv(buffer); + } else { + this->template evalGemm(buffer); + } + } + + template + #if !defined(EIGEN_HIPCC) + EIGEN_DEVICE_FUNC + #endif + void evalGemv(Scalar* buffer) const { + const Index rows = m_i_size; + const Index cols = m_k_size; + + typedef std::remove_const_t LhsScalar; + typedef std::remove_const_t RhsScalar; + typedef TensorEvaluator LeftEvaluator; + typedef TensorEvaluator RightEvaluator; + const Index lhs_packet_size = internal::unpacket_traits::size; + const Index rhs_packet_size = internal::unpacket_traits::size; + const int lhs_alignment = LeftEvaluator::IsAligned ? Aligned : Unaligned; + const int rhs_alignment = RightEvaluator::IsAligned ? Aligned : Unaligned; + typedef internal::TensorContractionInputMapper LhsMapper; + + typedef internal::TensorContractionInputMapper RhsMapper; + + LhsMapper lhs(m_leftImpl, m_left_nocontract_strides, m_i_strides, + m_left_contracting_strides, m_k_strides); + RhsMapper rhs(m_rightImpl, m_right_nocontract_strides, m_j_strides, + m_right_contracting_strides, m_k_strides); + + const Scalar alpha(1); + const Index resIncr(1); + + // zero out the result buffer (which must be of size at least rows * sizeof(Scalar) + m_device.fill(buffer, buffer + rows, Scalar(0)); + + internal::general_matrix_vector_product::run( + rows, cols, lhs, rhs, + buffer, resIncr, alpha); + + typedef internal::blas_data_mapper OutputMapper; + m_output_kernel(OutputMapper(buffer, rows), m_tensor_contraction_params, + static_cast(0), static_cast(0), rows, + static_cast(1)); + } + + template + #if !defined(EIGEN_HIPCC) + EIGEN_DEVICE_FUNC + #endif + void evalGemm(Scalar* buffer) const { + // columns in left side, rows in right side + const Index k = this->m_k_size; + this->template evalGemmPartial(buffer, 0, k, 1); + } + + template + EIGEN_DEVICE_FUNC void evalGemmPartialWithoutOutputKernel( + Scalar* buffer, Index k_start, Index k_end, int num_threads) const { + evalGemmPartial(buffer, k_start, k_end, + num_threads); + } + + template + EIGEN_DEVICE_FUNC void evalGemmPartial(Scalar* buffer, Index k_start, Index k_end, int num_threads) const { + eigen_assert(k_end >= k_start && k_start >= 0 && k_end <= this->m_k_size); + // columns in slice on left side, rows on right side + const Index k_slice = k_end - k_start; + + // rows in left side + const Index m = this->m_i_size; + + // columns in right side + const Index n = this->m_j_size; + + // define data mappers for Lhs and Rhs + typedef std::remove_const_t LhsScalar; + typedef std::remove_const_t RhsScalar; + + typedef TensorEvaluator LeftEvaluator; + typedef TensorEvaluator RightEvaluator; + + const Index lhs_packet_size = internal::unpacket_traits::size; + const Index rhs_packet_size = internal::unpacket_traits::size; + + typedef internal::TensorContractionInputMapper LhsMapper; + + typedef internal::TensorContractionInputMapper RhsMapper; + + typedef internal::blas_data_mapper OutputMapper; + + typedef internal::TensorContractionKernel< + Scalar, LhsScalar, RhsScalar, Index, OutputMapper, LhsMapper, RhsMapper> + TensorContractionKernel; + + // initialize data mappers + LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides, + this->m_left_contracting_strides, this->m_k_strides); + + RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides, + this->m_right_contracting_strides, this->m_k_strides); + + OutputMapper output(buffer, m); + + // Sizes of the blocks to load in cache. See the Goto paper for details. + internal::TensorContractionBlocking + blocking(k_slice, m, n, num_threads); + const Index kc = blocking.kc(); + const Index mc = numext::mini(m, blocking.mc()); + const Index nc = numext::mini(n, blocking.nc()); + + typedef typename TensorContractionKernel::LhsBlock LhsBlock; + typedef typename TensorContractionKernel::RhsBlock RhsBlock; + + LhsBlock blockA; + RhsBlock blockB; + + TensorContractionKernel kernel(m, k_slice, n, mc, kc, nc); + + typedef typename TensorContractionKernel::BlockMemHandle BlockMemHandle; + const BlockMemHandle packed_mem = + kernel.allocate(this->m_device, &blockA, &blockB); + + // If a contraction kernel does not support beta, explicitly initialize + // output buffer with zeroes. + if (!TensorContractionKernel::HasBeta) { + this->m_device.fill(buffer, buffer + m * n, Scalar(0)); + } + + for(Index i2=0; i2= k_end) { + m_output_kernel(output_mapper, m_tensor_contraction_params, i2, j2, + actual_mc, actual_nc); + } + } + } + } + + kernel.deallocate(this->m_device, packed_mem); + } + + EIGEN_STRONG_INLINE void cleanup() { + m_leftImpl.cleanup(); + m_rightImpl.cleanup(); + + if (m_result != NULL) { + m_device.deallocate(m_result); + m_result = NULL; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + return m_result[index]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const { + return internal::ploadt(m_result + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return m_result; } + +protected: + Dimensions m_dimensions; + + contract_t m_k_strides; + contract_t m_left_contracting_strides; + contract_t m_right_contracting_strides; + + bool m_lhs_inner_dim_contiguous; + bool m_rhs_inner_dim_contiguous; + bool m_rhs_inner_dim_reordered; + + left_nocontract_t m_i_strides; + right_nocontract_t m_j_strides; + left_nocontract_t m_left_nocontract_strides; + right_nocontract_t m_right_nocontract_strides; + + Index m_i_size; + Index m_j_size; + Index m_k_size; + + TensorContractionParams m_tensor_contraction_params; + + TensorEvaluator m_leftImpl; + TensorEvaluator m_rightImpl; + const Device EIGEN_DEVICE_REF m_device; + OutputKernelType m_output_kernel; + EvaluatorPointerType m_result; +}; + + +// evaluator for default device +template +struct TensorEvaluator, Device> : + public TensorContractionEvaluatorBase< + TensorEvaluator, Device> > { + typedef TensorEvaluator, Device> Self; + typedef TensorContractionEvaluatorBase Base; + + typedef TensorContractionOp XprType; + typedef std::remove_const_t Scalar; + typedef typename XprType::Index Index; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + static constexpr int Layout = TensorEvaluator::Layout; + + // Most of the code is assuming that both input tensors are ColMajor. If the + // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS: + // If we want to compute A * B = C, where A is LHS and B is RHS, the code + // will pretend B is LHS and A is RHS. + typedef std::conditional_t(ColMajor), LeftArgType, RightArgType> EvalLeftArgType; + typedef std::conditional_t(ColMajor), RightArgType, LeftArgType> EvalRightArgType; + + static constexpr int LDims = + internal::array_size::Dimensions>::value; + static constexpr int RDims = + internal::array_size::Dimensions>::value; + static constexpr int ContractDims = internal::array_size::value; + + typedef array contract_t; + typedef array left_nocontract_t; + typedef array right_nocontract_t; + + static constexpr int NumDims = LDims + RDims - 2 * ContractDims; + + // Could we use NumDimensions here? + typedef DSizes Dimensions; + + TensorEvaluator(const XprType& op, const Device& device) : + Base(op, device) { } + + template + void evalProduct(Scalar* buffer) const { + TENSOR_CONTRACTION_DISPATCH(this->template evalProductSequential, Alignment, (buffer)); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h new file mode 100644 index 0000000000000000000000000000000000000000..4b3d423803fe9317952c807cd8ba1a13b25dd98c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h @@ -0,0 +1,75 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +enum { + ShardByRow = 0, + ShardByCol = 1 +}; + + +// Default Blocking Strategy +template +class TensorContractionBlocking { + public: + + /* + adding EIGEN_DEVICE_FUNC unconditionally to 'TensorContractionBlocking' constructor in `TensorContractionBlocking.h` + requires adding EIGEN_DEVICE_FUNC to `computeProductBlockingSizes` in `GeneralBlockPanelKernel.h` + which in turn, requires adding EIGEN_DEVICE_FUNC to `evaluateProductBlockingSizesHeuristic` in `GeneralBlockPanelKernel.h` + which in turn, requires adding EIGEN_DEVICE_FUNC to `manage_caching_sizes` in `GeneralBlockPanelKernel.h` + (else HIPCC will error out) + + However adding EIGEN_DEVICE_FUNC to `manage_caching_sizes` in `GeneralBlockPanelKernel.h` + results in NVCC erroring out with the following error + + ../Eigen/src/Core/products/GeneralBlockPanelKernel.h(57): error #2901: + dynamic initialization is not supported for function-scope static variables within a __device__/__global__ function + */ + + #if !defined(EIGEN_HIPCC) + EIGEN_DEVICE_FUNC + #endif + TensorContractionBlocking(StorageIndex k, StorageIndex m, StorageIndex n, StorageIndex num_threads = 1) : + kc_(k), mc_(m), nc_(n) + { + if (ShardingType == ShardByCol) { + computeProductBlockingSizes(kc_, mc_, nc_, num_threads); + } + else { + computeProductBlockingSizes(kc_, nc_, mc_, num_threads); + } + + const int rhs_packet_size = internal::packet_traits::size; + kc_ = (rhs_packet_size <= 8 || kc_ <= rhs_packet_size) ? + kc_ : (kc_ / rhs_packet_size) * rhs_packet_size; + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex kc() const { return kc_; } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex mc() const { return mc_; } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE StorageIndex nc() const { return nc_; } + + private: + StorageIndex kc_; + StorageIndex mc_; + StorageIndex nc_; +}; + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_BLOCKING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h new file mode 100644 index 0000000000000000000000000000000000000000..3f315fedc54b64adc75ae42f4b8a7cc9202ea1b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionCuda.h @@ -0,0 +1,6 @@ + +#if defined(__clang__) || defined(__GNUC__) +#warning "Deprecated header file, please either include the main Eigen/CXX11/Tensor header or the respective TensorContractionGpu.h file" +#endif + +#include "TensorContractionGpu.h" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h new file mode 100644 index 0000000000000000000000000000000000000000..698baab7c3936712816b71cf1cc1bb1691de91fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h @@ -0,0 +1,1411 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014-2015 Benoit Steiner +// Copyright (C) 2015 Navdeep Jaitly +// Copyright (C) 2014 Eric Martin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H + +#if defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC) + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template +__device__ EIGEN_STRONG_INLINE void +EigenContractionKernelInternal(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, Scalar* lhs_shmem, Scalar* rhs_shmem, + const Index m_size, const Index n_size, const Index k_size) { + + const Index m_block_idx = blockIdx.x; + const Index n_block_idx = blockIdx.y; + + const Index base_m = 64 * m_block_idx; + const Index base_n = 64 * n_block_idx; + + // declare and initialize 64 registers for output 8x8 block + + // prefetch registers + Scalar lhs_pf0; + Scalar lhs_pf1; + Scalar lhs_pf2; + Scalar lhs_pf3; + Scalar lhs_pf4; + Scalar lhs_pf5; + Scalar lhs_pf6; + Scalar lhs_pf7; + + Scalar rhs_pf0; + Scalar rhs_pf1; + Scalar rhs_pf2; + Scalar rhs_pf3; + Scalar rhs_pf4; + Scalar rhs_pf5; + Scalar rhs_pf6; + Scalar rhs_pf7; + + // shared memory is formatted + // (contract idx in block, nocontract idx in block, block idx) + // where block idx is column major. This transposition limits the number of + // bank conflicts when reading the LHS. The core idea is that since the contracting + // index is shared by both sides, then the contracting index should be in threadIdx.x. + + // On the LHS, we pad each row inside of each block with an extra element. This makes + // each block 8 rows of 9 elements, which is 72 elements. This gives no bank conflicts + // on writes and very few 2-way conflicts on reads. There is an 8x8 grid of these blocks. + + // On the RHS we just add 8 padding elements to the end of each block. This gives no bank + // conflicts on writes and also none on reads. + + // storage indices + const Index lhs_store_idx_base = threadIdx.y * 72 + threadIdx.x * 9 + threadIdx.z; + const Index rhs_store_idx_base = threadIdx.y * 72 + threadIdx.z * 8 + threadIdx.x; + + const Index lhs_store_idx_0 = lhs_store_idx_base + 576 * 0; + const Index lhs_store_idx_1 = lhs_store_idx_base + 576 * 1; + const Index lhs_store_idx_2 = lhs_store_idx_base + 576 * 2; + const Index lhs_store_idx_3 = lhs_store_idx_base + 576 * 3; + const Index lhs_store_idx_4 = lhs_store_idx_base + 576 * 4; + const Index lhs_store_idx_5 = lhs_store_idx_base + 576 * 5; + const Index lhs_store_idx_6 = lhs_store_idx_base + 576 * 6; + const Index lhs_store_idx_7 = lhs_store_idx_base + 576 * 7; + + const Index rhs_store_idx_0 = rhs_store_idx_base + 576 * 0; + const Index rhs_store_idx_1 = rhs_store_idx_base + 576 * 1; + const Index rhs_store_idx_2 = rhs_store_idx_base + 576 * 2; + const Index rhs_store_idx_3 = rhs_store_idx_base + 576 * 3; + const Index rhs_store_idx_4 = rhs_store_idx_base + 576 * 4; + const Index rhs_store_idx_5 = rhs_store_idx_base + 576 * 5; + const Index rhs_store_idx_6 = rhs_store_idx_base + 576 * 6; + const Index rhs_store_idx_7 = rhs_store_idx_base + 576 * 7; + + // in the loading code, the following variables are important: + // threadIdx.x: the vertical position in an 8x8 block + // threadIdx.y: the vertical index of the 8x8 block in the grid + // threadIdx.z: the horizontal position in an 8x8 block + // k: the horizontal index of the 8x8 block in the grid + // + // The k parameter is implicit (it was the loop counter for a loop that went + // from 0 to <8, but now that loop is unrolled in the below code. + + const Index load_idx_vert = threadIdx.x + 8 * threadIdx.y; + const Index lhs_vert = base_m + load_idx_vert; + +#define prefetchIntoRegisters(base_k) \ + { \ + lhs_pf0 = conv(0); \ + lhs_pf1 = conv(0); \ + lhs_pf2 = conv(0); \ + lhs_pf3 = conv(0); \ + lhs_pf4 = conv(0); \ + lhs_pf5 = conv(0); \ + lhs_pf6 = conv(0); \ + lhs_pf7 = conv(0); \ + \ + rhs_pf0 = conv(0); \ + rhs_pf1 = conv(0); \ + rhs_pf2 = conv(0); \ + rhs_pf3 = conv(0); \ + rhs_pf4 = conv(0); \ + rhs_pf5 = conv(0); \ + rhs_pf6 = conv(0); \ + rhs_pf7 = conv(0); \ + \ + if (!needs_edge_check || lhs_vert < m_size) { \ + const Index lhs_horiz_0 = base_k + threadIdx.z + 0 * 8; \ + const Index lhs_horiz_1 = base_k + threadIdx.z + 1 * 8; \ + const Index lhs_horiz_2 = base_k + threadIdx.z + 2 * 8; \ + const Index lhs_horiz_3 = base_k + threadIdx.z + 3 * 8; \ + const Index lhs_horiz_4 = base_k + threadIdx.z + 4 * 8; \ + const Index lhs_horiz_5 = base_k + threadIdx.z + 5 * 8; \ + const Index lhs_horiz_6 = base_k + threadIdx.z + 6 * 8; \ + const Index lhs_horiz_7 = base_k + threadIdx.z + 7 * 8; \ + \ + if (!needs_edge_check || lhs_horiz_7 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \ + lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \ + lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \ + lhs_pf6 = lhs(lhs_vert, lhs_horiz_6); \ + lhs_pf7 = lhs(lhs_vert, lhs_horiz_7); \ + } else if (lhs_horiz_6 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \ + lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \ + lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \ + lhs_pf6 = lhs(lhs_vert, lhs_horiz_6); \ + } else if (lhs_horiz_5 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \ + lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \ + lhs_pf5 = lhs(lhs_vert, lhs_horiz_5); \ + } else if (lhs_horiz_4 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \ + lhs_pf4 = lhs(lhs_vert, lhs_horiz_4); \ + } else if (lhs_horiz_3 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + lhs_pf3 = lhs(lhs_vert, lhs_horiz_3); \ + } else if (lhs_horiz_2 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + lhs_pf2 = lhs(lhs_vert, lhs_horiz_2); \ + } else if (lhs_horiz_1 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + lhs_pf1 = lhs(lhs_vert, lhs_horiz_1); \ + } else if (lhs_horiz_0 < k_size) { \ + lhs_pf0 = lhs(lhs_vert, lhs_horiz_0); \ + } \ + } \ + \ + const Index rhs_vert = base_k + load_idx_vert; \ + if (!needs_edge_check || rhs_vert < k_size) { \ + const Index rhs_horiz_0 = base_n + threadIdx.z + 0 * 8; \ + const Index rhs_horiz_1 = base_n + threadIdx.z + 1 * 8; \ + const Index rhs_horiz_2 = base_n + threadIdx.z + 2 * 8; \ + const Index rhs_horiz_3 = base_n + threadIdx.z + 3 * 8; \ + const Index rhs_horiz_4 = base_n + threadIdx.z + 4 * 8; \ + const Index rhs_horiz_5 = base_n + threadIdx.z + 5 * 8; \ + const Index rhs_horiz_6 = base_n + threadIdx.z + 6 * 8; \ + const Index rhs_horiz_7 = base_n + threadIdx.z + 7 * 8; \ + \ + if (rhs_horiz_7 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \ + rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \ + rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \ + rhs_pf6 = rhs(rhs_vert, rhs_horiz_6); \ + rhs_pf7 = rhs(rhs_vert, rhs_horiz_7); \ + } else if (rhs_horiz_6 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \ + rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \ + rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \ + rhs_pf6 = rhs(rhs_vert, rhs_horiz_6); \ + } else if (rhs_horiz_5 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \ + rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \ + rhs_pf5 = rhs(rhs_vert, rhs_horiz_5); \ + } else if (rhs_horiz_4 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \ + rhs_pf4 = rhs(rhs_vert, rhs_horiz_4); \ + } else if (rhs_horiz_3 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + rhs_pf3 = rhs(rhs_vert, rhs_horiz_3); \ + } else if (rhs_horiz_2 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + rhs_pf2 = rhs(rhs_vert, rhs_horiz_2); \ + } else if (rhs_horiz_1 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + rhs_pf1 = rhs(rhs_vert, rhs_horiz_1); \ + } else if (rhs_horiz_0 < n_size) { \ + rhs_pf0 = rhs(rhs_vert, rhs_horiz_0); \ + } \ + } \ + } \ + +#define writeRegToShmem() \ + lhs_shmem[lhs_store_idx_0] = lhs_pf0; \ + rhs_shmem[rhs_store_idx_0] = rhs_pf0; \ + \ + lhs_shmem[lhs_store_idx_1] = lhs_pf1; \ + rhs_shmem[rhs_store_idx_1] = rhs_pf1; \ + \ + lhs_shmem[lhs_store_idx_2] = lhs_pf2; \ + rhs_shmem[rhs_store_idx_2] = rhs_pf2; \ + \ + lhs_shmem[lhs_store_idx_3] = lhs_pf3; \ + rhs_shmem[rhs_store_idx_3] = rhs_pf3; \ + \ + lhs_shmem[lhs_store_idx_4] = lhs_pf4; \ + rhs_shmem[rhs_store_idx_4] = rhs_pf4; \ + \ + lhs_shmem[lhs_store_idx_5] = lhs_pf5; \ + rhs_shmem[rhs_store_idx_5] = rhs_pf5; \ + \ + lhs_shmem[lhs_store_idx_6] = lhs_pf6; \ + rhs_shmem[rhs_store_idx_6] = rhs_pf6; \ + \ + lhs_shmem[lhs_store_idx_7] = lhs_pf7; \ + rhs_shmem[rhs_store_idx_7] = rhs_pf7; \ + + // declare and initialize result array +#define res(i, j) _res_##i##j +#define initResultRow(i) \ + Scalar res(i, 0) = conv(0); \ + Scalar res(i, 1) = conv(0); \ + Scalar res(i, 2) = conv(0); \ + Scalar res(i, 3) = conv(0); \ + Scalar res(i, 4) = conv(0); \ + Scalar res(i, 5) = conv(0); \ + Scalar res(i, 6) = conv(0); \ + Scalar res(i, 7) = conv(0); \ + + internal::scalar_cast_op conv; + initResultRow(0); + initResultRow(1); + initResultRow(2); + initResultRow(3); + initResultRow(4); + initResultRow(5); + initResultRow(6); + initResultRow(7); +#undef initResultRow + + for (Index base_k = 0; base_k < k_size; base_k += 64) { + // wait for previous iteration to finish with shmem. Despite common sense, + // the code is a bit faster with this here then at bottom of loop + __syncthreads(); + + prefetchIntoRegisters(base_k); + writeRegToShmem(); + + #undef prefetchIntoRegisters + #undef writeRegToShmem + + // wait for shared mem packing to be done before starting computation + __syncthreads(); + + // compute 8x8 matrix product by outer product. This involves packing one column + // of LHS and one row of RHS into registers (takes 16 registers). + +#define lcol(i) _lcol##i + Scalar lcol(0); + Scalar lcol(1); + Scalar lcol(2); + Scalar lcol(3); + Scalar lcol(4); + Scalar lcol(5); + Scalar lcol(6); + Scalar lcol(7); + +#define rrow(j) _rrow##j + Scalar rrow(0); + Scalar rrow(1); + Scalar rrow(2); + Scalar rrow(3); + Scalar rrow(4); + Scalar rrow(5); + Scalar rrow(6); + Scalar rrow(7); + + // Now x corresponds to k, y to m, and z to n + const Scalar* lhs_block = &lhs_shmem[threadIdx.x + 9 * threadIdx.y]; + const Scalar* rhs_block = &rhs_shmem[threadIdx.x + 8 * threadIdx.z]; + +#define lhs_element(i, j) lhs_block[72 * ((i) + 8 * (j))] +#define rhs_element(i, j) rhs_block[72 * ((i) + 8 * (j))] + +#define loadData(i, j) \ + lcol(0) = lhs_element(0, j); \ + rrow(0) = rhs_element(i, 0); \ + lcol(1) = lhs_element(1, j); \ + rrow(1) = rhs_element(i, 1); \ + lcol(2) = lhs_element(2, j); \ + rrow(2) = rhs_element(i, 2); \ + lcol(3) = lhs_element(3, j); \ + rrow(3) = rhs_element(i, 3); \ + lcol(4) = lhs_element(4, j); \ + rrow(4) = rhs_element(i, 4); \ + lcol(5) = lhs_element(5, j); \ + rrow(5) = rhs_element(i, 5); \ + lcol(6) = lhs_element(6, j); \ + rrow(6) = rhs_element(i, 6); \ + lcol(7) = lhs_element(7, j); \ + rrow(7) = rhs_element(i, 7); \ + +#define computeCol(j) \ + res(0, j) += lcol(0) * rrow(j); \ + res(1, j) += lcol(1) * rrow(j); \ + res(2, j) += lcol(2) * rrow(j); \ + res(3, j) += lcol(3) * rrow(j); \ + res(4, j) += lcol(4) * rrow(j); \ + res(5, j) += lcol(5) * rrow(j); \ + res(6, j) += lcol(6) * rrow(j); \ + res(7, j) += lcol(7) * rrow(j); \ + +#define computePass(i) \ + loadData(i, i); \ + \ + computeCol(0); \ + computeCol(1); \ + computeCol(2); \ + computeCol(3); \ + computeCol(4); \ + computeCol(5); \ + computeCol(6); \ + computeCol(7); \ + + computePass(0); + computePass(1); + computePass(2); + computePass(3); + computePass(4); + computePass(5); + computePass(6); + computePass(7); + +#undef lcol +#undef rrow +#undef lhs_element +#undef rhs_element +#undef loadData +#undef computeCol +#undef computePass + } // end loop over k + + // we've now iterated over all of the large (ie width 64) k blocks and + // accumulated results in registers. At this point thread (x, y, z) contains + // the sum across all big k blocks of the product of little k block of index (x, y) + // with block of index (y, z). To compute the final output, we need to reduce + // the 8 threads over y by summation. +#if defined(EIGEN_HIPCC) || (defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000) +#define shuffleInc(i, j, mask) res(i, j) += __shfl_xor(res(i, j), mask) +#else +#define shuffleInc(i, j, mask) res(i, j) += __shfl_xor_sync(0xFFFFFFFF, res(i, j), mask) +#endif + +#define reduceRow(i, mask) \ + shuffleInc(i, 0, mask); \ + shuffleInc(i, 1, mask); \ + shuffleInc(i, 2, mask); \ + shuffleInc(i, 3, mask); \ + shuffleInc(i, 4, mask); \ + shuffleInc(i, 5, mask); \ + shuffleInc(i, 6, mask); \ + shuffleInc(i, 7, mask); \ + +#define reduceMatrix(mask) \ + reduceRow(0, mask); \ + reduceRow(1, mask); \ + reduceRow(2, mask); \ + reduceRow(3, mask); \ + reduceRow(4, mask); \ + reduceRow(5, mask); \ + reduceRow(6, mask); \ + reduceRow(7, mask); \ + + // actually perform the reduction, now each thread of index (_, y, z) + // contains the correct values in its registers that belong in the output + // block + reduceMatrix(1); + reduceMatrix(2); + reduceMatrix(4); + +#undef shuffleInc +#undef reduceRow +#undef reduceMatrix + + // now we need to copy the 64 values into main memory. We can't split work + // among threads because all variables are in registers. There's 2 ways + // to do this: + // (1) have 1 thread do 64 writes from registers into global memory + // (2) have 1 thread do 64 writes into shared memory, and then 8 threads + // each do 8 writes into global memory. We can just overwrite the shared + // memory from the problem we just solved. + // (2) is slightly faster than (1) due to less branching and more ILP + + // TODO: won't yield much gain, but could just use currently unused shared mem + // and then we won't have to sync + // wait for shared mem to be out of use + __syncthreads(); + +#define writeResultShmem(i, j) \ + lhs_shmem[i + 8 * threadIdx.y + 64 * threadIdx.z + 512 * j] = res(i, j); \ + +#define writeRow(i) \ + writeResultShmem(i, 0); \ + writeResultShmem(i, 1); \ + writeResultShmem(i, 2); \ + writeResultShmem(i, 3); \ + writeResultShmem(i, 4); \ + writeResultShmem(i, 5); \ + writeResultShmem(i, 6); \ + writeResultShmem(i, 7); \ + + if (threadIdx.x == 0) { + writeRow(0); + writeRow(1); + writeRow(2); + writeRow(3); + writeRow(4); + writeRow(5); + writeRow(6); + writeRow(7); + } +#undef writeResultShmem +#undef writeRow + + const int max_i_write = numext::mini((int)((m_size - base_m - threadIdx.y + 7) / 8), 8); + const int max_j_write = numext::mini((int)((n_size - base_n - threadIdx.z + 7) / 8), 8); + + if (threadIdx.x < max_i_write) { + if (max_j_write == 8) { + // TODO: can i trade bank conflicts for coalesced writes? + Scalar val0 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 0]; + Scalar val1 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 1]; + Scalar val2 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 2]; + Scalar val3 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 3]; + Scalar val4 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 4]; + Scalar val5 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 5]; + Scalar val6 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 6]; + Scalar val7 = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * 7]; + + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 0) = val0; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 1) = val1; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 2) = val2; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 3) = val3; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 4) = val4; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 5) = val5; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 6) = val6; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * 7) = val7; + } else { +#pragma unroll 7 + for (int j = 0; j < max_j_write; j++) { + Scalar val = lhs_shmem[threadIdx.x + 8 * threadIdx.y + 64 * threadIdx.z + 512 * j]; + output(base_m + threadIdx.y + 8 * threadIdx.x, base_n + threadIdx.z + 8 * j) = val; + } + } + } +#undef res +} + + +template +__global__ void +#if defined(EIGEN_HIPCC) +__launch_bounds__(512, 1) +#else +__launch_bounds__(512) +#endif +EigenContractionKernel(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, + const Index m_size, const Index n_size, const Index k_size) { + __shared__ Scalar lhs_shmem[72 * 64]; + __shared__ Scalar rhs_shmem[72 * 64]; + + const Index m_block_idx = blockIdx.x; + const Index n_block_idx = blockIdx.y; + + const Index base_m = 64 * m_block_idx; + const Index base_n = 64 * n_block_idx; + + if (base_m + 63 < m_size && base_n + 63 < n_size) { + EigenContractionKernelInternal(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size); + } else { + EigenContractionKernelInternal(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size); + } +} + + +template +__device__ __forceinline__ void +EigenFloatContractionKernelInternal16x16(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, float2 lhs_shmem2[][16], + float2 rhs_shmem2[][8], const Index m_size, + const Index n_size, const Index k_size, + const Index base_m, const Index base_n) { + + // prefetch registers + float4 lhs_pf0, rhs_pf0; + + float4 results[4]; + for (int i=0; i < 4; i++) { + results[i].x = results[i].y = results[i].z = results[i].w = 0; + } + +#define prefetch_lhs(reg, row, col) \ + if (!CHECK_LHS_BOUNDARY) { \ + if (col < k_size) { \ + reg =lhs.template loadPacket(row, col); \ + } \ + } else { \ + if (col < k_size) { \ + if (row + 3 < m_size) { \ + reg =lhs.template loadPacket(row, col); \ + } else if (row + 2 < m_size) { \ + reg.x =lhs(row + 0, col); \ + reg.y =lhs(row + 1, col); \ + reg.z =lhs(row + 2, col); \ + } else if (row + 1 < m_size) { \ + reg.x =lhs(row + 0, col); \ + reg.y =lhs(row + 1, col); \ + } else if (row < m_size) { \ + reg.x =lhs(row + 0, col); \ + } \ + } \ + } \ + + Index lhs_vert = base_m+threadIdx.x*4; + + for (Index k = 0; k < k_size; k += 16) { + + lhs_pf0 = internal::pset1(0); + rhs_pf0 = internal::pset1(0); + + Index lhs_horiz = threadIdx.y+k; + prefetch_lhs(lhs_pf0, lhs_vert, lhs_horiz) + + Index rhs_vert = k+(threadIdx.x%4)*4; + Index rhs_horiz0 = (threadIdx.x>>2)+threadIdx.y*4+base_n; + + if (!CHECK_RHS_BOUNDARY) { + if ((rhs_vert + 3) < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0 = rhs.template loadPacket(rhs_vert, rhs_horiz0); + } else if (rhs_vert + 2 < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0); + } else if (rhs_vert + 1 < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + } else if (rhs_vert < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + } + } else { + if (rhs_horiz0 < n_size) { + if ((rhs_vert + 3) < k_size) { + rhs_pf0 = rhs.template loadPacket(rhs_vert, rhs_horiz0); + } else if ((rhs_vert + 2) < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0); + } else if ((rhs_vert + 1) < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + } else if (rhs_vert < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + } + } + } + float x1, x2 ; + // the following can be a bitwise operation..... some day. + if((threadIdx.x%8) < 4) { + x1 = rhs_pf0.y; + x2 = rhs_pf0.w; + } else { + x1 = rhs_pf0.x; + x2 = rhs_pf0.z; + } + #if defined(EIGEN_HIPCC) || (defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000) + x1 = __shfl_xor(x1, 4); + x2 = __shfl_xor(x2, 4); + #else + x1 = __shfl_xor_sync(0xFFFFFFFF, x1, 4); + x2 = __shfl_xor_sync(0xFFFFFFFF, x2, 4); + #endif + if((threadIdx.x%8) < 4) { + rhs_pf0.y = x1; + rhs_pf0.w = x2; + } else { + rhs_pf0.x = x1; + rhs_pf0.z = x2; + } + + // We have 64 features. + // Row 0 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 0, 1. + // Row 1 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 2, 3. + // ... + // Row 31 -> times (0, 4, 8, 12, 1, 5, 9, 13) for features 62, 63 + // Row 32 -> times (2, 6, 10, 14, 3, 7, 11, 15) for features 0, 1 + // ... + rhs_shmem2[(threadIdx.x>>3)+ threadIdx.y*2][threadIdx.x%8] = make_float2(rhs_pf0.x, rhs_pf0.y); + rhs_shmem2[(threadIdx.x>>3)+ threadIdx.y*2+32][threadIdx.x%8] = make_float2(rhs_pf0.z, rhs_pf0.w); + + // Row 0 (time 0) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) + // Row 1 (time 1) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) + // ... + // Row 15 (time 15) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) + // Row 16 (time 0) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63) + // ... + + lhs_shmem2[threadIdx.y][threadIdx.x] = make_float2(lhs_pf0.x, lhs_pf0.y); + lhs_shmem2[threadIdx.y+16][threadIdx.x] = make_float2(lhs_pf0.z, lhs_pf0.w); + + +#define add_vals(fl1, fl2, fr1, fr2)\ + results[0].x += fl1.x * fr1.x;\ + results[0].y += fl1.y * fr1.x;\ + results[0].z += fl2.x * fr1.x;\ + results[0].w += fl2.y * fr1.x;\ +\ + results[1].x += fl1.x * fr1.y;\ + results[1].y += fl1.y * fr1.y;\ + results[1].z += fl2.x * fr1.y;\ + results[1].w += fl2.y * fr1.y;\ +\ + results[2].x += fl1.x * fr2.x;\ + results[2].y += fl1.y * fr2.x;\ + results[2].z += fl2.x * fr2.x;\ + results[2].w += fl2.y * fr2.x;\ +\ + results[3].x += fl1.x * fr2.y;\ + results[3].y += fl1.y * fr2.y;\ + results[3].z += fl2.x * fr2.y;\ + results[3].w += fl2.y * fr2.y;\ + + __syncthreads(); + + // Do the multiplies. + #pragma unroll + for (int koff = 0; koff < 16; koff ++) { + // 32 x threads. + float2 fl1 = lhs_shmem2[koff][threadIdx.x]; + float2 fl2 = lhs_shmem2[koff + 16][threadIdx.x]; + + int start_feature = threadIdx.y * 4; + float2 fr1 = rhs_shmem2[(start_feature>>1) + 32*((koff%4)/2)][koff/4 + (koff%2)*4]; + float2 fr2 = rhs_shmem2[(start_feature>>1) + 1 + 32*((koff%4)/2)][koff/4 + (koff%2)*4]; + + add_vals(fl1, fl2, fr1, fr2) + } + __syncthreads(); + } + +#undef prefetch_lhs +#undef add_vals + + Index horiz_base = threadIdx.y*4+base_n; + if (!CHECK_LHS_BOUNDARY && !CHECK_RHS_BOUNDARY) { + for (int i = 0; i < 4; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } else if (!CHECK_RHS_BOUNDARY) { + // CHECK LHS + if (lhs_vert + 3 < m_size) { + for (int i = 0; i < 4; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } else if (lhs_vert + 2 < m_size) { + for (int i = 0; i < 4; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + } + } else if (lhs_vert + 1 < m_size) { + for (int i = 0; i < 4; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + } + } else if (lhs_vert < m_size) { + for (int i = 0; i < 4; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + } + } + } else if (!CHECK_LHS_BOUNDARY) { + // CHECK RHS + /* + int ncols_rem = fminf(n_size- horiz_base, 4); + for (int i = 0; i < ncols_rem; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + }*/ + for (int i = 0; i < 4; i++) { + if (horiz_base+i < n_size) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } + } else { + // CHECK both boundaries. + for (int i = 0; i < 4; i++) { + if (horiz_base+i < n_size) { + if (lhs_vert < m_size) + output(lhs_vert, horiz_base + i) = results[i].x; + if (lhs_vert + 1 < m_size) + output(lhs_vert + 1, horiz_base + i) = results[i].y; + if (lhs_vert + 2 < m_size) + output(lhs_vert + 2, horiz_base + i) = results[i].z; + if (lhs_vert + 3 < m_size) + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } + } +} + + +template +__device__ __forceinline__ void +EigenFloatContractionKernelInternal(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, float2 lhs_shmem2[][32], + float2 rhs_shmem2[][8], const Index m_size, + const Index n_size, const Index k_size, + const Index base_m, const Index base_n) { + + // prefetch registers + float4 lhs_pf0, lhs_pf1, lhs_pf2, lhs_pf3; + float4 rhs_pf0, rhs_pf1; + + float4 results[8]; + for (int i=0; i < 8; i++) { + results[i].x = results[i].y = results[i].z = results[i].w = 0; + } + + Index lhs_vert = base_m+threadIdx.x*4+(threadIdx.y%4)*32; + for (Index k = 0; k < k_size; k += 32) { + lhs_pf0 = internal::pset1(0); + lhs_pf1 = internal::pset1(0); + lhs_pf2 = internal::pset1(0); + lhs_pf3 = internal::pset1(0); + + rhs_pf0 = internal::pset1(0); + rhs_pf1 = internal::pset1(0); + + if (!CHECK_LHS_BOUNDARY) { + if ((threadIdx.y/4+k+24) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + lhs_pf2 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+16)); + lhs_pf3 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+24)); + } else if ((threadIdx.y/4+k+16) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + lhs_pf2 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+16)); + } else if ((threadIdx.y/4+k+8) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + } else if ((threadIdx.y/4+k) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + } + } else { + // just CHECK_LHS_BOUNDARY + if (lhs_vert + 3 < m_size) { + if ((threadIdx.y/4+k+24) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + lhs_pf2 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+16)); + lhs_pf3 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+24)); + } else if ((threadIdx.y/4+k+16) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + lhs_pf2 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+16)); + } else if ((threadIdx.y/4+k+8) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + lhs_pf1 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k+8)); + } else if ((threadIdx.y/4+k) < k_size) { + lhs_pf0 =lhs.template loadPacket(lhs_vert, (threadIdx.y/4+k)); + } + } else if (lhs_vert + 2 < m_size) { + if ((threadIdx.y/4+k+24) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16)); + lhs_pf2.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+16)); + lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24)); + lhs_pf3.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+24)); + lhs_pf3.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+24)); + } else if ((threadIdx.y/4+k+16) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16)); + lhs_pf2.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+16)); + } else if ((threadIdx.y/4+k+8) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + lhs_pf1.z =lhs(lhs_vert + 2, (threadIdx.y/4+k+8)); + } else if ((threadIdx.y/4+k) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf0.z =lhs(lhs_vert + 2, (threadIdx.y/4+k)); + } + } else if (lhs_vert + 1 < m_size) { + if ((threadIdx.y/4+k+24) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16)); + lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24)); + lhs_pf3.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+24)); + } else if ((threadIdx.y/4+k+16) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + lhs_pf2.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+16)); + } else if ((threadIdx.y/4+k+8) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf1.y =lhs(lhs_vert + 1, (threadIdx.y/4+k+8)); + } else if ((threadIdx.y/4+k) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf0.y =lhs(lhs_vert + 1, (threadIdx.y/4+k)); + } + } else if (lhs_vert < m_size) { + if ((threadIdx.y/4+k+24) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + lhs_pf3.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+24)); + } else if ((threadIdx.y/4+k+16) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + lhs_pf2.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+16)); + } else if ((threadIdx.y/4+k+8) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + lhs_pf1.x =lhs(lhs_vert + 0, (threadIdx.y/4+k+8)); + } else if ((threadIdx.y/4+k) < k_size) { + lhs_pf0.x =lhs(lhs_vert + 0, (threadIdx.y/4+k)); + } + } + } + __syncthreads(); + Index rhs_vert = k+threadIdx.x*4; + Index rhs_horiz0 = threadIdx.y*2+base_n; + Index rhs_horiz1 = threadIdx.y*2+1+base_n; + if (!CHECK_RHS_BOUNDARY) { + if ((rhs_vert + 3) < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0 = rhs.template loadPacket(rhs_vert, rhs_horiz0); + rhs_pf1 = rhs.template loadPacket(rhs_vert, rhs_horiz1); + } else if (rhs_vert + 2 < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1); + rhs_pf1.z = rhs(rhs_vert + 2, rhs_horiz1); + } else if (rhs_vert + 1 < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1); + } else if (rhs_vert < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + } + } else { + if (rhs_horiz1 < n_size) { + if ((rhs_vert + 3) < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0 = rhs.template loadPacket(rhs_vert, rhs_horiz0); + rhs_pf1 = rhs.template loadPacket(rhs_vert, rhs_horiz1); + } else if (rhs_vert + 2 < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1); + rhs_pf1.z = rhs(rhs_vert + 2, rhs_horiz1); + } else if (k+threadIdx.x*4 + 1 < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + rhs_pf1.y = rhs(rhs_vert + 1, rhs_horiz1); + } else if (k+threadIdx.x*4 < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf1.x = rhs(rhs_vert, rhs_horiz1); + } + } else if (rhs_horiz0 < n_size) { + if ((rhs_vert + 3) < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0 = rhs.template loadPacket(rhs_vert, rhs_horiz0); + } else if ((rhs_vert + 2) < k_size) { + // just CHECK_RHS_BOUNDARY + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + rhs_pf0.z = rhs(rhs_vert + 2, rhs_horiz0); + } else if ((rhs_vert + 1) < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + rhs_pf0.y = rhs(rhs_vert + 1, rhs_horiz0); + } else if (rhs_vert < k_size) { + rhs_pf0.x = rhs(rhs_vert, rhs_horiz0); + } + } + } + __syncthreads(); + // Loaded. Do computation + // Row 0 -> times (0, 4, 8, .. 28) for features 0, 1. + // Row 1 -> times (0, 4, 8, .. 28) for features 2, 3. + // .. + // Row 31 -> times (0, 4, 8, .. 28) for features 62, 63 + rhs_shmem2[threadIdx.y][threadIdx.x] = make_float2(rhs_pf0.x, rhs_pf1.x); + // Row 32 -> times (1, 5, 9, .. 29) for features 0, 1. + // Row 33 -> times (1, 5, 9, .. 29) for features 2, 3. + // .. + rhs_shmem2[threadIdx.y+32][threadIdx.x] = make_float2(rhs_pf0.y, rhs_pf1.y); + // Row 64 -> times (2, 6, 10, .. 30) for features 0, 1. + // Row 65 -> times (2, 6, 10, .. 30) for features 2, 3. + rhs_shmem2[threadIdx.y+64][threadIdx.x] = make_float2(rhs_pf0.z, rhs_pf1.z); + // Row 96 -> times (3, 7, 11, .. 31) for features 0, 1. + // Row 97 -> times (3, 7, 11, .. 31) for features 2, 3. + rhs_shmem2[threadIdx.y+96][threadIdx.x] = make_float2(rhs_pf0.w, rhs_pf1.w); + + // LHS. + // Row 0 (time 0) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) .. (124, 125) + // Row 1 (time 1) -> features (0, 1), (4, 5), .. (28, 29), (32, 33), .. (60, 61) .. (124, 125) + // ... + // Row 8 (time 0) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63) .. (126, 127) + // Row 15 (time 7) -> features (2, 3), (6, 7), .. (30, 31), (34, 35), .. (62, 63) .. (126, 127) + + +#define add_vals(a_feat1, a_feat2, f1, f2, f3, f4)\ + results[0].x += a_feat1.x * f1.x;\ + results[1].x += a_feat1.x * f1.y;\ + results[2].x += a_feat1.x * f2.x;\ + results[3].x += a_feat1.x * f2.y;\ + results[4].x += a_feat1.x * f3.x;\ + results[5].x += a_feat1.x * f3.y;\ + results[6].x += a_feat1.x * f4.x;\ + results[7].x += a_feat1.x * f4.y;\ +\ + results[0].y += a_feat1.y * f1.x;\ + results[1].y += a_feat1.y * f1.y;\ + results[2].y += a_feat1.y * f2.x;\ + results[3].y += a_feat1.y * f2.y;\ + results[4].y += a_feat1.y * f3.x;\ + results[5].y += a_feat1.y * f3.y;\ + results[6].y += a_feat1.y * f4.x;\ + results[7].y += a_feat1.y * f4.y;\ +\ + results[0].z += a_feat2.x * f1.x;\ + results[1].z += a_feat2.x * f1.y;\ + results[2].z += a_feat2.x * f2.x;\ + results[3].z += a_feat2.x * f2.y;\ + results[4].z += a_feat2.x * f3.x;\ + results[5].z += a_feat2.x * f3.y;\ + results[6].z += a_feat2.x * f4.x;\ + results[7].z += a_feat2.x * f4.y;\ +\ + results[0].w += a_feat2.y * f1.x;\ + results[1].w += a_feat2.y * f1.y;\ + results[2].w += a_feat2.y * f2.x;\ + results[3].w += a_feat2.y * f2.y;\ + results[4].w += a_feat2.y * f3.x;\ + results[5].w += a_feat2.y * f3.y;\ + results[6].w += a_feat2.y * f4.x;\ + results[7].w += a_feat2.y * f4.y;\ + + lhs_shmem2[threadIdx.y/4][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf0.x, lhs_pf0.y); + lhs_shmem2[threadIdx.y/4+8][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf1.x, lhs_pf1.y); + lhs_shmem2[threadIdx.y/4+16][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf2.x, lhs_pf2.y); + lhs_shmem2[threadIdx.y/4+24][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf3.x, lhs_pf3.y); + + lhs_shmem2[threadIdx.y/4 + 32][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf0.z, lhs_pf0.w); + lhs_shmem2[threadIdx.y/4 + 40][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf1.z, lhs_pf1.w); + lhs_shmem2[threadIdx.y/4 + 48][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf2.z, lhs_pf2.w); + lhs_shmem2[threadIdx.y/4 + 56][threadIdx.x+(threadIdx.y%4)*8] = make_float2(lhs_pf3.z, lhs_pf3.w); + + __syncthreads(); + + // Do the multiplies. + #pragma unroll + for (int koff = 0; koff < 32; koff ++) { + float2 a3 = lhs_shmem2[koff][threadIdx.x + (threadIdx.y % 4) * 8]; + float2 a4 = lhs_shmem2[koff + 32][threadIdx.x + (threadIdx.y % 4) * 8]; + + // first feature is at (threadIdx.y/4) * 8 last is at start + 8. + int start_feature = (threadIdx.y / 4) * 8; + + float2 br1 = rhs_shmem2[start_feature/2 + (koff % 4) * 32][koff/4]; + float2 br2 = rhs_shmem2[start_feature/2 + 1 + (koff % 4) * 32][koff/4]; + float2 br3 = rhs_shmem2[start_feature/2 + 2 + (koff % 4) * 32][koff/4]; + float2 br4 = rhs_shmem2[start_feature/2 + 3 + (koff % 4) * 32][koff/4]; + + add_vals(a3, a4, br1, br2, br3, br4) + } + __syncthreads(); + } // end loop over k + + __syncthreads(); + Index horiz_base = (threadIdx.y/4)*8+base_n; + if (!CHECK_LHS_BOUNDARY && !CHECK_RHS_BOUNDARY) { + for (int i = 0; i < 8; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } else if (!CHECK_RHS_BOUNDARY) { + if (lhs_vert + 3 < m_size) { + for (int i = 0; i < 8; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } else if (lhs_vert + 2 < m_size) { + for (int i = 0; i < 8; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + } + } else if (lhs_vert + 1 < m_size) { + for (int i = 0; i < 8; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + } + } else if (lhs_vert < m_size) { + for (int i = 0; i < 8; i++) { + output(lhs_vert, horiz_base + i) = results[i].x; + } + } + } else if (!CHECK_LHS_BOUNDARY) { + // CHECK BOUNDARY_B + for (int i = 0; i < 8; i++) { + if (horiz_base + i < n_size) { + output(lhs_vert, horiz_base + i) = results[i].x; + output(lhs_vert + 1, horiz_base + i) = results[i].y; + output(lhs_vert + 2, horiz_base + i) = results[i].z; + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } + } else { + // CHECK both boundaries. + for (int i = 0; i < 8; i++) { + if (horiz_base + i < n_size) { + if (lhs_vert < m_size) + output(lhs_vert, horiz_base + i) = results[i].x; + if (lhs_vert + 1 < m_size) + output(lhs_vert + 1, horiz_base + i) = results[i].y; + if (lhs_vert + 2 < m_size) + output(lhs_vert + 2, horiz_base + i) = results[i].z; + if (lhs_vert + 3 < m_size) + output(lhs_vert + 3, horiz_base + i) = results[i].w; + } + } + } +} + + +template +__global__ void +#if defined(EIGEN_HIPCC) +__launch_bounds__(256, 1) +#else +__launch_bounds__(256) +#endif +EigenFloatContractionKernel(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, + const Index m_size, const Index n_size, const Index k_size) { + __shared__ float2 lhs_shmem[64*32]; + __shared__ float2 rhs_shmem[128*8]; + + typedef float2 LHS_MEM[64][32]; + typedef float2 RHS_MEM[128][8]; + + const Index m_block_idx = blockIdx.x; + const Index n_block_idx = blockIdx.y; + + const Index base_m = 128 * m_block_idx; + const Index base_n = 64 * n_block_idx; + + bool check_rhs = (base_n + 63) >= n_size; + bool check_lhs128 = (base_m + 127) >= m_size; + + if (!check_rhs) { + if (!check_lhs128) { + // >= 128 rows left + EigenFloatContractionKernelInternal( + lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n); + } else { + EigenFloatContractionKernelInternal( + lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n); + } + } else { + if (!check_lhs128) { + // >= 128 rows left + EigenFloatContractionKernelInternal( + lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n); + } else { + EigenFloatContractionKernelInternal( + lhs, rhs, output, *((LHS_MEM *) lhs_shmem), *((RHS_MEM *) rhs_shmem), m_size, n_size, k_size, base_m, base_n); + } + } +} + +template +__global__ void +#if defined(EIGEN_HIPCC) +__launch_bounds__(256, 1) +#else +__launch_bounds__(256) +#endif +EigenFloatContractionKernel16x16(const LhsMapper lhs, const RhsMapper rhs, + const OutputMapper output, + const Index m_size, const Index n_size, const Index k_size) { + __shared__ float2 lhs_shmem[32][16]; + __shared__ float2 rhs_shmem[64][8]; + + const Index m_block_idx = blockIdx.x; + const Index n_block_idx = blockIdx.y; + + const Index base_m = 64 * m_block_idx; + const Index base_n = 64 * n_block_idx; + + if (base_m + 63 < m_size) { + if (base_n + 63 < n_size) { + EigenFloatContractionKernelInternal16x16(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n); + } else { + EigenFloatContractionKernelInternal16x16(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n); + } + } else { + if (base_n + 63 < n_size) { + EigenFloatContractionKernelInternal16x16(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n); + } else { + EigenFloatContractionKernelInternal16x16(lhs, rhs, output, lhs_shmem, rhs_shmem, m_size, n_size, k_size, base_m, base_n); + } + } +} + + +template +struct TensorEvaluator, GpuDevice> : + public TensorContractionEvaluatorBase, GpuDevice> > { + + typedef GpuDevice Device; + + typedef TensorEvaluator, Device> Self; + typedef TensorContractionEvaluatorBase Base; + + typedef TensorContractionOp XprType; + typedef std::remove_const_t Scalar; + typedef typename XprType::Index Index; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + static constexpr int Layout = TensorEvaluator::Layout; + + // Most of the code is assuming that both input tensors are ColMajor. If the + // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS: + // If we want to compute A * B = C, where A is LHS and B is RHS, the code + // will pretend B is LHS and A is RHS. + typedef std::conditional_t(ColMajor), LeftArgType, RightArgType> EvalLeftArgType; + typedef std::conditional_t(ColMajor), RightArgType, LeftArgType> EvalRightArgType; + + static constexpr int LDims = + internal::array_size::Dimensions>::value; + static constexpr int RDims = + internal::array_size::Dimensions>::value; + static constexpr int ContractDims = internal::array_size::value; + + typedef array left_dim_mapper_t; + typedef array right_dim_mapper_t; + + typedef array contract_t; + typedef array left_nocontract_t; + typedef array right_nocontract_t; + + static constexpr int NumDims = LDims + RDims - 2 * ContractDims; + + typedef DSizes Dimensions; + + // typedefs needed in evalTo + typedef std::remove_const_t LhsScalar; + typedef std::remove_const_t RhsScalar; + + typedef TensorEvaluator LeftEvaluator; + typedef TensorEvaluator RightEvaluator; + + typedef typename LeftEvaluator::Dimensions LeftDimensions; + typedef typename RightEvaluator::Dimensions RightDimensions; + + TensorEvaluator(const XprType& op, const Device& device) : + Base(op, device) + { + EIGEN_STATIC_ASSERT( (internal::is_same::value), + GPU_TENSOR_CONTRACTION_DOES_NOT_SUPPORT_OUTPUT_KERNELS); + } + + // We need to redefine this method to make nvcc happy + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar* data) { + this->m_leftImpl.evalSubExprsIfNeeded(NULL); + this->m_rightImpl.evalSubExprsIfNeeded(NULL); + if (data) { + evalTo(data); + return false; + } else { + this->m_result = static_cast(this->m_device.allocate(this->dimensions().TotalSize() * sizeof(Scalar))); + evalTo(this->m_result); + return true; + } + } + + void evalTo(Scalar* buffer) const { + if (this->m_lhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } + else { + evalTyped(buffer); + } + } + else { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } + else { + evalTyped(buffer); + } + } + } + else { + if (this->m_rhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } + else { + evalTyped(buffer); + } + } + else { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } + else { + evalTyped(buffer); + } + } + } + } + + template struct LaunchKernels { + static void Run(const LhsMapper& lhs, const RhsMapper& rhs, const OutputMapper& output, Index m, Index n, Index k, const GpuDevice& device) { + const Index m_blocks = (m + 63) / 64; + const Index n_blocks = (n + 63) / 64; + const dim3 num_blocks(m_blocks, n_blocks, 1); + const dim3 block_size(8, 8, 8); + LAUNCH_GPU_KERNEL((EigenContractionKernel), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k); + } + }; + + template struct LaunchKernels { + static void Run(const LhsMapper& lhs, const RhsMapper& rhs, const OutputMapper& output, Index m, Index n, Index k, const GpuDevice& device) { + if (m < 768 || n < 768) { + const Index m_blocks = (m + 63) / 64; + const Index n_blocks = (n + 63) / 64; + const dim3 num_blocks(m_blocks, n_blocks, 1); + const dim3 block_size(16, 16, 1); + LAUNCH_GPU_KERNEL((EigenFloatContractionKernel16x16), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k); + } else { + const Index m_blocks = (m + 127) / 128; + const Index n_blocks = (n + 63) / 64; + const dim3 num_blocks(m_blocks, n_blocks, 1); + const dim3 block_size(8, 32, 1); + LAUNCH_GPU_KERNEL((EigenFloatContractionKernel), num_blocks, block_size, 0, device, lhs, rhs, output, m, n, k); + } + } + }; + + template + void evalTyped(Scalar* buffer) const { + // columns in left side, rows in right side + const Index k = this->m_k_size; + EIGEN_UNUSED_VARIABLE(k) + + // rows in left side + const Index m = this->m_i_size; + + // columns in right side + const Index n = this->m_j_size; + + // zero out the result buffer (which must be of size at least m * n * sizeof(Scalar)) + this->m_device.fill(buffer, buffer + m * n, Scalar(0)); + + typedef internal::TensorContractionInputMapper LhsMapper; + + typedef internal::TensorContractionInputMapper RhsMapper; + + typedef internal::blas_data_mapper OutputMapper; + + + // initialize data mappers + LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides, + this->m_left_contracting_strides, this->m_k_strides); + + RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides, + this->m_right_contracting_strides, this->m_k_strides); + + OutputMapper output(buffer, m); + +#if defined(EIGEN_USE_HIP) + setGpuSharedMemConfig(hipSharedMemBankSizeEightByte); +#else + setGpuSharedMemConfig(cudaSharedMemBankSizeEightByte); +#endif + + LaunchKernels::Run(lhs, rhs, output, m, n, k, this->m_device); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_USE_GPU and EIGEN_GPUCC +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_GPU_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h new file mode 100644 index 0000000000000000000000000000000000000000..7fb54b9610d7f9bffc0e5fa6478a4f2960e336c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h @@ -0,0 +1,573 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +enum { + Rhs = 0, + Lhs = 1 +}; + +/* + * Implementation of the Eigen blas_data_mapper class for tensors. + */ +/// The make pointer class is used by sycl in order to build the mapper class on the device. For other platform the default make pointer is used which +/// is scalar * for CoeffLoader. +template class MakePointer_ = MakePointer> +struct CoeffLoader; + +template class MakePointer_ = MakePointer> +class BaseTensorContractionMapper; + +template class MakePointer_> +struct CoeffLoader { + enum { + DirectOffsets = false + }; + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffLoader(const Tensor& tensor) : m_tensor(tensor) { } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index) { + eigen_assert(false && "unsupported"); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const typename MakePointer_::Type + data() const { + eigen_assert(false && "unsupported"); + return NULL; + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE typename Tensor::Scalar coeff(typename Tensor::Index index) const { return m_tensor.coeff(index); } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename Tensor::PacketReturnType packet(typename Tensor::Index index) const + { + return m_tensor.template packet(index); + } + + private: + const Tensor m_tensor; +}; + +template class MakePointer_> +struct CoeffLoader { + enum { + DirectOffsets = true + }; + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffLoader(const Tensor& tensor) : m_data(tensor.data()) {} + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index offset) { + m_data += offset; + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const typename MakePointer_::Type + data() const { + return m_data; + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE typename Tensor::Scalar coeff(typename Tensor::Index index) const { return loadConstant(m_data+index); } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename Tensor::PacketReturnType packet(typename Tensor::Index index) const + { + return internal::ploadt_ro(m_data + index); + } + + private: + typedef typename Tensor::Scalar Scalar; + + typename MakePointer_::Type m_data; +}; + +template class MakePointer_ = MakePointer> +class SimpleTensorContractionMapper { + public: + EIGEN_DEVICE_FUNC + SimpleTensorContractionMapper(const Tensor& tensor, + const nocontract_t& nocontract_strides, + const nocontract_t& ij_strides, + const contract_t& contract_strides, + const contract_t& k_strides) : + m_tensor(tensor), + m_nocontract_strides(nocontract_strides), + m_ij_strides(ij_strides), + m_contract_strides(contract_strides), + m_k_strides(k_strides) { } + + enum { + DirectOffsets = CoeffLoader::DirectOffsets + }; + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void offsetBuffer(typename Tensor::Index offset) { + m_tensor.offsetBuffer(offset); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void prefetch(Index /*i*/) { } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar operator()(Index row) const { + // column major assumption + return operator()(row, 0); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar operator()(Index row, Index col) const { + return m_tensor.coeff(computeIndex(row, col)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index computeIndex(Index row, Index col) const { + const bool left = (side == Lhs); + EIGEN_UNUSED_VARIABLE(left); // annoying bug in g++8.1: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85963 + Index nocontract_val = left ? row : col; + Index linidx = 0; + EIGEN_UNROLL_LOOP + for (int i = static_cast(array_size::value) - 1; i > 0; i--) { + const Index idx = nocontract_val / m_ij_strides[i]; + linidx += idx * m_nocontract_strides[i]; + nocontract_val -= idx * m_ij_strides[i]; + } + if (array_size::value > array_size::value) { + if (side == Lhs && inner_dim_contiguous) { + eigen_assert(m_nocontract_strides[0] == 1); + linidx += nocontract_val; + } else { + linidx += nocontract_val * m_nocontract_strides[0]; + } + } + + Index contract_val = left ? col : row; + if(array_size::value > 0) { + EIGEN_UNROLL_LOOP + for (int i = static_cast(array_size::value) - 1; i > 0; i--) { + const Index idx = contract_val / m_k_strides[i]; + linidx += idx * m_contract_strides[i]; + contract_val -= idx * m_k_strides[i]; + } + + if (side == Rhs && inner_dim_contiguous) { + eigen_assert(m_contract_strides[0] == 1); + linidx += contract_val; + } else { + linidx += contract_val * m_contract_strides[0]; + } + } + + return linidx; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE IndexPair computeIndexPair(Index row, Index col, const Index distance) const { + const bool left = (side == Lhs); + EIGEN_UNUSED_VARIABLE(left); // annoying bug in g++8.1: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85963 + Index nocontract_val[2] = {left ? row : col, left ? row + distance : col}; + Index linidx[2] = {0, 0}; + if (array_size::value > array_size::value) { + EIGEN_UNROLL_LOOP + for (int i = static_cast(array_size::value) - 1; i > 0; i--) { + const Index idx0 = nocontract_val[0] / m_ij_strides[i]; + const Index idx1 = nocontract_val[1] / m_ij_strides[i]; + linidx[0] += idx0 * m_nocontract_strides[i]; + linidx[1] += idx1 * m_nocontract_strides[i]; + nocontract_val[0] -= idx0 * m_ij_strides[i]; + nocontract_val[1] -= idx1 * m_ij_strides[i]; + } + if (side == Lhs && inner_dim_contiguous) { + eigen_assert(m_nocontract_strides[0] == 1); + linidx[0] += nocontract_val[0]; + linidx[1] += nocontract_val[1]; + } else { + linidx[0] += nocontract_val[0] * m_nocontract_strides[0]; + linidx[1] += nocontract_val[1] * m_nocontract_strides[0]; + } + } + + Index contract_val[2] = {left ? col : row, left ? col : row + distance}; + if (array_size::value> 0) { + EIGEN_UNROLL_LOOP + for (int i = static_cast(array_size::value) - 1; i > 0; i--) { + const Index idx0 = contract_val[0] / m_k_strides[i]; + const Index idx1 = contract_val[1] / m_k_strides[i]; + linidx[0] += idx0 * m_contract_strides[i]; + linidx[1] += idx1 * m_contract_strides[i]; + contract_val[0] -= idx0 * m_k_strides[i]; + contract_val[1] -= idx1 * m_k_strides[i]; + } + + if (side == Rhs && inner_dim_contiguous) { + eigen_assert(m_contract_strides[0] == 1); + linidx[0] += contract_val[0]; + linidx[1] += contract_val[1]; + } else { + linidx[0] += contract_val[0] * m_contract_strides[0]; + linidx[1] += contract_val[1] * m_contract_strides[0]; + } + } + return IndexPair(linidx[0], linidx[1]); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index firstAligned(Index size) const { + // Only claim alignment when we can compute the actual stride (ie when we're + // dealing with the lhs with inner_dim_contiguous. This is because the + // matrix-vector product relies on the stride when dealing with aligned inputs. + return (Alignment == Aligned) && (side == Lhs) && inner_dim_contiguous ? 0 : size; + } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index stride() const { + return ((side == Lhs) && inner_dim_contiguous && array_size::value > 0) ? m_contract_strides[0] : 1; + } + + const CoeffLoader& tensor() const { + return m_tensor; + } + + const nocontract_t& nocontract_strides() const { + return m_nocontract_strides; + } + const nocontract_t& ij_strides() const { return m_ij_strides; } + const contract_t& contract_strides() const { return m_contract_strides; } + const contract_t& k_strides() const { return m_k_strides; } + + protected: + CoeffLoader m_tensor; + const nocontract_t m_nocontract_strides; + const nocontract_t m_ij_strides; + const contract_t m_contract_strides; + const contract_t m_k_strides; +}; + +template class MakePointer_> +class BaseTensorContractionMapper : public SimpleTensorContractionMapper +{ + public: + typedef SimpleTensorContractionMapper ParentMapper; + + EIGEN_DEVICE_FUNC + BaseTensorContractionMapper(const Tensor& tensor, + const nocontract_t& nocontract_strides, + const nocontract_t& ij_strides, + const contract_t& contract_strides, + const contract_t& k_strides) : + ParentMapper(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t::size==packet_size,PacketT> + load(Index i, Index j) const + { + // whole method makes column major assumption + + // don't need to add offsets for now (because operator handles that) + // current code assumes packet size must be a multiple of 2 + EIGEN_STATIC_ASSERT(packet_size % 2 == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + + if (Tensor::PacketAccess && inner_dim_contiguous && !inner_dim_reordered) { + const Index index = this->computeIndex(i, j); + eigen_assert(this->computeIndex(i+packet_size-1, j) == index + packet_size-1); + return this->m_tensor.template packet(index); + } + + const IndexPair indexPair = this->computeIndexPair(i, j, packet_size - 1); + const Index first = indexPair.first; + const Index lastIdx = indexPair.second; + + // We can always do optimized packet reads from left hand side right now, because + // the vertical matrix dimension on the left hand side is never contracting. + // On the right hand side we need to check if the contracting dimensions may have + // been shuffled first. + if (Tensor::PacketAccess && + (side == Lhs || internal::array_size::value <= 1 || !inner_dim_reordered) && + (lastIdx - first) == (packet_size - 1)) { + + return this->m_tensor.template packet(first); + } + + EIGEN_ALIGN_MAX Scalar data[packet_size]; + + data[0] = this->m_tensor.coeff(first); + EIGEN_UNROLL_LOOP + for (Index k = 1; k < packet_size - 1; k += 2) { + const IndexPair internal_pair = this->computeIndexPair(i + k, j, 1); + data[k] = this->m_tensor.coeff(internal_pair.first); + data[k + 1] = this->m_tensor.coeff(internal_pair.second); + } + data[packet_size - 1] = this->m_tensor.coeff(lastIdx); + + return pload(data); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t::size!=packet_size,PacketT> + load(Index i, Index j) const + { + const Index requested_packet_size = internal::unpacket_traits::size; + EIGEN_ALIGN_MAX Scalar data[requested_packet_size]; + + const IndexPair indexPair = this->computeIndexPair(i, j, requested_packet_size - 1); + const Index first = indexPair.first; + const Index lastIdx = indexPair.second; + + data[0] = this->m_tensor.coeff(first); + for (Index k = 1; k < requested_packet_size - 1; k += 2) { + const IndexPair internal_pair = this->computeIndexPair(i + k, j, 1); + data[k] = this->m_tensor.coeff(internal_pair.first); + data[k + 1] = this->m_tensor.coeff(internal_pair.second); + } + data[requested_packet_size - 1] = this->m_tensor.coeff(lastIdx); + + return pload(data); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PacketT loadPacket(Index i, Index j) const { + return this->load(i,j); + } +}; + + +template class MakePointer_> +class BaseTensorContractionMapper + : public SimpleTensorContractionMapper +{ + public: + typedef SimpleTensorContractionMapper ParentMapper; + + EIGEN_DEVICE_FUNC + BaseTensorContractionMapper(const Tensor& tensor, + const nocontract_t& nocontract_strides, + const nocontract_t& ij_strides, + const contract_t& contract_strides, + const contract_t& k_strides) : + ParentMapper(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PacketT loadPacket(Index i, Index j) const { + EIGEN_ALIGN_MAX Scalar data[1]; + data[0] = this->m_tensor.coeff(this->computeIndex(i, j)); + return pload(data); + } + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PacketT load(Index i, Index j) const { + EIGEN_ALIGN_MAX Scalar data[1]; + data[0] = this->m_tensor.coeff(this->computeIndex(i, j)); + return pload(data); + } +}; + + +template class MakePointer_=MakePointer> +class TensorContractionSubMapper { + public: + + typedef BaseTensorContractionMapper ParentMapper; + typedef TensorContractionSubMapper Self; + typedef Self LinearMapper; + typedef Self SubMapper; + + enum { + // We can use direct offsets iff the parent mapper supports then and we can compute the strides. + // TODO: we should also enable direct offsets for the Rhs case. + UseDirectOffsets = ParentMapper::DirectOffsets && (side == Lhs) && inner_dim_contiguous && (array_size::value > 0) + }; + + EIGEN_DEVICE_FUNC TensorContractionSubMapper(const ParentMapper& base_mapper, Index vert_offset, Index horiz_offset) + : m_base_mapper(base_mapper), m_vert_offset(vert_offset), m_horiz_offset(horiz_offset) { + // Bake the offsets into the buffer used by the base mapper whenever possible. This avoids the need to recompute + // this offset every time we attempt to access a coefficient. + if (UseDirectOffsets) { + Index stride = m_base_mapper.stride(); + m_base_mapper.offsetBuffer(vert_offset + horiz_offset * stride); + } + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar operator()(Index i) const { + if (UseDirectOffsets) { + return m_base_mapper(i, 0); + } + return m_base_mapper(i + m_vert_offset, m_horiz_offset); + } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Scalar operator()(Index i, Index j) const { + if (UseDirectOffsets) { + return m_base_mapper(i, j); + } + return m_base_mapper(i + m_vert_offset, j + m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i) const { + if (UseDirectOffsets) { + return m_base_mapper.template loadPacket(i, 0); + } + return m_base_mapper.template loadPacket(i + m_vert_offset, m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i, Index j) const { + if (UseDirectOffsets) { + return m_base_mapper.template loadPacket(i, j); + } + return m_base_mapper.template loadPacket(i + m_vert_offset, j + m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacketPartial(Index i, Index j, Index, Index = 0) const { + if (UseDirectOffsets) { + return m_base_mapper.template loadPacket(i, j); + } + return m_base_mapper.template loadPacket(i + m_vert_offset, j + m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT loadPacket(Index i, Index j) const { + if (UseDirectOffsets) { + return m_base_mapper.template load(i, j); + } + return m_base_mapper.template loadPacket(i + m_vert_offset, j + m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void storePacket(Index i, const PacketT& p) const { + if (UseDirectOffsets) { + m_base_mapper.storePacket(i, 0, p); + } + m_base_mapper.storePacket(i + m_vert_offset, m_horiz_offset, p); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE LinearMapper getLinearMapper(Index i, Index j) const { + if (UseDirectOffsets) { + return LinearMapper(m_base_mapper, i, j); + } + return LinearMapper(m_base_mapper, i + m_vert_offset, j + m_horiz_offset); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SubMapper getSubMapper(Index i, Index j) const { + if (UseDirectOffsets) { + return SubMapper(m_base_mapper, i, j); + } + return SubMapper(m_base_mapper, i + m_vert_offset, j + m_horiz_offset); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const Index stride() const { return m_base_mapper.stride(); } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketT load(Index i) const { + EIGEN_STATIC_ASSERT((internal::is_same::value), YOU_MADE_A_PROGRAMMING_MISTAKE); + const int ActualAlignment = (AlignmentType == Aligned) && (Alignment == Aligned) ? Aligned : Unaligned; + if (UseDirectOffsets) { + return m_base_mapper.template loadPacket(i, 0); + } + return m_base_mapper.template loadPacket(i + m_vert_offset, m_horiz_offset); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool aligned(Index) const { + return false; + } + + const ParentMapper& base_mapper() const { return m_base_mapper; } + Index vert_offset() const { return m_vert_offset; } + Index horiz_offset() const { return m_horiz_offset; } + + private: + ParentMapper m_base_mapper; + const Index m_vert_offset; + const Index m_horiz_offset; +}; + + +template class MakePointer_=MakePointer> +class TensorContractionInputMapper + : public BaseTensorContractionMapper { + + public: + typedef Scalar_ Scalar; + typedef BaseTensorContractionMapper Base; + typedef TensorContractionSubMapper SubMapper; + typedef SubMapper VectorMapper; + typedef SubMapper LinearMapper; + + EIGEN_DEVICE_FUNC TensorContractionInputMapper(const Tensor& tensor, + const nocontract_t& nocontract_strides, + const nocontract_t& ij_strides, + const contract_t& contract_strides, + const contract_t& k_strides) + : Base(tensor, nocontract_strides, ij_strides, contract_strides, k_strides) { } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE SubMapper getSubMapper(Index i, Index j) const { + return SubMapper(*this, i, j); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE LinearMapper getLinearMapper(Index i, Index j) const { + return LinearMapper(*this, i, j); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE VectorMapper getVectorMapper(Index i, Index j) const { + return VectorMapper(*this, i, j); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE const CoeffLoader& get_tensor() const { + return Base::m_tensor; + } +}; + + +template struct TensorContractionInputMapperTrait; + +template class MakePointer_> +struct TensorContractionInputMapperTrait > { + + typedef Tensor_ XprType; + static const bool inner_dim_contiguous = inner_dim_contiguous_; + static const bool inner_dim_reordered = inner_dim_reordered_; + }; + + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_MAPPER_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h new file mode 100644 index 0000000000000000000000000000000000000000..a4e0fc702def75acb3c365400c592a972ced93e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h @@ -0,0 +1,1645 @@ +// This file is part of Eigen, a lightweight C++ template library for linear algebra. +// +// Mehdi Goli Codeplay Software Ltd. +// Ralph Potter Codeplay Software Ltd. +// Luke Iwanski Codeplay Software Ltd. +// Contact: +// +// This Source Code Form is subject to the terms of the Mozilla Public License v. 2.0. If a copy of the MPL was not +// distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/***************************************************************** + * TensorContractionSycl.h + * + * \brief: + * TensorContractionSycl.h, provides various tensor contraction kernel for SYCL backend + * + *****************************************************************/ + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace TensorSycl { +namespace internal { + +#ifndef EIGEN_SYCL_DISABLE_GEMV +/*! + * \brief TVPanelSize, a template class used for setting the panel size required for launching General TensorVector + * contraction kernel on various hardware devices. + * + * \tparam Scalar: determines the element type of the tensor/vector + * + * \tparam StorageIndex determines the Index type. + * + * \tparam NCWindow: determines the number of non-contracting element to be process by each work-group + * + * \tparam CFactor: determines the number of contracting element to be process by each thread + * + * \tparam NCFactor: determines the number of non-contracting element to be process by each thread + */ +template +struct TVPanelSize { + // LocalThreadSizeC: determines total number of thread per workgroup for the contracting dimension + static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeC = EIGEN_SYCL_LOCAL_THREAD_DIM0; + // LocalThreadSizeNC: determines total number of thread per workgroup for the non-contracting dimension + static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeNC = EIGEN_SYCL_LOCAL_THREAD_DIM1; + // TileSizeDimNC: determines the tile size for the non-contracting dimension + static EIGEN_CONSTEXPR StorageIndex TileSizeDimNC = NCWindow / NCFactor; + // TileSizeDimC: determines the tile size for the contracting dimension + static EIGEN_CONSTEXPR StorageIndex TileSizeDimC = CFactor * LocalThreadSizeNC * LocalThreadSizeC; + // WorkLoadPerThreadNC : determines workload per thread for loading the non-contracting dimension + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadNC = TileSizeDimNC / LocalThreadSizeNC; + // WorkLoadPerThreadC: determines workload per thread for loading the non-contracting dimension + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadC = TileSizeDimC / LocalThreadSizeC; + // BC : determines if supporting bank conflict is required + static EIGEN_CONSTEXPR bool BC = false; +}; +#endif + +/*! + * \brief TTPanelSize, a template class used for setting the panel size required for launching General Tensor Tensor + contraction kernel on various hardware devices. + * + * \tparam Scalar: determines the element type of the tensor + * + * \tparam StorageIndex: determines the Index type. + * + * \tparam REG_SIZE_M: determines workload per thread for loading the M dimension This can be varied based on the + available register on a chosen device(can be controlled by EIGEN_SYCL_REG_M macro). + * + * \tparam REG_SIZE_N: determines workload per thread for loading the N dimension This can be varied based on the + available register on a chosen device(can be controlled by EIGEN_SYCL_REG_N macro). + * + * \tparam TSDK: determines Tile size for dimension K. The packet size is assumed to be considered + */ + +template +struct TTPanelSize { + // TileSizeDimK: determines Tile size for dimension K. The packet size is assumed to be considered + static EIGEN_CONSTEXPR StorageIndex TileSizeDimK = TSDK; + // WorkLoadPerThreadM : determines workload per thread for loading the M dimension This can be varied based on the + // available register on a chosen device(can be controlled by EIGEN_SYCL_REG_M macro// +#ifndef EIGEN_SYCL_REG_M + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadM = REG_SIZE_M; +#else + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadM = EIGEN_SYCL_REG_M; +#endif +// WorkLoadPerThreadN : determines workload per thread for loading the N dimension This can be varied based on the +// available register on a chosen device(can be controlled by EIGEN_SYCL_REG_N macro +#ifndef EIGEN_SYCL_REG_N + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadN = REG_SIZE_N; +#else + static EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadN = EIGEN_SYCL_REG_N; +#endif + // LocalThreadSizeM: determines total number of thread per workgroup for the m dimension + static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeM = EIGEN_SYCL_LOCAL_THREAD_DIM0; + // LocalThreadSizeN: determines total number of thread per workgroup for the n dimension + static EIGEN_CONSTEXPR StorageIndex LocalThreadSizeN = EIGEN_SYCL_LOCAL_THREAD_DIM1; + // TileSizeDimM: determines the tile size for the m dimension + static EIGEN_CONSTEXPR StorageIndex TileSizeDimM = LocalThreadSizeM * WorkLoadPerThreadM; + // TileSizeDimN: determines the tile size for the n dimension + static EIGEN_CONSTEXPR StorageIndex TileSizeDimN = LocalThreadSizeN * WorkLoadPerThreadN; + // LoadPerThreadLhs: determines workload per thread for loading Lhs Tensor. This must be divisable by packetsize + static EIGEN_CONSTEXPR StorageIndex LoadPerThreadLhs = + ((TileSizeDimK * WorkLoadPerThreadM * WorkLoadPerThreadN) / (TileSizeDimN)); + // LoadPerThreadRhs: determines workload per thread for loading Rhs Tensor. This must be divisable by packetsize + static EIGEN_CONSTEXPR StorageIndex LoadPerThreadRhs = + ((TileSizeDimK * WorkLoadPerThreadM * WorkLoadPerThreadN) / (TileSizeDimM)); + // BC : determines if supporting bank conflict is required + static EIGEN_CONSTEXPR bool BC = true; + // DoubleBuffer: determines if double buffering technique should be used (This can be disabled by + // EIGEN_SYCL_DISABLE_DOUBLE_BUFFER macro when the device does not have sufficient local memory) + static EIGEN_CONSTEXPR bool DoubleBuffer = +#ifdef EIGEN_SYCL_DISABLE_DOUBLE_BUFFER + false; +#else + true; +#endif +}; + +/* ! + * \brief contraction_type: an enum class representing the Tensor Contraction implementation algorithm. This is used to + * specialize the contraction algorithm based on device support for dedicated local memory. + */ +enum class contraction_type { local, no_local }; +/* ! + * \brief data_source an enum class determining the location of the data in a memory hierarchy (global, local, private). + */ +enum class data_source { global_mem, local_mem, private_mem }; + +/*! + * \brief read, a template function used for loading the data from global + memory. This function is used to guarantee coalesced and vectorized load whenever possible + * + * \tparam PacketLoad: determines if the each element of this tensor block should be loaded in a packet mode + * + * \param is_coalesced_layout: determines whether or not the Tensor data in a memory can be access coalesced and + vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the + contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case + when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed. + * + * \tparam PacketType: determines the type of packet + * + * \tparam TensorMapper: determines the input tensor mapper type + * + * \tparam StorageIndex: determines the Index type + + * \param tensorMapper: is the input tensor + * + * \param NCIndex: is the non-contracting dim index + * + * \param CIndex is the contracting dim index + * + * \param ld: is the leading dimension of the flattened tensor + */ +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t read( + const TensorMapper &tensorMapper, const StorageIndex &NCIndex, const StorageIndex &CIndex, const StorageIndex &ld) { + const StorageIndex row = (is_coalesced_layout) ? NCIndex : CIndex; + const StorageIndex col = (is_coalesced_layout) ? CIndex : NCIndex; + return tensorMapper.get_tensor().template packet(row + (col * ld)); +} + +/*! + * \brief read, special overload of read function, when the read access is not vectorized + * + * \tparam PacketLoad: determines if the each element of this tensor block should be loaded in a packet mode + * + * \param is_coalesced_layout: determines whether or not the Tensor data in a memory can be access coalesced and + vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the + contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case + when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed. + * + * \tparam PacketType: determines the type of packet + * + * \tparam TensorMapper: determines the input tensor mapper type + * + * \tparam StorageIndex: determines the Index type + + * \param tensorMapper: is the input tensor + * + * \param NCIndex: is the non-contracting dim index + * + * \param CIndex: is the contracting dim index + */ +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t read( + const TensorMapper &tensorMapper, const StorageIndex &NCIndex, const StorageIndex &CIndex, const StorageIndex &) { + const StorageIndex row = (IsRhs) ? CIndex : NCIndex; + const StorageIndex col = (IsRhs) ? NCIndex : CIndex; + return tensorMapper(row, col); +} + +/*! + * \brief write, a template function used for storing the data to local memory. This function is used to guarantee + * coalesced and vectorized store whenever possible. + * + * \tparam StorageIndex: determines the Index type + * + * \param ld is the leading dimension of the local memory. ld is a compile time value for the local memory + * + * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy. + * + * \tparam PacketType: determines the type of packet + * + * \tparam DataScalar: determines the output data type + * + * \param packet_data: the data to be written in the local memory + * + * \param ptr: a pointer to the local memory + * + * \param CIndex is the contracting dim index + */ + +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t
+ write(PacketType &packet_data, DataScalar ptr) { + EIGEN_CONSTEXPR int PacketSize = Eigen::internal::unpacket_traits::size; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; i++) { + *ptr = PacketWrapper::scalarize(i, packet_data); + ptr += ld; + } +} + +/*! + * \brief Overloading the write function for storing the data to global memory, when vectorization enabled This function + * is used to guarantee coalesced and vectorized store whenever possible. + * + * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy. + * + * \tparam PacketType: determines the type of packet + * + * \tparam DataScalar: determines the output data type + * + * \param packet_data: the data to be written in the local memory + * + * \param ptr: a pointer to the local memory + */ + +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if_t< + Eigen::internal::unpacket_traits::size != 1 && dt == data_source::global_mem, void> +write(PacketType &packet_data, DataScalar *ptr) { + ::Eigen::internal::pstoreu(ptr, packet_data); +} + +/*! + * \brief Overloading the write function for storing the data to global memory, when vectorization is disabled. + * + * \tparam data_source: an enum value representing if the location of the data in a memory hierarchy. + * + * \tparam PacketType: determines the type of packet + * + * \tparam DataScalar: determines the output data type + * + * \param packet_data: the data to be written in the local memory + * + * \param ptr: a pointer to the local memory + */ +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if_t< + Eigen::internal::unpacket_traits::size == 1 && dt == data_source::global_mem, void> +write(PacketType &packet_data, DataScalar *ptr) { + *ptr = packet_data; +} + +/*! + * \brief check_boundary: is used to check the edge condition for non-internal blocks. + * + * \tparam is_internal: determines if the block is internal + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_boundary(bool) { + return true; +} + +/*! + * \brief check_boundary: specialization of the check_boundary for non-internal blocks. + * + * \param cond: true when the data is in range. Otherwise false + */ +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool check_boundary(bool cond) { + return cond; +} + +/*! + * \brief BlockProperties is a template class that provides different characteristic of a block of each Tensor processed + * by each workgroup. + * + * \tparam is_transposed: iff true, determines whether or not the block of the Tensor is transposed + * + * \tparam packet_load_: determines if the each element of this tensor block should be loaded in a packet mode + * + * \tparam PacketType: determines the type of packet + * + * \tparam OutType: determines the type of each element for this block of tensor. If packet load is true, it will be + * packetType; Otherwise it will be scalar Type + * + * \param elements_per_access determines the size of each element based on OutType + * + * \param is_coalesced_layout determines whether or not the Tensor data in a memory can be access coalesced and + * vectorized when possible. Coalesced memory access is a key factor in Kernel performance. When a tensor is 2d and the + * contracting dimension is 1, it is always possible to accessed tensor data coalesced and vectorized. This is the case + * when RHS(right hand side) Tensor is transposed or when LHS(left hand side) Tensor is not transposed. + * + * \param nc_stride determines the stride of non-contracting dimension to access the next adjustment element within the + * Tensor Block for each workgroup + * + * \param c_stride determines the stride of contracting dimension to access the next adjustment element within the + * Tensor Block for each workgroup + */ +template +struct BlockProperties { + static EIGEN_CONSTEXPR bool packet_load = packet_load_; + typedef typename Eigen::internal::unpacket_traits::type OutScalar; + static EIGEN_CONSTEXPR bool is_rhs = is_rhs_; + typedef std::conditional_t OutType; + static EIGEN_CONSTEXPR int elements_per_access = Eigen::internal::unpacket_traits::size; + static EIGEN_CONSTEXPR bool is_coalesced_layout = !(is_transposed ^ is_rhs); + static EIGEN_CONSTEXPR int nc_stride = (is_coalesced_layout ? elements_per_access : 1); + static EIGEN_CONSTEXPR int c_stride = (is_coalesced_layout ? 1 : elements_per_access); +}; + +/*! + * \brief ThreadProperties is a template class that provides each thread's properties within a workgroup. Please see + * the sycl-1.2.1 specification (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for the workgroup, + * work-items + * + * \tparam StorageIndex: determines the StorageIndex Type + * + * \param linearLocalThreadId: determines the linearized location of a thread within a work-group + * + * \param kGroupId: determines the logical group id in a k dimension of the flattened tensor. It will be > 1 when + * tall/skinny algorithm is used + * + * \param mGroupOffset: determines the logical start position of all thread within a workgroup for the m dimension of + * the flattened tensor. + * + * \param kGroupOffset determines the logical start position of all thread within a workgroup for the k dimension of the + * flattened tensor. It will be > 1 when tall/skinny algorithm is used. + * + * \param mLocalOffset: determines the logical start position of each thread within a workgroup for the m dimension of a + * flattened tensor. The position determines the distance of each thread within the workgroup from each other + * independent from their global position. + * + * \param nLocalOffset: determines the logical start position of each thread within a workgroup for the n dimension of a + * flattened tensor. The position determines the distance of each thread within the workgroup from each other + * independent from their global position. + * + * \param mGlobalOffset: determines the logical start position of each thread a thread for the m dimension on a + * flattened tensor + * + * \param nGlobalOffset: determines the logical start position of each thread a thread for the n dimension on a + * flattened tensor + * + * \param kSize : determine the number of the k elements of the flattened Tensor to be processed by each thread for the + * given tensor block. This is !=K dimension of Flattened Tensor when Tall/Skinny matrix is used. + * + * \param is_internal : this will determined if the thread within the work-group computes an internal block of tensor or + * the edge blocks. When it is internal, there is no need to check the boundaries and all the if stantement can be + * resolve by compiler. + */ +template +struct ThreadProperties { + const StorageIndex linearLocalThreadId; + const StorageIndex kGroupId; + const StorageIndex mGroupOffset; + const StorageIndex nGroupOffset; + const StorageIndex kGroupOffset; + const StorageIndex mLocalOffset; + const StorageIndex nLocalOffset; + const StorageIndex mGlobalOffset; + const StorageIndex nGlobalOffset; + StorageIndex kSize; + const bool is_internal; + // this is used to adjust the last block + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ThreadProperties( + const StorageIndex linearLocalThreadId_, const StorageIndex kGroupId_, const StorageIndex mGroupOffset_, + const StorageIndex nGroupOffset_, const StorageIndex kGroupOffset_, const StorageIndex mLocalOffset_, + const StorageIndex nLocalOffset_, const StorageIndex mGlobalOffset_, const StorageIndex nGlobalOffset_, + StorageIndex kSize_, const bool is_internal_) + : linearLocalThreadId(linearLocalThreadId_), + kGroupId(kGroupId_), + mGroupOffset(mGroupOffset_), + nGroupOffset(nGroupOffset_), + kGroupOffset(kGroupOffset_), + mLocalOffset(mLocalOffset_), + nLocalOffset(nLocalOffset_), + mGlobalOffset(mGlobalOffset_), + nGlobalOffset(nGlobalOffset_), + kSize(kSize_), + is_internal(is_internal_) {} +}; + +/*! + * \brief TensorContractionKernel is a template class that provides Tensor -Tensor contraction operation. + * + * \tparam OutScalar: determines the output scalar type + * + * \tparam LhsScalar: determines the left-hand-side scalar type + * + * \tparam RhsScalar: determines the right-hand-side scalar type + * + * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification + (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition) + * + * \tparam LhsMapper determines the tensor contraction mapper type for left-hand-side matrix + * + * \tparam RhsMapper determines the tensor contraction mapper type for right-hand-side matrix + * + * \tparam StorageIndex: determines the StorageIndex Type + * + * \tparam Properties: determines the Contraction Panel properties + * + * \tparam TripleDim: determines the M, K, N dimensions for the flatten tensors in order to treat them as a matrix + * + * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression. + * + * \tparam input_mapper_properties : determine if the input tensors are matrix. If they are matrix, special memory + access is used to guarantee that always the memory access are coalesced. + * + * \tptaram IsFinal : determine if this is the final kernel. If so, the result will be written in a final output. + Otherwise, the result of contraction will be written iin a temporary buffer. This is the case when Tall/Skinny + contraction is used. So in this case, a final reduction step is required to compute final output. + + * \tparam contraction_tp: it is an enum value representing whether the local memory/no local memory implementation of + the algorithm to be used + * + * \param scratch: local memory containing tiles of LHS and RHS tensors for each work-group + * + * \param lhs: determines the left-hand-side flattened tensor (tensor mapper) + * + * \param rhs: determines the right-hand-side flattened tensor (tensor mapper) + * + * \param out_res: determines the output tensor containing the contraction result + * + * \param groupSizeM: a logical number determining the number of work-group for m dimension + * + * \param groupSizeN: a logical number determining the number of work-group for n dimension + * + * \param numTiles: determines total number of tiles on the k dimension + * + * \param TripleDim: determines the M, K, N dimensions for the flatten tensors in order to treat them as a matrix + */ +template +class TensorContractionKernel { + public: + typedef typename Eigen::TensorSycl::internal::Vectorise::PacketReturnType + PacketReturnType; + static EIGEN_CONSTEXPR int PacketSize = + Eigen::TensorSycl::internal::Vectorise::PacketSize; + static EIGEN_CONSTEXPR bool is_lhs_transposed = + !::Eigen::internal::TensorContractionInputMapperTrait::inner_dim_contiguous; + static EIGEN_CONSTEXPR bool is_rhs_transposed = + !::Eigen::internal::TensorContractionInputMapperTrait::inner_dim_contiguous; + + typedef BlockProperties + LHSBlockProperties; + + typedef BlockProperties + RHSBlockProperties; + + static EIGEN_CONSTEXPR StorageIndex NStride = + contraction_tp == contraction_type::local ? Properties::WorkLoadPerThreadN : RHSBlockProperties::nc_stride; + + typedef cl::sycl::accessor Scratch; + typedef cl::sycl::multi_ptr local_ptr; + typedef OutScalar * /*cl::sycl::multi_ptr*/ private_ptr; + typedef std::conditional_t + tile_ptr; + static EIGEN_CONSTEXPR StorageIndex LSDL = contraction_tp == contraction_type::local + ? Properties::TileSizeDimM + Properties::BC + : Properties::WorkLoadPerThreadM; + static EIGEN_CONSTEXPR StorageIndex LSDR = contraction_tp == contraction_type::local + ? Properties::TileSizeDimN + Properties::BC + : Properties::WorkLoadPerThreadN; + static EIGEN_CONSTEXPR StorageIndex LocalOffset = Properties::LocalThreadSizeM * Properties::LocalThreadSizeN; + + /** + * \brief MemHolder this is a place holder struct for creating memory hierarchy in SYCL. Inside SYCL kernel it is not + * allowed to have dynamic memory allocation. While the local memory is created outside of the kernel and passed to + * the kernel as an accessor, the private memory can only allowed to be allocated statically. Since we are abstracting + * the TiledMemory for both local and private memory, the MemHolder structs is used as a helper to abstract out + * different type of memory needed when local/no_local memory computation is called. + * + * \tparam contraction_type: it is an enum value representing whether the local memory/no local memory implementation + of the algorithm to be used + * \tparam the private memory size + * \param ptr the tile memory pointer type + */ + template + struct MemHolder { + tile_ptr ptr; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE MemHolder(local_ptr block_start_ptr) : ptr(block_start_ptr) {} + }; + /** + * \brief specialization of memHolder class when no local memory kernel is used. + */ + template + struct MemHolder { + OutScalar ptr[MemSize] = {OutScalar{0}}; + }; + /** + * \brief TiledMemory: contains required memory pointer for loading each tile of the TensorContraction panel from + * global memory to local/private memory when local/no_local algorithm used. + * + * \param lhs_scratch_extract : determines the LHS tile memory. It is either private or local memory based on the + * selected contraction_type. + * + * \param rhs_scratch_extract : determines the RHS tile memory. It is either private or local memory based on the + * selected contraction_type. + * + * \param lhs_extract_index: determines the position of each thread on a local memory for lhs input. When private + * memory is used this is set to zero as this is not applicable in case of private memory. + * + * \param rhs_extract_index: determines the position of each thread on a local memory for rhs input. When private + * memory is used this is set to zero as this is not applicable in case of private memory. + * + * \param lhs_scratch_compute : determines the location to load for computation for lhs_local memory. This is the + * same as lhs_scratch_extract for private memory. + * + * \param rhs_scratch_compute : determines the location to load for computation for rhs_local memory. This is the + * same as rhs_scratch_extract for private memory. + */ + struct TiledMemory { + MemHolder lhs_scratch_extract; + MemHolder rhs_scratch_extract; + tile_ptr lhs_scratch_ptr_compute; + tile_ptr rhs_scratch_ptr_compute; + const std::pair lhs_extract_index; + const std::pair rhs_extract_index; + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TiledMemory(const ThreadProperties &, local_ptr, + std::enable_if_t * = 0) + : lhs_scratch_extract{}, + rhs_scratch_extract{}, + lhs_scratch_ptr_compute(lhs_scratch_extract.ptr), + rhs_scratch_ptr_compute(rhs_scratch_extract.ptr), + lhs_extract_index(std::pair(StorageIndex{0}, StorageIndex{0})), + rhs_extract_index(std::pair(StorageIndex{0}, StorageIndex{0})) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TiledMemory(const ThreadProperties &thread_properties, local_ptr block_start_ptr, + std::enable_if_t * = 0) + : lhs_scratch_extract{block_start_ptr}, + rhs_scratch_extract{lhs_scratch_extract.ptr + + ((Properties::DoubleBuffer + 1) * LSDL * Properties::TileSizeDimK)}, + lhs_scratch_ptr_compute(lhs_scratch_extract.ptr + thread_properties.mLocalOffset), + rhs_scratch_ptr_compute(rhs_scratch_extract.ptr + thread_properties.nLocalOffset), + lhs_extract_index( + local_id_extract(thread_properties.linearLocalThreadId)), + rhs_extract_index( + local_id_extract(thread_properties.linearLocalThreadId)) {} + }; + + Scratch scratch; + const LhsMapper lhs; + const RhsMapper rhs; + OutAccessor out_res; + const StorageIndex groupSizeM; + const StorageIndex groupSizeN; + const StorageIndex numTiles; + const TripleDim triple_dim; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionKernel(Scratch scratch_, const LhsMapper lhs_, + const RhsMapper rhs_, OutAccessor out_res_, + const StorageIndex groupSizeM_, + const StorageIndex groupSizeN_, + const StorageIndex numTiles_, + const TripleDim triple_dim_) + : scratch(scratch_), + lhs(lhs_), + rhs(rhs_), + out_res(out_res_), + groupSizeM(groupSizeM_), + groupSizeN(groupSizeN_), + numTiles(numTiles_), + triple_dim(triple_dim_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorContractionKernel(Scratch scratch_, const LhsMapper lhs_, + const RhsMapper rhs_, OutAccessor out_res_, + const StorageIndex groupSizeM_, + const StorageIndex numTiles_, + const TripleDim triple_dim_) + : TensorContractionKernel(scratch_, lhs_, rhs_, out_res_, groupSizeM_, 1, numTiles_, triple_dim_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + const StorageIndex linearLocalThreadId = itemID.get_local_id(0); + const StorageIndex nLocalThreadId = linearLocalThreadId / Properties::LocalThreadSizeM; + const StorageIndex mLocalThreadId = linearLocalThreadId % Properties::LocalThreadSizeM; + const StorageIndex mGroupId = itemID.get_group(0) % groupSizeM; + const StorageIndex tmp = itemID.get_group(0) / groupSizeM; + const StorageIndex nGroupId = IsFinal ? tmp : tmp % groupSizeN; + const StorageIndex kGroupId = IsFinal ? 0 : tmp / groupSizeN; + const StorageIndex mGroupOffset = mGroupId * Properties::TileSizeDimM; + const StorageIndex nGroupOffset = nGroupId * Properties::TileSizeDimN; + const StorageIndex mLocalOffset = PacketSize * mLocalThreadId; + const StorageIndex nLocalOffset = NStride * nLocalThreadId; + const StorageIndex mGlobalOffset = mGroupOffset + mLocalOffset; + const StorageIndex nGlobalOffset = nGroupOffset + nLocalOffset; + + const StorageIndex kSizePerWG = IsFinal ? triple_dim.K : numTiles * Properties::TileSizeDimK; + StorageIndex kGroupOffset = kGroupId * kSizePerWG; + const bool is_internal = triple_dim.M - mGroupOffset >= Properties::TileSizeDimM && + triple_dim.N - nGroupOffset >= Properties::TileSizeDimN && + triple_dim.K - kGroupOffset >= kSizePerWG; + // this is used to adjust the last block + StorageIndex kSize = IsFinal ? triple_dim.K : std::min(kSizePerWG, triple_dim.K - kGroupOffset); + // This is used to find out the lats K offset so that kGroupOffset -kSize can compute the coffset for loading to + // tile + kGroupOffset += kSize; + + auto thread_properties = + ThreadProperties(linearLocalThreadId, kGroupId, mGroupOffset, nGroupOffset, kGroupOffset, + mLocalOffset, nLocalOffset, mGlobalOffset, nGlobalOffset, kSize, is_internal); + + auto out_ptr = out_res + (IsFinal ? 0 : thread_properties.kGroupId * triple_dim.M * triple_dim.N); + + (thread_properties.is_internal) ? compute_panel(itemID, thread_properties, out_ptr) + : compute_panel(itemID, thread_properties, out_ptr); + } + // The compute block computes the contraction operation private block for each thread and store the resutl in the + // privateRes memory of Each computation the compute block function is independent of local and no local concepts as + // it only compute the block on each thread's private memory space + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_block_per_tile(OutScalar *lhs_block_ptr, OutScalar *rhs_block_ptr, + PacketReturnType *privateRes) const { + StorageIndex idx = 0; + EIGEN_CONSTEXPR StorageIndex lhs_stride = + contraction_tp == contraction_type::local ? (PacketSize * Properties::LocalThreadSizeM) : 1; + EIGEN_UNROLL_LOOP + for (StorageIndex wLPTN = 0; wLPTN < Properties::WorkLoadPerThreadN; wLPTN++) { + auto rhsPacket = PacketReturnType{*(rhs_block_ptr + wLPTN)}; + StorageIndex lhs_index = 0; + EIGEN_UNROLL_LOOP + for (StorageIndex wLPTM = 0; wLPTM < Properties::WorkLoadPerThreadM / PacketSize; wLPTM++) { + PacketReturnType lhsPack{}; + Eigen::TensorSycl::internal::PacketWrapper::set_packet(lhsPack, + lhs_block_ptr + lhs_index); + privateRes[idx] = ::Eigen::internal::pmadd(lhsPack, rhsPacket, privateRes[idx]); + + lhs_index += lhs_stride; + idx++; + } + } + } + // The store function write the computed contraction operation in the private memory of each thread to the global + // memory. The store function is independent of local and no local concepts s that it can be abstract out in the base + // class. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void store(OutPtr *out_ptr, PacketReturnType *privateRes, + StorageIndex mGlobalOffset, StorageIndex nGlobalOffset) const { + auto chk_bound = [&](const StorageIndex &mIndex, const StorageIndex &nIndex) EIGEN_DEVICE_FUNC { + return (mIndex + PacketSize - 1 < triple_dim.M && nGlobalOffset + nIndex < triple_dim.N); + }; + // when local memory is not used M and N are both accessed in a coalesced way. However, when local memory is + // available the k*N is transposed in the local to N*K therefore, each blocks operates on blockId* + // WorkLoadPerThreadN slice of N + EIGEN_CONSTEXPR StorageIndex GlobalNStride = + contraction_tp == contraction_type::local ? 1 : Properties::LocalThreadSizeN; + EIGEN_UNROLL_LOOP + for (StorageIndex wLPTN = 0; wLPTN < Properties::WorkLoadPerThreadN / PrivateNStride; wLPTN++) { + // output leading dimension + StorageIndex outputLD = 0; + // When local memory is used the PrivateNstride is always 1 because the coalesed access on N is loaded into Local + // memory and extracting from local to global is the same as no transposed version. However, when local memory is + // not used and RHS is transposed we packetize the load for RHS. + EIGEN_UNROLL_LOOP + for (StorageIndex nId = 0; nId < PrivateNStride; nId++) { + StorageIndex globalRow = mGlobalOffset; + EIGEN_UNROLL_LOOP + for (StorageIndex wLPTM = 0; wLPTM < Properties::WorkLoadPerThreadM / PacketSize; wLPTM++) { + PacketReturnType privetOut = privateRes[wLPTM]; + if (check_boundary(chk_bound(globalRow, nId))) { + // Store the final results in C. The C matrix has always M as a first StorageIndex and N as a second + // StorageIndex Therefore it is always coalesced layout + write(privetOut, out_ptr + outputLD + globalRow); + } else { + EIGEN_UNROLL_LOOP + for (StorageIndex mId = 0; mId < PacketSize; mId++) { + StorageIndex mOffset = globalRow + mId; + if (mOffset < triple_dim.M && (nGlobalOffset + nId < triple_dim.N)) { + out_ptr[mOffset + outputLD] = + Eigen::TensorSycl::internal::PacketWrapper::scalarize(mId, privetOut); + } + } + } + globalRow += (PacketSize * Properties::LocalThreadSizeM); + } + outputLD += triple_dim.M; + privateRes += Properties::WorkLoadPerThreadM / PacketSize; + } + out_ptr += (GlobalNStride * outputLD); + + nGlobalOffset += (PrivateNStride * GlobalNStride); + } + } + // when no local memory is used the following extract_block will be enabled + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + extract_block(const Input &inpt, PrivateReg private_ptr, const std::pair &, + const StorageIndex &ncOffset, const StorageIndex cOffset) const { + EIGEN_CONSTEXPR StorageIndex LocalThreadSizeNC = + InputBlockProperties::is_rhs ? Properties::LocalThreadSizeN : Properties::LocalThreadSizeM; + EIGEN_CONSTEXPR StorageIndex WorkLoadPerThreadNC = + InputBlockProperties::is_rhs ? Properties::WorkLoadPerThreadN : Properties::WorkLoadPerThreadM; + const StorageIndex &NC = InputBlockProperties::is_rhs ? triple_dim.N : triple_dim.M; + + auto chk_bound = [&](const StorageIndex &CIndex, const StorageIndex &NCIndex) EIGEN_DEVICE_FUNC { + return ((CIndex + InputBlockProperties::c_stride - 1 < triple_dim.K) && + (NCIndex + InputBlockProperties::nc_stride - 1 < NC)); + }; + const StorageIndex ld = InputBlockProperties::is_coalesced_layout ? NC : triple_dim.K; + StorageIndex cIndex = cOffset; + + EIGEN_UNROLL_LOOP + for (StorageIndex cId = 0; cId < Properties::TileSizeDimK / InputBlockProperties::c_stride; cId++) { + StorageIndex ncIndex = ncOffset; + EIGEN_UNROLL_LOOP + for (StorageIndex ncId = 0; ncId < WorkLoadPerThreadNC / InputBlockProperties::nc_stride; ncId++) { + if (check_boundary(chk_bound(cIndex, ncIndex))) { + auto val = + read(inpt, ncIndex, cIndex, ld); + + write(val, private_ptr); + } else { + EIGEN_UNROLL_LOOP + for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) { + const StorageIndex ncInd = ncIndex + (InputBlockProperties::is_coalesced_layout ? i : 0); + const StorageIndex cInd = cIndex + (InputBlockProperties::is_coalesced_layout ? 0 : i); + OutScalar val = + (ncInd < NC && cInd < triple_dim.K) + ? read( + inpt, ncInd, cInd, ld) + : OutScalar(0); + write( + val, private_ptr + (InputBlockProperties::is_coalesced_layout ? i : 0) + + ((InputBlockProperties::is_coalesced_layout ? 0 : i) * WorkLoadPerThreadNC)); + } + } + + // if it is lhs we have to load it packetised when the packet size is > 1, because the output is coalesced. So + // even if M is not accessed in a coalesced mode, we have to load packet_size number of m per thread. + ncIndex = (!InputBlockProperties::is_rhs && InputBlockProperties::nc_stride == 1 && PacketSize != 1) + ? ncOffset + (ncId + 1) % PacketSize + ((ncId + 1) / PacketSize) * LocalThreadSizeNC + : (ncIndex + InputBlockProperties::nc_stride * LocalThreadSizeNC); + private_ptr += InputBlockProperties::nc_stride; + } + // the previous for loop ( private_ptr += (ncId * nc_stride)) has already moved ptr with one WorkLoadPerThreadNC + private_ptr += (InputBlockProperties::c_stride - 1) * WorkLoadPerThreadNC; + cIndex += InputBlockProperties::c_stride; + } + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::pair local_id_extract( + const StorageIndex &linearLocalThreadId) { + const StorageIndex localThreadNC = + (InputBlockProperties::is_coalesced_layout) + ? linearLocalThreadId % (TileSizeDimNC / InputBlockProperties::nc_stride) + : linearLocalThreadId / (Properties::TileSizeDimK / InputBlockProperties::c_stride); + const StorageIndex localThreadC = + (InputBlockProperties::is_coalesced_layout) + ? linearLocalThreadId / (TileSizeDimNC / InputBlockProperties::nc_stride) + : linearLocalThreadId % (Properties::TileSizeDimK / InputBlockProperties::c_stride); + return std::pair(localThreadNC, localThreadC); + } + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + sync_mem(const cl::sycl::nd_item<1> &, bool &db_offset) noexcept { + db_offset = !db_offset; + } + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + sync_mem(const cl::sycl::nd_item<1> &itemID, bool &) noexcept { + itemID.barrier(cl::sycl::access::fence_space::local_space); + } + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + sync_mem(const cl::sycl::nd_item<1> &, bool &) noexcept { + return; + } + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + sync_thread(const cl::sycl::nd_item<1> & +#ifdef EIGEN_SYCL_ARM_GPU_CACHE_OPTIMISATION + itemID +#endif + ) noexcept { +#ifdef EIGEN_SYCL_ARM_GPU_CACHE_OPTIMISATION + itemID.barrier(cl::sycl::access::fence_spacce::local_space); +#else + return; +#endif + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + sync_thread(const cl::sycl::nd_item<1> &itemID) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t sync_thread( + const cl::sycl::nd_item<1> &) { + return; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_tile_per_panel(const cl::sycl::nd_item<1> &itemID, + ThreadProperties &thread_properties, + TiledMemory &tiled_input_block, + PacketReturnType *privateRes, bool &db_offset) const { + + // Tiling the Rhs block from global to local memory + extract_block( + rhs, tiled_input_block.rhs_scratch_extract.ptr + (db_offset * Properties::TileSizeDimK * LSDR), + tiled_input_block.rhs_extract_index, + contraction_tp == contraction_type::local ? thread_properties.nGroupOffset : thread_properties.nGlobalOffset, + thread_properties.kGroupOffset - thread_properties.kSize); + + sync_thread(itemID); + + // Tiling the Lhs block from global to local memory + extract_block( + lhs, tiled_input_block.lhs_scratch_extract.ptr + (db_offset * LSDL * Properties::TileSizeDimK), + tiled_input_block.lhs_extract_index, + contraction_tp == contraction_type::local ? thread_properties.mGroupOffset : thread_properties.mGlobalOffset, + thread_properties.kGroupOffset - thread_properties.kSize); + + // itemID.barrier(cl::sycl::access::fence_space::local_space); + sync_thread(itemID); + // switch to compute mede + StorageIndex lhs_offset = (db_offset * LSDL * Properties::TileSizeDimK); + StorageIndex rhs_offset = (db_offset * Properties::TileSizeDimK * LSDR); + // Loop over the values of a single tile + for (StorageIndex k = 0; k < Properties::TileSizeDimK; k++) { + compute_block_per_tile(tiled_input_block.lhs_scratch_ptr_compute + lhs_offset, + tiled_input_block.rhs_scratch_ptr_compute + rhs_offset, privateRes); + lhs_offset += LSDL; + rhs_offset += LSDR; + } + // computing the K index for the next tile + thread_properties.kSize -= Properties::TileSizeDimK; + sync_mem(itemID, db_offset); + } + + // when local memory is available the following compute_panel will be enabled + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_panel(const cl::sycl::nd_item<1> &itemID, + ThreadProperties &thread_properties, + OutPtr out_ptr) const { + auto tiled_input_block = TiledMemory{thread_properties, scratch.get_pointer()}; + // Allocate register space + PacketReturnType privateRes[Properties::WorkLoadPerThreadM * Properties::WorkLoadPerThreadN / PacketSize] = { + PacketReturnType{0}}; + bool db_offset = 0; + + while (thread_properties.kSize >= Properties::TileSizeDimK) { + compute_tile_per_panel(itemID, thread_properties, tiled_input_block, privateRes, db_offset); + } + if (thread_properties.kSize > 0) { + compute_tile_per_panel(itemID, thread_properties, tiled_input_block, privateRes, db_offset); + } + + // Storing the final results in the output + store(1) : RHSBlockProperties::nc_stride>( + out_ptr + thread_properties.nGlobalOffset * triple_dim.M, privateRes, thread_properties.mGlobalOffset, + thread_properties.nGlobalOffset); + } + // When local memory is available the following extract_block will be enabled + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t + extract_block(const Input &inpt, Local local_ptr, const std::pair& local_index, + const StorageIndex &ncOffset, const StorageIndex cOffset) const { + EIGEN_CONSTEXPR StorageIndex TileSizeDimNC = + InputBlockProperties::is_rhs ? Properties::TileSizeDimN : Properties::TileSizeDimM; + EIGEN_CONSTEXPR StorageIndex LoadPerThread = + InputBlockProperties::is_rhs ? Properties::LoadPerThreadRhs : Properties::LoadPerThreadLhs; + EIGEN_CONSTEXPR StorageIndex LSD = InputBlockProperties::is_rhs ? LSDR : LSDL; + static_assert(((LocalOffset % (TileSizeDimNC / InputBlockProperties::nc_stride) == 0) && + (LocalOffset % (Properties::TileSizeDimK / InputBlockProperties::c_stride) == 0)), + " LocalOffset must be divisable by stride"); + const StorageIndex &NC = InputBlockProperties::is_rhs ? triple_dim.N : triple_dim.M; + StorageIndex localThreadNC = local_index.first; + StorageIndex localThreadC = local_index.second; + auto chk_bound = [&](const StorageIndex &CIndex, const StorageIndex &NCIndex) EIGEN_DEVICE_FUNC { + return ((CIndex + InputBlockProperties::c_stride - 1 < triple_dim.K) && + (NCIndex + InputBlockProperties::nc_stride - 1 < NC)); + }; + EIGEN_UNROLL_LOOP + for (StorageIndex lPT = 0; lPT < LoadPerThread / InputBlockProperties::elements_per_access; lPT++) { + const StorageIndex CIndex = cOffset + (InputBlockProperties::c_stride * localThreadC); + const StorageIndex NCIndex = ncOffset + (InputBlockProperties::nc_stride * localThreadNC); + const StorageIndex ld = InputBlockProperties::is_coalesced_layout ? NC : triple_dim.K; + if (check_boundary(chk_bound(CIndex, NCIndex))) { + auto val = + read(inpt, NCIndex, CIndex, ld); + write( + val, local_ptr + (InputBlockProperties::nc_stride * localThreadNC) + + (InputBlockProperties::c_stride * localThreadC * LSD)); + } else { + EIGEN_UNROLL_LOOP + for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) { + const StorageIndex nCInd = NCIndex + (InputBlockProperties::is_coalesced_layout ? i : 0); + const StorageIndex cInd = CIndex + (InputBlockProperties::is_coalesced_layout ? 0 : i); + OutScalar val = + (nCInd < NC && cInd < triple_dim.K) + ? read( + inpt, nCInd, cInd, ld) + : OutScalar(0); + + write( + val, local_ptr + (InputBlockProperties::nc_stride * localThreadNC) + + (InputBlockProperties::is_coalesced_layout ? i : 0) + + ((InputBlockProperties::c_stride * localThreadC + + (InputBlockProperties::is_coalesced_layout ? 0 : i)) * + LSD)); + } + } + localThreadNC += (InputBlockProperties::is_coalesced_layout) + ? LocalOffset % (TileSizeDimNC / InputBlockProperties::nc_stride) + : LocalOffset / (Properties::TileSizeDimK / InputBlockProperties::c_stride); + localThreadC += (InputBlockProperties::is_coalesced_layout) + ? LocalOffset / (TileSizeDimNC / InputBlockProperties::nc_stride) + : LocalOffset % (Properties::TileSizeDimK / InputBlockProperties::c_stride); + } + } +}; + +#ifndef EIGEN_SYCL_DISABLE_GEMV + +/*! + * \brief GeneralVectorTensor is a template class that provides Tensor -vector contraction operation, which is a special + * case of Tensor Tensor contraction. + * + * \tparam OutScalar: determines the output scalar type + * + * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification + * (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition) + * + * \tparam VectorMapper: determines the tensor contraction mapper for the vector input (can be lhs or rhs) + * + * \tparam TensorMapper: determines the tensor contraction mapper for the tensor input (can be lhs or rhs) + * + * \tparam StorageIndex: determines the StorageIndex Type + * + * \tparam Properties: determines the Contraction Panel properties + * + * \tparam KFactor: determines the number of elements in K dimension in a Tile + * + * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression. + * + * \tparam is_lhs_vec: determines whether lhs is a vector or rhs is a vector + * + * \tparam IsFinal: determine if this is the final kernel. If so, the result will be written in a final output. + * Otherwise, the result of contraction will be written iin a temporary buffer. + * + * \param scratch: determines the local memory containing the vector block for each work-group + * + * \param vec: determines the vector input (tensor mapper) + * + * \param mat: determines the tensor input (tensor mapper) + * + * \param out_res: determines the output vector containing the contraction result + * + * \param nonContractGroupSize: a logical number determining the number of work-group for non-contracting dimension + * + * \param nonContractDim: determines the size of non contracting dimension for the flattened tensor + * + * \param contractDim: determines the size of non contracting dimension for the flattened tensor + * + */ +template +struct GeneralVectorTensor { + typedef typename Eigen::TensorSycl::internal::Vectorise::PacketReturnType + PacketReturnType; + static EIGEN_CONSTEXPR int PacketSize = + Eigen::TensorSycl::internal::Vectorise::PacketSize; + typedef cl::sycl::accessor Scratch; + + static EIGEN_CONSTEXPR StorageIndex OutScratchOffset = + KFactor * Properties::LocalThreadSizeC * Properties::LocalThreadSizeNC; + + // Since the access layout for a vector can always be coalesced, when LHS is a vector, we pass false and false to make + // sure that the !^ is true When RHS is a vector, we pass true and true to make sure that the !^ is true. + typedef BlockProperties + VecBlockProperties; + + Scratch scratch; + const VectorMapper vec; + const TensorMapper mat; + OutAccessor out_res; + const StorageIndex nonContractGroupSize; + const StorageIndex nonContractDim; + const StorageIndex contractDim; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE GeneralVectorTensor(Scratch scratch_, const VectorMapper vec_, + const TensorMapper mat_, OutAccessor out_res_, + const StorageIndex nonContractGroupSize_, + const StorageIndex nonContractDim_, + const StorageIndex contractDim_) + : scratch(scratch_), + vec(vec_), + mat(mat_), + out_res(out_res_), + nonContractGroupSize(nonContractGroupSize_), + nonContractDim(nonContractDim_), + contractDim(contractDim_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + auto scratch_ptr = scratch.get_pointer(); + const StorageIndex linearLocalThreadId = itemID.get_local_id(0); + StorageIndex nonContractId = is_lhs_vec ? linearLocalThreadId / Properties::LocalThreadSizeC + : linearLocalThreadId % Properties::LocalThreadSizeNC; + StorageIndex contractId = is_lhs_vec ? linearLocalThreadId % Properties::LocalThreadSizeC + : linearLocalThreadId / Properties::LocalThreadSizeNC; + const StorageIndex cGroupSize = itemID.get_group_range(0) / nonContractGroupSize; + const StorageIndex nonContractGroupId = + is_lhs_vec ? itemID.get_group(0) / cGroupSize : itemID.get_group(0) % nonContractGroupSize; + const StorageIndex contractGroupId = + is_lhs_vec ? itemID.get_group(0) % cGroupSize : itemID.get_group(0) / nonContractGroupSize; + auto out_ptr = out_res + (IsFinal ? 0 : contractGroupId * nonContractDim); + + const StorageIndex nonContractGroupOffset = nonContractGroupId * Properties::TileSizeDimNC; + const StorageIndex contractGroupOffset = contractGroupId * Properties::TileSizeDimC; + auto outScratchIndex = nonContractId + contractId * Properties::LocalThreadSizeNC; + const StorageIndex globalNonContractDimOffset = nonContractGroupOffset + nonContractId; + const StorageIndex globalContractDimOffset = contractGroupOffset + contractId; + auto local_output = scratch_ptr + OutScratchOffset; + const bool is_internal = nonContractDim - nonContractGroupOffset >= Properties::TileSizeDimNC && + contractDim - contractGroupOffset >= Properties::TileSizeDimC; + is_internal + ? compute_panel(itemID, vec, mat, local_output, out_ptr, +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + scratch_ptr, contractGroupOffset, +#endif + nonContractGroupOffset, linearLocalThreadId, contractDim, nonContractDim, contractId, + nonContractId, globalContractDimOffset, globalNonContractDimOffset, outScratchIndex) + : compute_panel(itemID, vec, mat, local_output, out_ptr, +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + scratch_ptr, contractGroupOffset, +#endif + nonContractGroupOffset, linearLocalThreadId, contractDim, nonContractDim, contractId, + nonContractId, globalContractDimOffset, globalNonContractDimOffset, outScratchIndex); + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_panel( + const cl::sycl::nd_item<1> &itemID, const VectorMapper &vec, const TensorMapper &mat, OutScalar *local_output, + OutPtr out_ptr, +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + OutScalar *scratch_ptr, const StorageIndex contractGroupOffset, +#endif + const StorageIndex nonContractGroupOffset, const StorageIndex linearLocalThreadId, StorageIndex contractDim, + StorageIndex nonContractDim, StorageIndex contractId, StorageIndex nonContractId, + StorageIndex globalContractDimOffset, StorageIndex globalNonContractDimOffset, StorageIndex outScratchIndex) { + OutScalar outScalar[Properties::WorkLoadPerThreadNC] = {OutScalar(0)}; + // Reading the vector +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + const StorageIndex vectorOffset = contractGroupOffset + linearLocalThreadId; + extract_block(vec, scratch_ptr, linearLocalThreadId, + vectorOffset, contractDim); + + itemID.barrier(cl::sycl::access::fence_space::local_space); + auto in_scratch_ptr = scratch_ptr + contractId; +#endif + + StorageIndex privateOffsetC = 0; + EIGEN_UNROLL_LOOP + for (StorageIndex i = 0; i < Properties::WorkLoadPerThreadC; i++) { + StorageIndex privateOffsetNC = 0; + bool contract_conds = ((globalContractDimOffset + privateOffsetC) < contractDim); +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + auto vecScalar = *in_scratch_ptr; +#else + auto vecScalar = (check_boundary(contract_conds)) + ? vec(is_lhs_vec ? StorageIndex(0) : globalContractDimOffset + privateOffsetC, + is_lhs_vec ? globalContractDimOffset + privateOffsetC : StorageIndex(0)) + : OutScalar(0); +#endif + EIGEN_UNROLL_LOOP + for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) { + auto matScalar = (check_boundary( + contract_conds && ((globalNonContractDimOffset + privateOffsetNC) < nonContractDim))) + ? mat(is_lhs_vec ? globalContractDimOffset + privateOffsetC + : globalNonContractDimOffset + privateOffsetNC, + is_lhs_vec ? globalNonContractDimOffset + privateOffsetNC + : globalContractDimOffset + privateOffsetC) + : OutScalar(0); + + outScalar[j] = cl::sycl::mad(matScalar, vecScalar, outScalar[j]); + privateOffsetNC += Properties::LocalThreadSizeNC; + } + privateOffsetC += Properties::LocalThreadSizeC; +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + in_scratch_ptr += Properties::LocalThreadSizeC; +#endif + } + + auto out_scratch_ptr = local_output + outScratchIndex; + // Each block of 16*16 element in shared memory should reduce to 16*1 + EIGEN_UNROLL_LOOP + for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) { + *out_scratch_ptr = outScalar[j]; + + out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC); + } + if (is_lhs_vec) { + nonContractId = linearLocalThreadId % Properties::LocalThreadSizeNC; + contractId = linearLocalThreadId / Properties::LocalThreadSizeNC; + outScratchIndex = nonContractId + contractId * Properties::LocalThreadSizeNC; + } + + out_scratch_ptr = local_output + outScratchIndex; + EIGEN_UNROLL_LOOP + for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) { + EIGEN_UNROLL_LOOP + for (StorageIndex offset = Properties::LocalThreadSizeC >> 1; offset > 0; offset >>= 1) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (contractId < offset) { + StorageIndex myNeigbourId = (Properties::LocalThreadSizeNC * offset); + *out_scratch_ptr += out_scratch_ptr[myNeigbourId]; + } + } + // moving to next 16 by 16 block + out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC); + } + + if (contractId == 0) { + out_scratch_ptr = local_output + nonContractId; + StorageIndex global_final_offset = nonContractGroupOffset + nonContractId; + out_ptr += global_final_offset; + EIGEN_UNROLL_LOOP + for (StorageIndex j = 0; j < Properties::WorkLoadPerThreadNC; j++) { + if (check_boundary(global_final_offset < nonContractDim)) { + auto res = *out_scratch_ptr; + + *out_ptr = res; + out_ptr += Properties::LocalThreadSizeNC; + } + // moving to next 16 by 16 block to ge the next 16 reduced elements + out_scratch_ptr += (Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC); + if (!(is_internal_block)) global_final_offset += Properties::LocalThreadSizeNC; + } + } + } + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void extract_block(const Input &inpt, Local *local_ptr, + const StorageIndex &linearLocalThreadId, + const StorageIndex &cOffset, const StorageIndex &C) { + local_ptr += InputBlockProperties::c_stride * linearLocalThreadId; + StorageIndex cIndex = cOffset; + for (StorageIndex cId = 0; cId < CFactor / InputBlockProperties::c_stride; cId++) { + if (check_boundary(cIndex + InputBlockProperties::c_stride - 1 < C)) { + auto val = read(inpt, StorageIndex(0), + cIndex, StorageIndex(1)); + write(val, local_ptr); + } else { + EIGEN_UNROLL_LOOP + for (StorageIndex i = 0; i < InputBlockProperties::elements_per_access; i++) { + OutScalar val = + (cIndex + i < C) + ? read( + inpt, StorageIndex(0), cIndex + i, StorageIndex(1)) + : OutScalar(0); + write(val, local_ptr + i); + } + } + local_ptr += InputBlockProperties::c_stride * GroupSize; + cIndex += InputBlockProperties::c_stride * GroupSize; + } + } +}; +#endif + +#ifndef EIGEN_SYCL_DISABLE_SCALAR + +/*! + * \brief GeneralScalarContraction is a template class that provides the scalar value of Tensor -Tensor contraction + * operation, when all the dimensions are contracting dimensions. This Kernel reduces two tensors to an scalar + * + * \tparam OutScalar: determines the output scalar type + * + * \tparam LhsScalar: determines the left-hand-side scalar type + * + * \tparam RhsScalar: determines the right-hand-side scalar type + * + * \tparam OutAccessor: determines the sycl accessor type for out put (please see the sycl-1.2.1 specification + * (https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf) for accessor definition) + * + * \tparam LhsMapper: determines the tensor contraction mapper type for left-hand-side matrix + * + * \tparam RhsMapper: determines the tensor contraction mapper type for right-hand-side matrix + * + * \tparam StorageIndex: determines the StorageIndex Type + * + * \tparam Vectorizable: determines whether or not the vectorization is enabled for the Eigen expression. + * + * \param scratch: local memory containing tiles of LHS and RHS tensors for each work-group + * + * \param lhs: determines the left-hand-side flattened tensor (tensor mapper) + * + * \param rhs: determines the right-hand-side flattened tensor (tensor mapper) + * + * \param out_res: determines the output tensor containing the contraction result + * + * \param rng: determines the total input data size + */ +template +struct GeneralScalarContraction { + typedef cl::sycl::accessor Scratch; + Scratch scratch; + const LhsMapper lhs; + const RhsMapper rhs; + OutAccessor out_res; + const StorageIndex rng; + + EIGEN_DEVICE_FUNC + GeneralScalarContraction(Scratch scratch_, const LhsMapper lhs_, const RhsMapper rhs_, OutAccessor out_res_, + const StorageIndex rng_) + : scratch(scratch_), lhs(lhs_), rhs(rhs_), out_res(out_res_), rng(rng_) {} + + EIGEN_DEVICE_FUNC void operator()(cl::sycl::nd_item<1> itemID) const { + + auto out_ptr = out_res; + OutScalar * scratch_ptr = scratch.get_pointer(); + + StorageIndex globalid = itemID.get_global_id(0); + StorageIndex localid = itemID.get_local_id(0); + OutScalar accumulator = OutScalar(0); + for (StorageIndex i = globalid; i < rng; i += itemID.get_global_range(0)) { + accumulator = cl::sycl::mad(lhs(0, i), rhs(i, 0), accumulator); + } + auto out_scratch_ptr = scratch_ptr + localid; + *out_scratch_ptr = accumulator; + for (StorageIndex offset = itemID.get_local_range(0) >> 1; offset > 0; offset >>= 1) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (localid < offset) { + *out_scratch_ptr = (accumulator += out_scratch_ptr[offset]); + } + } + if (localid == 0) { + out_ptr[itemID.get_group(0)] = accumulator; + } + } +}; +#endif + +} // namespace internal +} // namespace TensorSycl + +template +struct TensorEvaluator, + Eigen::SyclDevice> + : public TensorContractionEvaluatorBase, Eigen::SyclDevice>> { + static_assert(std::is_same::value, + "SYCL tensor contraction does not support output kernels."); + + typedef Eigen::SyclDevice Device; + + typedef TensorEvaluator, Device> Self; + typedef TensorContractionEvaluatorBase Base; + typedef TensorContractionOp XprType; + typedef std::remove_const_t Scalar; + typedef typename XprType::Index StorageIndex; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename Base::Storage Storage; + typedef typename Base::EvaluatorPointerType EvaluatorPointerType; + struct TripleDim { + const StorageIndex M; + const StorageIndex N; + const StorageIndex K; + TripleDim(const StorageIndex M_, const StorageIndex N_, const StorageIndex K_) : M(M_), N(N_), K(K_) {} + }; + enum { + PacketAccess = (PacketType::size > 1), + BlockAccess = false, + }; + + static constexpr int Layout = TensorEvaluator::Layout; + static constexpr int LDims = Base::LDims; + static constexpr int RDims = Base::RDims; + static constexpr int ContractDims = Base::ContractDims; + + typedef array left_dim_mapper_t; + typedef array right_dim_mapper_t; + + typedef array contract_t; + typedef array left_nocontract_t; + typedef array right_nocontract_t; + + static constexpr int NumDims = LDims + RDims - 2 * ContractDims; + + typedef DSizes Dimensions; + + typedef TensorEvaluator LeftEvaluator; + typedef TensorEvaluator RightEvaluator; + typedef std::remove_const_t LhsScalar; + typedef std::remove_const_t RhsScalar; + + typedef typename LeftEvaluator::Dimensions LeftDimensions; + typedef typename RightEvaluator::Dimensions RightDimensions; + + template + struct input_mapper_propertis { + static EIGEN_CONSTEXPR bool is_lhs_matrix = (LDims == 2 && ContractDims == 1) || lhs_inner_dim_contiguous; + static EIGEN_CONSTEXPR bool is_rhs_matrix = + (RDims == 2 && ContractDims == 1) || (rhs_inner_dim_contiguous && !rhs_inner_dim_reordered); + }; + + TensorEvaluator(const XprType &op, const Device &device) : Base(op, device) {} + + // We need to redefine this method to make nvcc happy + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(typename Base::EvaluatorPointerType data) { + this->m_leftImpl.evalSubExprsIfNeeded(NULL); + this->m_rightImpl.evalSubExprsIfNeeded(NULL); + if (!data) { + this->m_result = this->m_device.get( + static_cast(this->m_device.allocate_temp(this->dimensions().TotalSize() * sizeof(Scalar)))); + data = this->m_result; + } + evalToSycl(data); + return (this->m_result != NULL); + } + const Eigen::SyclDevice &device() const { return this->m_device; } + void evalToSycl(typename Base::EvaluatorPointerType buffer) const { + if (this->m_lhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } else { + evalTyped(buffer); + } + } else { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } else { + evalTyped(buffer); + } + } + } else { + if (this->m_rhs_inner_dim_contiguous) { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } else { + evalTyped(buffer); + } + } else { + if (this->m_rhs_inner_dim_reordered) { + evalTyped(buffer); + } else { + evalTyped(buffer); + } + } + } + } + + template + void evalTyped(typename Base::EvaluatorPointerType buffer) const { + const auto triple_dim = TripleDim{this->m_i_size, this->m_j_size, this->m_k_size}; + typedef internal::TensorContractionInputMapper< + LhsScalar, StorageIndex, internal::Lhs, LeftEvaluator, left_nocontract_t, contract_t, + PacketType::size, lhs_inner_dim_contiguous, false, Unaligned, MakePointer> + LhsMapper; + + typedef internal::TensorContractionInputMapper::size, rhs_inner_dim_contiguous, + rhs_inner_dim_reordered, Unaligned, MakePointer> + RhsMapper; + + // initialize data mappers + LhsMapper lhs(this->m_leftImpl, this->m_left_nocontract_strides, this->m_i_strides, + this->m_left_contracting_strides, this->m_k_strides); + + RhsMapper rhs(this->m_rightImpl, this->m_right_nocontract_strides, this->m_j_strides, + this->m_right_contracting_strides, this->m_k_strides); + +#ifndef EIGEN_SYCL_DISABLE_SCALAR + if (triple_dim.M == 1 && triple_dim.N == 1) { + launchSC(buffer, lhs, rhs, triple_dim.K); + } else +#endif +#ifndef EIGEN_SYCL_DISABLE_GEMV + if (triple_dim.M != 1 && triple_dim.N == 1) { + LaunchVT(buffer, rhs, lhs, triple_dim.M, triple_dim.K); + } else if (triple_dim.M == 1 && triple_dim.N != 1) { + LaunchVT(buffer, lhs, rhs, triple_dim.N, triple_dim.K); + } else // This is equivalent of if (m!=1 && n!=1) +#endif + { + typedef input_mapper_propertis + inpt_mapper_properties; +#ifndef EIGEN_SYCL_DISABLE_SKINNY + bool skinny = false; + auto platform_name = this->device().getPlatformName(); + // This is based on empirical calculation for AMD r9-nano and Fiji + if (platform_name.find("AMD") == 0) { + skinny = (triple_dim.M < triple_dim.K || triple_dim.N < triple_dim.K) && + ((triple_dim.M < 1024 && triple_dim.N < 1024) || + (uint64_t(triple_dim.M * triple_dim.N) < uint64_t(triple_dim.K))); + } else { + skinny = (((std::max(triple_dim.K, triple_dim.N) / std::min(triple_dim.K, triple_dim.N)) > 100) || + ((std::max(triple_dim.K, triple_dim.M) / std::min(triple_dim.K, triple_dim.M)) > 100) || + ((std::max(triple_dim.N, triple_dim.M) / std::min(triple_dim.N, triple_dim.M)) > 100)); + } + if (skinny) + adjustTT(buffer, lhs, rhs, triple_dim); + else +#endif // EIGEN_SYCL_DISABLE_SKINNY + adjustTT(buffer, lhs, rhs, triple_dim); + } + } + + template + void EIGEN_ALWAYS_INLINE adjustTT(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs, + const TripleDim &triple_dim) const { +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON + if (device().has_local_memory()) { + typedef TensorSycl::internal::TTPanelSize PanelParameters; + launchTT( + buffer, lhs, rhs, triple_dim); + } +#endif +#ifdef EIGEN_SYCL_LOCAL_MEM_UNSET_OR_OFF + if (!(device().has_local_memory())) { + typedef TensorSycl::internal::TTPanelSize PanelParameters; + launchTT( + buffer, lhs, rhs, triple_dim); + } +#endif + } + + template + void launchTT(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs, + const TripleDim &triple_dim) const { + const StorageIndex roundUpM = Eigen::TensorSycl::internal::roundUp(triple_dim.M, Properties::TileSizeDimM); + const StorageIndex roundUpN = Eigen::TensorSycl::internal::roundUp(triple_dim.N, Properties::TileSizeDimN); + const StorageIndex groupSizeM = roundUpM / Properties::TileSizeDimM; + const StorageIndex groupSizeN = roundUpN / Properties::TileSizeDimN; + + const StorageIndex roundUpK = Eigen::TensorSycl::internal::roundUp(triple_dim.K, Properties::TileSizeDimK); + StorageIndex totalTilesK = roundUpK / Properties::TileSizeDimK; + StorageIndex groupSizeK = + skinny + ? std::max(std::min(totalTilesK, + (StorageIndex)(device().getPowerOfTwo(device().getNumSyclMultiProcessors(), true) * 4) / + (groupSizeM * groupSizeN)), + StorageIndex(1)) + : StorageIndex(1); + + const StorageIndex numTilesPerGroup = Eigen::TensorSycl::internal::roundUp(totalTilesK, groupSizeK) / groupSizeK; + + const StorageIndex totalGroupSize = groupSizeM * groupSizeN * groupSizeK; + + const StorageIndex localRange = Properties::LocalThreadSizeM * Properties::LocalThreadSizeN; + const StorageIndex globalRange = totalGroupSize * localRange; + + const StorageIndex scratchSize = (ct == TensorSycl::internal::contraction_type::local) + ? ((Properties::DoubleBuffer + 1) * + (Properties::TileSizeDimM + Properties::BC) * (Properties::TileSizeDimK)) + + ((Properties::DoubleBuffer + 1) * (Properties::TileSizeDimK) * + (Properties::TileSizeDimN + Properties::BC)) + : StorageIndex(1); + + auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(globalRange), cl::sycl::range<1>(localRange)); + if (groupSizeK == 1) { + typedef TensorSycl::internal::TensorContractionKernel + ContractKernelName; + device().template binary_kernel_launcher( + lhs, rhs, buffer, thread_range, scratchSize, groupSizeM, groupSizeN, numTilesPerGroup, triple_dim).wait(); + } else { + typedef TensorSycl::internal::TensorContractionKernel + ContractKernelName; + CoeffReturnType *temp_pointer = static_cast( + device().allocate_temp(triple_dim.M * triple_dim.N * groupSizeK * sizeof(CoeffReturnType))); + EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer); + + device().template binary_kernel_launcher( + lhs, rhs, tmp_global_accessor, thread_range, scratchSize, groupSizeM, groupSizeN, numTilesPerGroup, + triple_dim).wait(); + + typedef Eigen::internal::SumReducer Op; + auto op = Op(); + typedef TensorSycl::internal::SecondStepPartialReduction + ReductionKernel; + + device().template unary_kernel_launcher( + tmp_global_accessor, buffer, + cl::sycl::nd_range<1>(cl::sycl::range<1>(StorageIndex( + Eigen::TensorSycl::internal::roundUp(triple_dim.M * triple_dim.N, localRange))), + cl::sycl::range<1>(localRange)), + StorageIndex(1), op, StorageIndex(triple_dim.M * triple_dim.N), groupSizeK).wait(); + device().deallocate_temp(temp_pointer); + } + } + +#ifndef EIGEN_SYCL_DISABLE_GEMV + template + void EIGEN_ALWAYS_INLINE LaunchVT(EvaluatorPointerType buffer, const VectorMapper &vec, const TensorMapper &mat, + StorageIndex NC, StorageIndex C) const { + const StorageIndex nonContractDim = NC; + EIGEN_CONSTEXPR StorageIndex NCFactor = 1; + EIGEN_CONSTEXPR StorageIndex CFactor = 1; + EIGEN_CONSTEXPR StorageIndex NCWindow = 16; + typedef Eigen::TensorSycl::internal::TVPanelSize + Properties; + const StorageIndex roundUpC = Eigen::TensorSycl::internal::roundUp(C, Properties::TileSizeDimC); + const StorageIndex cNumGroups = roundUpC / (Properties::LocalThreadSizeC * Properties::WorkLoadPerThreadC); + const StorageIndex roundUpNC = Eigen::TensorSycl::internal::roundUp(nonContractDim, Properties::TileSizeDimNC); + const StorageIndex nCNumGroups = roundUpNC / (Properties::LocalThreadSizeNC * Properties::WorkLoadPerThreadNC); + const StorageIndex globalRange = + (roundUpNC / (Properties::WorkLoadPerThreadNC)) * (roundUpC / (Properties::WorkLoadPerThreadC)); + const StorageIndex localRange = Properties::LocalThreadSizeNC * Properties::LocalThreadSizeC; + const StorageIndex scratchSize = + (Properties::WorkLoadPerThreadNC + CFactor) * Properties::LocalThreadSizeC * Properties::LocalThreadSizeNC; + auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(globalRange), cl::sycl::range<1>(localRange)); + if (cNumGroups > 1) { + typedef Eigen::TensorSycl::internal::GeneralVectorTensor + ContractKernelName; + CoeffReturnType *temp_pointer = + static_cast(device().allocate_temp(nonContractDim * cNumGroups * sizeof(CoeffReturnType))); + EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer); + + device().template binary_kernel_launcher( + vec, mat, tmp_global_accessor, thread_range, scratchSize, nCNumGroups, nonContractDim, C).wait(); + + typedef Eigen::internal::SumReducer Op; + typedef TensorSycl::internal::SecondStepPartialReduction + ReductionKernel; + + device().template unary_kernel_launcher( + tmp_global_accessor, buffer, + cl::sycl::nd_range<1>(cl::sycl::range<1>(Eigen::TensorSycl::internal::roundUp(nonContractDim, localRange)), + cl::sycl::range<1>(localRange)), + StorageIndex(1), Op(), nonContractDim, cNumGroups).wait(); + device().deallocate_temp(temp_pointer); + } else { + typedef Eigen::TensorSycl::internal::GeneralVectorTensor + ContractKernelName; + device().template binary_kernel_launcher( + vec, mat, buffer, thread_range, scratchSize, nCNumGroups, nonContractDim, C).wait(); + + } + } +#endif + +#ifndef EIGEN_SYCL_DISABLE_SCALAR + template + EIGEN_ALWAYS_INLINE void launchSC(EvaluatorPointerType buffer, const LhsMapper &lhs, const RhsMapper &rhs, + StorageIndex K) const { + EIGEN_STATIC_ASSERT(!((EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1) & + (EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1 - 1)), + "The Local thread size must be a power of 2 for the reduction " + "operation"); + EIGEN_CONSTEXPR StorageIndex local_range = EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1; + + // Here we force the code not to be more than 2-step reduction: Our empirical research shows that if each thread + // reduces at least 512 elementss individually, we get better performance. + const StorageIndex num_work_group = ((K + (512 * local_range - 1)) / (512 * local_range) > 1 ? local_range : 1); + const StorageIndex global_range = num_work_group * local_range; + + typedef Eigen::TensorSycl::internal::GeneralScalarContraction< + CoeffReturnType, LhsScalar, RhsScalar, EvaluatorPointerType, LhsMapper, RhsMapper, StorageIndex, false> + ContractKernelName; + auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(global_range), cl::sycl::range<1>(local_range)); + if (num_work_group > 1) { + CoeffReturnType *temp_pointer = + static_cast(device().allocate_temp(num_work_group * sizeof(CoeffReturnType))); + EvaluatorPointerType tmp_global_accessor = device().get(temp_pointer); + device().template binary_kernel_launcher(lhs, rhs, tmp_global_accessor, + thread_range, local_range, K).wait(); + typedef Eigen::internal::SumReducer Op; + typedef TensorSycl::internal::SecondStepFullReducer + GenericRKernel; + device().template unary_kernel_launcher( + tmp_global_accessor, buffer, + cl::sycl::nd_range<1>(cl::sycl::range<1>(local_range), cl::sycl::range<1>(local_range)), local_range, Op()).wait(); + device().deallocate_temp(temp_pointer); + } else { + device().template binary_kernel_launcher(lhs, rhs, buffer, thread_range, + local_range, K).wait(); + } + } +#endif + + EIGEN_STRONG_INLINE void cleanup() { + this->m_leftImpl.cleanup(); + this->m_rightImpl.cleanup(); + + if (this->m_result) { + this->m_device.deallocate_temp(this->m_result); + this->m_result = NULL; + } + } +}; +} // namespace Eigen +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_SYCL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h new file mode 100644 index 0000000000000000000000000000000000000000..19f664cad2ad11b7b7237c5c984e92ba6ef39ef3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h @@ -0,0 +1,1679 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H + +// evaluator for thread pool device +#ifdef EIGEN_USE_THREADS + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template +struct TensorEvaluator, ThreadPoolDevice> : + public TensorContractionEvaluatorBase, ThreadPoolDevice> > { + + typedef ThreadPoolDevice Device; + + typedef TensorEvaluator, Device> Self; + typedef TensorContractionEvaluatorBase Base; + + typedef TensorContractionOp XprType; + typedef std::remove_const_t Scalar; + typedef typename XprType::Index Index; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + static constexpr int Layout = TensorEvaluator::Layout; + + // Most of the code is assuming that both input tensors are ColMajor. If the + // inputs are RowMajor, we will "cheat" by swapping the LHS and RHS: + // If we want to compute A * B = C, where A is LHS and B is RHS, the code + // will pretend B is LHS and A is RHS. + typedef std::conditional_t< + static_cast(Layout) == static_cast(ColMajor), LeftArgType, RightArgType> EvalLeftArgType; + typedef std::conditional_t< + static_cast(Layout) == static_cast(ColMajor), RightArgType, LeftArgType> EvalRightArgType; + + static constexpr int LDims = + internal::array_size::Dimensions>::value; + static constexpr int RDims = + internal::array_size::Dimensions>::value; + static constexpr int ContractDims = internal::array_size::value; + + typedef array left_dim_mapper_t; + typedef array right_dim_mapper_t; + + typedef array contract_t; + typedef array left_nocontract_t; + typedef array right_nocontract_t; + + static constexpr int NumDims = LDims + RDims - 2 * ContractDims; + + typedef DSizes Dimensions; + + // typedefs needed in evalTo + typedef std::remove_const_t LhsScalar; + typedef std::remove_const_t RhsScalar; + typedef typename internal::gebp_traits Traits; + + typedef TensorEvaluator LeftEvaluator; + typedef TensorEvaluator RightEvaluator; + + TensorEvaluator(const XprType& op, const Device& device) : + Base(op, device) {} + + template + void evalProduct(Scalar* buffer) const { + evalProductImpl(buffer, NoCallback()); + } + + template + void evalProductAsync(Scalar* buffer, EvalToCallback done) const { + evalProductImpl(buffer, std::move(done)); + } + + template + void evalProductImpl(Scalar* buffer, DoneCallback done) const { + // This function computes a lot of heuristics in multiple steps, and it + // also has multiple exit points. To keep it sane, readable and all in one + // place, sync/async execution decision is made at runtime at the very end. + // + // (1) In sync mode we allocate Context on the stack, submit computations + // to the device thread pool, and block on a barrier until it is + // completed. + // + // (2) In async mode we allocate Context on the heap, and after all tasks + // are finished, we call provided the done callback, and delete a + // context from the heap. + // + // (*) EvalParallelContext & EvalShardedByInnerDimContext owns all the state + // and temporary buffers, required for executing the tensor contraction. + // They are responsible for cleaning it up after contraction is done. + static const bool IsEvalInSyncMode = + std::is_same::value; + + const Index m = this->m_i_size; + const Index n = this->m_j_size; + const Index k = this->m_k_size; + if (m == 0 || n == 0 || k == 0) return; + + // Compute a set of algorithm parameters: + // - kernel block sizes (bm, bn, bk) + // - task grain sizes (number of kernels executed per task: gm, gn) + // - number of threads + // - sharding by row/column + // - parallel packing or first lhs then rhs + // and some derived parameters: + // - number of tasks (nm, nn, nk) + // - number of kernels (nm0, nn0) + // Unfortunately, all these parameters are tightly interdependent. + // So in some cases we first compute approximate values, then compute other + // values based on these approximations and then refine the approximations. + + // There are lots of heuristics here. There is some reasoning behind them, + // but ultimately they are just tuned on contraction benchmarks for + // different input configurations, thread counts and instruction sets. + // So feel free to question any of them. + + // Compute whether we want to shard by row or by column. + // This is a first approximation, it will be refined later. Since we don't + // know number of threads yet we use 2, because what's we are most + // interested in at this point is whether it makes sense to use + // parallelization at all or not. + bool shard_by_col = shardByCol(m, n, 2); + + // First approximation of kernel blocking sizes. + // Again, we don't know number of threads yet, so we use 2. + Index bm, bn, bk; + if (shard_by_col) { + internal::TensorContractionBlocking + blocking(k, m, n, 2); + bm = blocking.mc(); + bn = blocking.nc(); + bk = blocking.kc(); + } else { + internal::TensorContractionBlocking + blocking(k, m, n, 2); + bm = blocking.mc(); + bn = blocking.nc(); + bk = blocking.kc(); + } + + // Compute optimal number of threads. + // Note: we use bk instead of k here because we are interested in amount of + // _parallelizable_ computations, and computations are not parallelizable + // across k dimension. + const TensorOpCost cost = + contractionCost(m, n, bm, bn, bk, shard_by_col, false); + int num_threads = TensorCostModel::numThreads( + static_cast(n) * m, cost, this->m_device.numThreads()); + int num_threads_by_k = numThreadsInnerDim(m, n, k); + if (shardByInnerDim(m, n, k, num_threads, num_threads_by_k)) { + // We are in the scenario where it is more effective to shard by the + // inner dimension. + if (IsEvalInSyncMode) { + EvalShardedByInnerDimContext ctx( + this, num_threads_by_k, buffer, m, n, k, std::move(done)); + ctx.template run(); + } else { + auto* ctx = new EvalShardedByInnerDimContext( + this, num_threads_by_k, buffer, m, n, k, std::move(done)); + ctx->template runAsync(); + } + + return; + } + + // TODO(dvyukov): this is a stop-gap to prevent regressions while the cost + // model is not tuned. Remove this when the cost model is tuned. + if (n == 1) num_threads = 1; + + if (num_threads == 1) { + TENSOR_CONTRACTION_DISPATCH(this->template evalProductSequential, + Unaligned, (buffer)); + if (!IsEvalInSyncMode) done(); + return; + } + + // Now that we know number of threads, recalculate sharding and blocking. + shard_by_col = shardByCol(m, n, num_threads); + if (shard_by_col) { + internal::TensorContractionBlocking + blocking(k, m, n, num_threads); + bm = blocking.mc(); + bn = blocking.nc(); + bk = blocking.kc(); + } else { + internal::TensorContractionBlocking + blocking(k, m, n, num_threads); + bm = blocking.mc(); + bn = blocking.nc(); + bk = blocking.kc(); + } + + // Number of kernels for each dimension. + Index nm0 = divup(m, bm); + Index nn0 = divup(n, bn); + Index nk = divup(k, bk); + + // Calculate task grain size (number of kernels executed per task). + // This task size coarsening serves two purposes: + // 1. It reduces per-task overheads including synchronization overheads. + // 2. It allows to use caches better (reuse the same packed rhs in several + // consecutive kernels). + Index gm = 1; + Index gn = 1; + // If we are sharding by column, then we prefer to reduce rows first. + if (shard_by_col) { + gm = coarsenM(m, n, bm, bn, bk, gn, num_threads, shard_by_col); + gn = coarsenN(m, n, bm, bn, bk, gm, num_threads, shard_by_col); + } else { + gn = coarsenN(m, n, bm, bn, bk, gm, num_threads, shard_by_col); + gm = coarsenM(m, n, bm, bn, bk, gn, num_threads, shard_by_col); + } + // Number of tasks in each dimension. + Index nm = divup(nm0, gm); + Index nn = divup(nn0, gn); + + // If there is enough concurrency in the sharding dimension, we choose not + // to paralellize by the other dimension, and execute all kernels in sync + // mode. This reduces parallelism from the nm x nn down to nn + // (shard_by_col==true) or nm (shard_by_col==false). + const Index sharding_dim_tasks = shard_by_col ? nn : nm; + const int num_worker_threads = this->m_device.numThreadsInPool(); + + // With small number of threads we want to make sure that we do not reduce + // parallelism too much. With large number of threads we trade maximum + // parallelism for better memory locality. + const float oversharding_factor = + num_worker_threads <= 4 ? 8.0 : + num_worker_threads <= 8 ? 4.0 : + num_worker_threads <= 16 ? 2.0 : + num_worker_threads <= 32 ? 1.0 : + num_worker_threads <= 64 ? 0.8 : /* num_worker_threads > 64 */ 0.6; + + const bool parallelize_by_sharding_dim_only = + sharding_dim_tasks >= oversharding_factor * num_worker_threads; + + // Last by not least, decide whether we want to issue both lhs and rhs + // packing in parallel; or issue lhs packing first, and then issue rhs + // packing when lhs packing completes (for !shard_by_col lhs and rhs are + // swapped). Parallel packing allows more parallelism (for both packing and + // kernels), while sequential packing provides better locality (once + // a thread finishes rhs packing it proceed to kernels with that rhs). + // First, we are interested in parallel packing if there are few tasks. + bool parallel_pack = num_threads >= nm * nn; + // Also do parallel packing if all data fits into L2$. + if (m * bk * Index(sizeof(LhsScalar)) + n * bk * Index(sizeof(RhsScalar)) <= + l2CacheSize() * num_threads) + parallel_pack = true; + // But don't do it if we will use each rhs only once. Locality seems to be + // more important in this case. + if ((shard_by_col ? nm : nn) == 1) parallel_pack = false; + // Also don't get in the way of parallelize_by_sharding_dim_only + // optimization. + if (parallelize_by_sharding_dim_only) parallel_pack = false; + + // TODO(ezhulnev): With if contexpr we don't need SyncEvalParallelContext. + if (IsEvalInSyncMode) { +#define CONTEXT_ARGS \ + (this, num_threads, buffer, m, n, k, bm, bn, bk, nm, nn, nk, gm, gn, nm0, \ + nn0, shard_by_col, parallel_pack, parallelize_by_sharding_dim_only, \ + NoCallback()) \ + .run() + TENSOR_CONTRACTION_DISPATCH(SyncEvalParallelContext, Alignment, + CONTEXT_ARGS); +#undef CONTEXT_ARGS + + } else { +#define CONTEXT_ARGS \ + (this, num_threads, buffer, m, n, k, bm, bn, bk, nm, nn, nk, gm, gn, nm0, \ + nn0, shard_by_col, parallel_pack, parallelize_by_sharding_dim_only, \ + std::move(done)) + TENSOR_CONTRACTION_ASYNC_DISPATCH(EvalParallelContext, DoneCallback, + Alignment, CONTEXT_ARGS, run()); +#undef CONTEXT_ARGS + } + } + + // ------------------------------------------------------------------------ // + + // Dummy struct to represent an empty DoneCallback. + + struct NoCallback { + void operator()() { + eigen_assert(false && "NoCallback should never be called"); + } + }; + + // ------------------------------------------------------------------------ // + + template + class EvalParallelNotification; + + // Synchronous evaluation notification that blocks caller thread in Wait(). + template + class EvalParallelNotification { + public: + EvalParallelNotification(Context*, NoCallback) {} + void Notify() { done_.Notify(); } + void Wait() { done_.Wait(); } + private: + Eigen::Notification done_; + }; + + // Asynchronous evaluation notification that does not block in Wait(). + template + class EvalParallelNotification { + public: + EvalParallelNotification(Context* ctx, DoneCallback done) + : ctx_(ctx), done_(std::move(done)) {} + + void Notify() { + // Make a copy of done callback, because it will be destructed when we + // will delete context in the next line (EvalParallelNotification is a + // data member of EvalParallelContext class). + DoneCallback done_copy = std::move(done_); + + // Delete parallel evaluation context. + delete ctx_; + + // Now safely call the done callback. + done_copy(); + } + + void Wait() {} + + private: + Context* ctx_; + DoneCallback done_; + }; + + // Context orchestrates sync/async parallel contraction evaluation. When it is + // executed in asynchronous mode, it owns all the shared state that might be + // accessible by block packing and kernel tasks. + + template + class EvalParallelContext { + public: + typedef internal::TensorContractionInputMapper< + LhsScalar, Index, internal::Lhs, LeftEvaluator, left_nocontract_t, + contract_t, internal::packet_traits::size, + lhs_inner_dim_contiguous, false, Unaligned> + LhsMapper; + typedef internal::TensorContractionInputMapper< + RhsScalar, Index, internal::Rhs, RightEvaluator, right_nocontract_t, + contract_t, internal::packet_traits::size, + rhs_inner_dim_contiguous, rhs_inner_dim_reordered, Unaligned> + RhsMapper; + + typedef internal::blas_data_mapper OutputMapper; + + typedef internal::TensorContractionKernel< + Scalar, LhsScalar, RhsScalar, Index, OutputMapper, LhsMapper, RhsMapper> + TensorContractionKernel; + + typedef typename TensorContractionKernel::LhsBlock LhsBlock; + typedef typename TensorContractionKernel::RhsBlock RhsBlock; + typedef typename TensorContractionKernel::BlockMemHandle BlockMemHandle; + + EvalParallelContext(const Self* self, int num_threads, Scalar* buffer, + Index tm, Index tn, Index tk, Index bm, Index bn, + Index bk, Index nm, Index nn, Index nk, Index gm, + Index gn, Index nm0, Index nn0, bool shard_by_col, + bool parallel_pack, + bool parallelize_by_sharding_dim_only, + DoneCallback done) + : created_by_thread_id_(std::this_thread::get_id()), + done_(this, std::move(done)), + device_(self->m_device), + lhs_(self->m_leftImpl, self->m_left_nocontract_strides, + self->m_i_strides, self->m_left_contracting_strides, + self->m_k_strides), + rhs_(self->m_rightImpl, self->m_right_nocontract_strides, + self->m_j_strides, self->m_right_contracting_strides, + self->m_k_strides), + buffer_(buffer), + output_(buffer, tm), + output_kernel_(self->m_output_kernel), + tensor_contraction_params_(self->m_tensor_contraction_params), + num_threads_(num_threads), + shard_by_col_(shard_by_col), + parallel_pack_(parallel_pack), + parallelize_by_sharding_dim_only_(parallelize_by_sharding_dim_only), + m_(tm), + n_(tn), + k_(tk), + bm_(bm), + bn_(bn), + bk_(bk), + nm_(nm), + nn_(nn), + nk_(nk), + gm_(gm), + gn_(gn), + nm0_(nm0), + nn0_(nn0), + kernel_(m_, k_, n_, bm_, bk_, bn_), + num_thread_local_allocations_(0), + // We reserve 2X more capacity for a thread local values, than the + // number of threads in the pool to efficiently handle task stealing + // by threads that are not managed by the pool. + thread_local_capacity(2 * (parallelize_by_sharding_dim_only_ + ? device_.numThreadsInPool() + : 0)), + // We will use only one of the Lhs/Rhs thread local storage depending + // on the shard_by_col value and we parallelize by sharding dim ONLY. + lhs_thread_local_blocks_(shard_by_col_ ? 0 : thread_local_capacity, + {*this}, {*this}), + rhs_thread_local_blocks_(shard_by_col_ ? thread_local_capacity : 0, + {*this}, {*this}) { + // These two options are mutually exclusive. + eigen_assert(!(parallel_pack && parallelize_by_sharding_dim_only)); + + for (Index x = 0; x < P; x++) { + // Normal number of notifications for k slice switch is + // nm_ + nn_ + nm_ * nn_. However, first P - 1 slices will receive only + // nm_ + nn_ notifications, because they will not receive notifications + // from preceding kernels. + state_switch_[x] = + x == 0 + ? 1 + : (parallel_pack_ ? nn_ + nm_ : (shard_by_col_ ? nn_ : nm_)) + + (x == P - 1 ? nm_ * nn_ : 0); + state_packing_ready_[x] = + parallel_pack_ ? 0 : (shard_by_col_ ? nm_ : nn_); + state_kernel_[x] = new std::atomic*[nm_]; + for (Index m = 0; m < nm_; m++) { + state_kernel_[x][m] = new std::atomic[nn_]; + // Kernels generally receive 3 notifications (previous kernel + 2 + // packing), but the first slice won't get notifications from previous + // kernels. + for (Index n = 0; n < nn_; n++) + state_kernel_[x][m][n].store( + (x == 0 ? 0 : 1) + (parallel_pack_ ? 2 : 1), + std::memory_order_relaxed); + } + } + + // Allocate memory for packed rhs/lhs matrices. + packed_mem_ = kernel_.allocateSlices( // + device_, // + /*num_lhs=*/nm0_, // + /*num_rhs=*/nn0_, // + /*num_slices=*/std::min(nk_, P - 1), // + packed_lhs_, packed_rhs_); + + if (parallelize_by_sharding_dim_only_) { + const int num_worker_threads = device_.numThreadsInPool(); + + if (shard_by_col) { + can_use_thread_local_packed_ = new std::atomic[nn_]; + for (int i = 0; i < nn_; ++i) + can_use_thread_local_packed_[i].store(true, + std::memory_order_relaxed); + + Index num_blocks = num_worker_threads * gn_; + thread_local_pre_alocated_mem_ = kernel_.allocateSlices( // + device_, // + /*num_lhs=*/0, // + /*num_rhs=*/num_blocks, // + /*num_slices=*/1, // + /*lhs_blocks=*/nullptr, &rhs_thread_local_pre_allocated_); + + } else { + can_use_thread_local_packed_ = new std::atomic[nm_]; + for (int i = 0; i < nm_; ++i) + can_use_thread_local_packed_[i].store(true, + std::memory_order_relaxed); + + Index num_blocks = num_worker_threads * gm_; + thread_local_pre_alocated_mem_ = kernel_.allocateSlices( // + device_, // + /*num_lhs=*/num_blocks, // + /*num_rhs=*/0, // + /*num_slices=*/1, &lhs_thread_local_pre_allocated_, // + /*rhs_blocks=*/nullptr); + } + } + } + + ~EvalParallelContext() { + for (Index x = 0; x < P; x++) { + for (Index m = 0; m < nm_; m++) delete[] state_kernel_[x][m]; + delete[] state_kernel_[x]; + } + kernel_.deallocate(device_, packed_mem_); + if (parallelize_by_sharding_dim_only_) { + kernel_.deallocate(device_, thread_local_pre_alocated_mem_); + delete[] can_use_thread_local_packed_; + } + } + + void run() { + // Kick off packing of the first slice. + signal_switch(0, 1); + + // Wait for overall completion. + // + // If parallel evaluation is executed in async mode, this is a no-op, and + // Wait() will return immediately. In synchronous mode it will block the + // caller thread until it will receive notification from last task. + // + // In async mode, last task when completed will call done callback from + // the same thread, and will delete this context. + // + // TODO(dvyukov): This wait can lead to deadlock if contraction is + // evaluated in synchronous mode. If nthreads contractions are + // concurrently submitted from worker threads, this wait will block all + // worker threads and the system will deadlock. + done_.Wait(); + } + + private: + std::thread::id created_by_thread_id_; + + // This notification is specialized on the type of DoneCallback and can be + // blocking or non-blocking. + EvalParallelNotification done_; + + const Device& device_; + LhsMapper lhs_; + RhsMapper rhs_; + Scalar* const buffer_; + OutputMapper output_; + OutputKernelType output_kernel_; + TensorContractionParams tensor_contraction_params_; + const int num_threads_; + const bool shard_by_col_; + const bool parallel_pack_; + const bool parallelize_by_sharding_dim_only_; + // Matrix sizes. + const Index m_; + const Index n_; + const Index k_; + // Block sizes. + const Index bm_; + const Index bn_; + const Index bk_; + // Number of tasks. + const Index nm_; + const Index nn_; + const Index nk_; + // Task grain sizes (number of kernels executed per task). + const Index gm_; + const Index gn_; + // Number of blocks (this is different from ni_/nn_ because of task size + // coarsening). + const Index nm0_; + const Index nn0_; + // Tensor contraction kernel. + TensorContractionKernel kernel_; + + // Parallelization strategy. + // + // Blocks related to the same k block can run in parallel because they write + // to different output blocks. So we parallelize within k slices, this + // gives us parallelism level of m x n. Before we can start any kernels + // related to k-th slice, we need to issue m lhs packing tasks and n rhs + // packing tasks. + // + // However, there is a bottleneck when we are finishing kernels for k-th + // slice (at the very end there is only 1 runnable kernel). To mitigate this + // bottleneck we allow kernels from k-th and k+1-th slices to run in + // parallel. Note that (m, n, k) and (m, n, k+1) kernels write to the same + // output block, so they must not run in parallel. + // + // This gives us the following dependency graph. + // On each k slice we have m x n kernel tasks, m lhs paking tasks and n rhs + // packing tasks. + // Kernel (m, n, k) can start when: + // - kernel (m, n, k-1) has finished + // - lhs packing (m, k) has finished + // - rhs packing (n, k) has finished + // Lhs/rhs packing can start when: + // - all k-1 packing has finished (artificially imposed to limit amount of + // parallel packing) + // + // On top of that we limit runnable tasks to two consecutive k slices. + // This is done to limit amount of memory we need for packed lhs/rhs + // (for each k slice we need m*bk + n*bk memory in packed_lhs_/packed_rhs_). + // + // state_switch_ tracks when we are ready to switch to the next k slice. + // state_kernel_[m][n] tracks when we are ready to kick off kernel (m, n). + // These variable are rolling over 3 consecutive k slices: first two we are + // actively executing + one to track completion of kernels in the second + // slice. + static constexpr Index P = 3; + + // Handle to the allocated temporary storage for Lhs/Rhs blocks. + BlockMemHandle packed_mem_; + std::vector packed_lhs_[P - 1]; + std::vector packed_rhs_[P - 1]; + + // If we choose to parallelize only by the sharding dimension, each thread + // will have it's own "thead local" (not a c++ thread local storage) memory + // for packed_lhs or packed_rhs (shard_by_col = false of true). This memory + // can't be passed to a kernel that might execute on a different thread. + // + // In practice when we are ready to pack memory for the sharding dimension + // (rhs if shard_by_col==true) of the K-th slice, all kernels for K-1 slice + // already computed (99% of the time), and we can pack data into the thread + // local storage, and guarantee that all the kernels will be executed + // immediately in the same thread. This significantly increases L1 cache hit + // ratio and reduces pressure on the memory bus. + // + // It's still possible that kernel for the K-th slice will be ready before + // completion of the K-1 kernel, so we have to allocate "global" packed_lhs_ + // and packed_rhs_ to allow kernels to be executed later on a thread + // different from the thread that was used for packing. + + // Handle for pre-allocated thread local memory buffers. + BlockMemHandle thread_local_pre_alocated_mem_; + + // Only one of these will be initialized depending on shard_by_col value + // (the size will be `num_worker_threads * num_grains_in_the_sharding_dim`). + std::vector lhs_thread_local_pre_allocated_; + std::vector rhs_thread_local_pre_allocated_; + + // How many thread local blocks were already allocated. + std::atomic num_thread_local_allocations_; + const int thread_local_capacity; + + // We will use pre-allocated Lhs/Rhs blocks defined above, if the number of + // unique threads in a system is below or equal to the number of threads in + // a thread pool. We will fallback on dynamic memory allocation after that. + + // ThreadLocalBlocks is a container for Lhs or Rhs thread local buffers. Its + // size is equal to the grain size in Lhs/Rhs sharding dimension. + template + class ThreadLocalBlocks { + public: + ThreadLocalBlocks() = default; + + ThreadLocalBlocks(BlockType* base, size_t grain_size) + : is_pre_allocated_(true), + thread_local_pre_allocated_base_(base), + grain_size_(grain_size) {} + + ThreadLocalBlocks(BlockMemHandle mem_handle, + std::vector blocks) + : is_pre_allocated_(false), + mem_handle_(std::move(mem_handle)), + blocks_(std::move(blocks)) {} + + BlockType& block(int grain_index) { + eigen_assert(grain_index >= 0); + eigen_assert(static_cast(grain_index) < size()); + return is_pre_allocated_ ? thread_local_pre_allocated_base_[grain_index] + : blocks_[grain_index]; + } + + void Release(EvalParallelContext& ctx) const { + if (!is_pre_allocated_) { + ctx.kernel_.deallocate(ctx.device_, mem_handle_); + } + } + + size_t size() const { + return is_pre_allocated_ ? grain_size_ : blocks_.size(); + } + + private: + bool is_pre_allocated_; + + // Reuse pre-allocated thread local buffers. + BlockType* thread_local_pre_allocated_base_ = nullptr; + size_t grain_size_ = 0; + + // These will be initialized only if `is_pre_allocated == false`. + BlockMemHandle mem_handle_{}; + std::vector blocks_; + }; + + // ThreadLocalBlocksInitialize callable does custom thread local blocks + // initialization, and will reuse pre-allocated buffers if possible, or will + // dynamically allocate new memory. + // + // Lhs/Rhs blocks might be of the same type, so we have to pass explicitly + // for what side do we plan to do block allocation. + template + class ThreadLocalBlocksInitialize { + static constexpr bool kIsLhs = + !is_rhs && std::is_same::value; + static const bool kIsRhs = + is_rhs && std::is_same::value; + static_assert(kIsLhs || kIsRhs, "Unknown block type"); + + using Blocks = ThreadLocalBlocks; + + public: + ThreadLocalBlocksInitialize(EvalParallelContext& ctx) + : ctx_(ctx), + num_worker_threads_(ctx_.device_.numThreadsInPool()) {} + + void operator()(Blocks& blocks) { + const int n = ctx_.num_thread_local_allocations_.fetch_add( + 1, std::memory_order_relaxed); + + if (n >= num_worker_threads_) { + ThreadLocalBlocksAllocator::allocate(ctx_, blocks); + } else { + ThreadLocalBlocksAllocator::reuse(ctx_, n, blocks); + } + } + + private: + // NOTE(ezhulenev): Without 'if constexpr' we have to put calls to + // TensorContractionKernel::allocateSlices into template specializations. + // Also explicit specializations are not allowed at class scope in C++03, + // EvalCtx type parameter is just a workaround for that limitation. + template + struct ThreadLocalBlocksAllocator; + + template + struct ThreadLocalBlocksAllocator { + static void allocate(EvalCtx& ctx, Blocks& blocks) { + std::vector rhs_blocks; + BlockMemHandle mem_handle = ctx.kernel_.allocateSlices( + ctx.device_, + /*num_lhs=*/0, + /*num_rhs=*/ctx.gn_, + /*num_slices=*/1, + /*lhs_blocks=*/nullptr, /*rhs_blocks=*/&rhs_blocks); + + blocks = ThreadLocalBlocks(std::move(mem_handle), + std::move(rhs_blocks)); + } + + static void reuse(EvalCtx& ctx, int index, Blocks& blocks) { + RhsBlock* ptr = &ctx.rhs_thread_local_pre_allocated_[ctx.gn_ * index]; + blocks = ThreadLocalBlocks(ptr, ctx.gn_); + } + }; + + template + struct ThreadLocalBlocksAllocator { + static void allocate(EvalCtx& ctx, Blocks& blocks) { + std::vector lhs_blocks; + BlockMemHandle mem_handle = ctx.kernel_.allocateSlices( + ctx.device_, + /*num_lhs=*/ctx.gm_, + /*num_rhs=*/0, + /*num_slices=*/1, + /*lhs_blocks=*/&lhs_blocks, /*rhs_blocks=*/nullptr); + + blocks = ThreadLocalBlocks(std::move(mem_handle), + std::move(lhs_blocks)); + } + + static void reuse(EvalCtx& ctx, int index, Blocks& blocks) { + LhsBlock* ptr = &ctx.lhs_thread_local_pre_allocated_[ctx.gm_ * index]; + blocks = ThreadLocalBlocks(ptr, ctx.gm_); + } + }; + + EvalParallelContext& ctx_; + const int num_worker_threads_; + }; + + template + class ThreadLocalBlocksRelease { + public: + using Blocks = ThreadLocalBlocks; + ThreadLocalBlocksRelease(EvalParallelContext& ctx) : ctx_(ctx) {} + void operator()(Blocks& blocks) { blocks.Release(ctx_); } + + private: + EvalParallelContext& ctx_; + }; + + // ThreadLocalBlocks initialization callables. + using ThreadLocalLhsInit = + ThreadLocalBlocksInitialize; + using ThreadLocalRhsInit = + ThreadLocalBlocksInitialize; + + // ThreadLocalBlocks release callables. + using ThreadLocalLhsRelease = ThreadLocalBlocksRelease; + using ThreadLocalRhsRelease = ThreadLocalBlocksRelease; + + // Thread local containers for Lhs/Rhs block packs. In practice only one of + // them will be used, depending on the shard_by_col value. + Eigen::ThreadLocal, ThreadLocalLhsInit, + ThreadLocalLhsRelease> + lhs_thread_local_blocks_; + Eigen::ThreadLocal, ThreadLocalRhsInit, + ThreadLocalRhsRelease> + rhs_thread_local_blocks_; + + // After a particular shard for Kth slice missed thread local execution + // opportunity (K-1 slice didn't complete kernels execution), we can no + // longer schedule K+1 and following slices in thread local mode, because + // there is no more guarantee that previous kernels were executed + // sequentially in the same thread (size is nn_ or nm_). + std::atomic* can_use_thread_local_packed_; + + std::atomic** state_kernel_[P]; + // state_switch_ is frequently modified by worker threads, while other + // fields are read-only after constructor. Let's move it to a separate cache + // line to reduce cache-coherency traffic. + char pad_[128]; + std::atomic state_packing_ready_[P]; + std::atomic state_switch_[P]; + + LhsBlock& packed_lhs(Index m, Index k, Index m1, bool use_thread_local) { + if (use_thread_local) { + eigen_assert(!shard_by_col_); + ThreadLocalBlocks& blocks = lhs_thread_local_blocks_.local(); + + Index grain_index = m1 - m * gm_; + return blocks.block(internal::convert_index(grain_index)); // FIXME better make ThreadLocalBlocks use Eigen::Index? + } else { + return packed_lhs_[k % (P - 1)][m1]; + } + } + + RhsBlock& packed_rhs(Index n, Index k, Index n1, bool use_thread_local) { + if (use_thread_local) { + eigen_assert(shard_by_col_); + ThreadLocalBlocks& blocks = rhs_thread_local_blocks_.local(); + + Index grain_index = n1 - n * gn_; + return blocks.block(internal::convert_index(grain_index)); // FIXME better make ThreadLocalBlocks use Eigen::Index? + } else { + return packed_rhs_[k % (P - 1)][n1]; + } + } + + // In following two methods (pack_lhs and pack_rhs), if we know for sure + // that we'll be able to immediately call a kernel with packed data, and do + // not submit it to the thread pool, we can use thread local memory for + // packed data. + // + // We can only reliably check it if we are running all kernels in sync mode + // (parallelize only by sharding dim). If kernel for m==0 (n==0) is ready to + // run, it's guaranteed that all kernels with larger values of m (n) are + // also ready, because we execute them in the same order for all K slices. + + void pack_lhs(Index m, Index k) { + bool use_thread_local = false; + + if (parallelize_by_sharding_dim_only_ && !shard_by_col_ && + can_use_thread_local_packed_[m].load(std::memory_order_relaxed)) { + if (state_kernel_[k % P][m][0].load(std::memory_order_relaxed) == 1) { + use_thread_local = true; + } else { + // If we can't guarantee that all kernels in `k` slice will be + // executed sequentially in current thread, it's no longer safe to use + // thread local memory in following slices along the k dimensions. + eigen_assert(k > 0); + can_use_thread_local_packed_[m].store(false, + std::memory_order_relaxed); + } + } + + const Index mend = m * gm_ + gm(m); + for (Index m1 = m * gm_; m1 < mend; m1++) + kernel_.packLhs(&packed_lhs(m, k, m1, use_thread_local), + lhs_.getSubMapper(m1 * bm_, k * bk_), bk(k), bm(m1)); + + if (!parallel_pack_ && shard_by_col_) { + eigen_assert(!use_thread_local); + signal_packing(k); + } else { + signal_switch(k + 1); + for (Index n = nn_ - 1; n >= 0; n--) { + bool sync = parallelize_by_sharding_dim_only_ || n == 0; + signal_kernel(m, n, k, sync, use_thread_local); + } + } + } + + void pack_rhs(Index n, Index k) { + bool use_thread_local = false; + + if (parallelize_by_sharding_dim_only_ && shard_by_col_ && + can_use_thread_local_packed_[n].load(std::memory_order_relaxed)) { + if (state_kernel_[k % P][0][n].load(std::memory_order_relaxed) == 1) { + use_thread_local = true; + } else { + // If we can't guarantee that all kernels in `k` slice will be + // executed sequentially in current thread, it's no longer safe to use + // thread local memory in following slices along the k dimensions. + eigen_assert(k > 0); + can_use_thread_local_packed_[n].store(false, + std::memory_order_relaxed); + } + } + + const Index nend = n * gn_ + gn(n); + for (Index n1 = n * gn_; n1 < nend; n1++) { + if (!TensorContractionKernel::HasBeta && k == 0) { + // Zero the output memory in parallel, only if contraction kernel does + // not support `beta`. Otherwise we will pass beta 0.0 to the first + // call to the `TensorContractionKernel::invoke()`. + // + // On 10000x2x10000 mm zeroing can easily take half of time. Zero (bn + // x m) row. Safe to do here because all kernels that will write to + // this memory depend on completion of this task. Note: don't call + // device_.fill() here. device_.fill() blocks on thread pool + // worker thread, which can lead to underutilization and deadlocks. + std::fill_n(buffer_ + n1 * bn_ * m_, bn(n1) * m_, Scalar(0)); + } + kernel_.packRhs(&packed_rhs(n, k, n1, use_thread_local), + rhs_.getSubMapper(k * bk_, n1 * bn_), bk(k), bn(n1)); + } + + if (parallel_pack_ || shard_by_col_) { + signal_switch(k + 1); + for (Index m = nm_ - 1; m >= 0; m--) { + bool sync = parallelize_by_sharding_dim_only_ || m == 0; + signal_kernel(m, n, k, sync, use_thread_local); + } + } else { + eigen_assert(!use_thread_local); + signal_packing(k); + } + } + + void kernel(Index m, Index n, Index k, bool use_thread_local) { + // Note: order of iteration matters here. Iteration over m is innermost + // because we want to reuse the same packed rhs in consecutive tasks + // (rhs fits into L2$ while lhs only into L3$). + const Index nend = n * gn_ + gn(n); + const Index mend = m * gm_ + gm(m); + + // NOTE: output = alpha * LHS * RHS + beta * output. + const Scalar alpha = Scalar(1); + const Scalar beta = + (TensorContractionKernel::HasBeta && k == 0) ? Scalar(0) : Scalar(1); + + if (shard_by_col_) { + for (Index n1 = n * gn_; n1 < nend; n1++) { + for (Index m1 = m * gm_; m1 < mend; m1++) { + const auto output_mapper = output_.getSubMapper(m1 * bm_, n1 * bn_); + kernel_.invoke( + output_mapper, + packed_lhs(m, k, m1, !shard_by_col_ && use_thread_local), + packed_rhs(n, k, n1, shard_by_col_ && use_thread_local), bm(m1), + bk(k), bn(n1), alpha, beta); + + // We are done with the last task for the [m1, n1] block. + if (k + 1 == nk_) { + output_kernel_(output_mapper, tensor_contraction_params_, + m1 * bm_, n1 * bn_, bm(m1), bn(n1)); + } + } + } + } else { + for (Index m1 = m * gm_; m1 < mend; m1++) + for (Index n1 = n * gn_; n1 < nend; n1++) { + const auto output_mapper = output_.getSubMapper(m1 * bm_, n1 * bn_); + kernel_.invoke( + output_mapper, + packed_lhs(m, k, m1, !shard_by_col_ && use_thread_local), + packed_rhs(n, k, n1, shard_by_col_ && use_thread_local), bm(m1), + bk(k), bn(n1), alpha, beta); + + // We are done with the last task for the [m1, n1] block. + if (k + 1 == nk_) { + output_kernel_(output_mapper, tensor_contraction_params_, + m1 * bm_, n1 * bn_, bm(m1), bn(n1)); + } + } + } + signal_kernel(m, n, k + 1, /*sync=*/false, /*use_thread_local=*/false); + signal_switch(k + 2); + } + + void signal_packing(Index k) { + eigen_assert(!parallel_pack_); + Index s = state_packing_ready_[k % P].fetch_sub(1); + eigen_assert(s > 0); + if (s != 1) return; + state_packing_ready_[k % P] = shard_by_col_ ? nm_ : nn_; + enqueue_packing(k, shard_by_col_); + } + + void signal_kernel(Index m, Index n, Index k, bool sync, + bool use_thread_local) { + std::atomic* state = &state_kernel_[k % P][m][n]; + Index s = state->load(); + eigen_assert(s > 0); + if (s != 1 && state->fetch_sub(1) != 1) { + eigen_assert(!use_thread_local); + return; + } + state->store(parallel_pack_ ? 3 : 2, std::memory_order_relaxed); + if (sync) { + kernel(m, n, k, use_thread_local); + } else { + eigen_assert(!use_thread_local); + device_.enqueueNoNotification( + [=]() { kernel(m, n, k, use_thread_local); }); + } + } + + void signal_switch(Index k, Index v = 1) { + Index s = state_switch_[k % P].fetch_sub(v); + eigen_assert(s >= v); + if (s != v) return; + + // Ready to switch to the next k slice. + // Reset counter for the next iteration. + state_switch_[k % P] = + (parallel_pack_ ? nm_ + nn_ : (shard_by_col_ ? nn_ : nm_)) + + nm_ * nn_; + if (k < nk_) { + // Issue lhs/rhs packing. Their completion will in turn kick off + // kernels. + if (parallel_pack_) { + enqueue_packing(k, !shard_by_col_); + enqueue_packing(k, shard_by_col_); + } else if (shard_by_col_) { + enqueue_packing(k, false); + } else { + enqueue_packing(k, true); + } + + // Termination handling. + // Because kernel completion signals k + 2 switch, we need to finish nk + // + 2 slices without issuing any tasks on nk + 1 slice. So here we + // pretend that all nk + 1 packing tasks just finish instantly; so that + // nk + 2 switch only waits for completion of nk kernels. + } else if (k == nk_) { + signal_switch(k + 1, + parallel_pack_ ? nm_ + nn_ : (shard_by_col_ ? nn_ : nm_)); + } else { + done_.Notify(); + } + } + + // Enqueue all rhs/lhs packing for k-th slice. + void enqueue_packing(Index k, bool rhs) { + enqueue_packing_helper(0, rhs ? nn_ : nm_, k, rhs); + } + + void enqueue_packing_helper(Index start, Index end, Index k, bool rhs) { + if (end - start == 1) { + if (rhs) + pack_rhs(start, k); + else + pack_lhs(start, k); + } else { + while (end - start > 1) { + Index mid = (start + end) / 2; + device_.enqueueNoNotification( + [=]() { enqueue_packing_helper(mid, end, k, rhs); }); + end = mid; + } + + // Decide if we want to run first packing task (start == 0) in + // async mode if we parallelize only by sharding dim: + // (1) pack_lhs and pack_rhs call signal_switch before completing + // all calls to signal_kernel, which in sync mode might lead + // to the execution of the first kernel of the k+1 slice, before + // completing a call to the last kernel of the k slice. + // (2) all pack tasks for sharded dim must be executed in a thread + // pool to get pre-allocated thead local buffers. + bool pack_async = + (start == 0) && + (parallelize_by_sharding_dim_only_&& shard_by_col_ == rhs) && + (k > 0 || std::this_thread::get_id() == created_by_thread_id_); + + if (pack_async) { + device_.enqueueNoNotification( + [=]() { enqueue_packing_helper(start, end, k, rhs); }); + } else { + enqueue_packing_helper(start, end, k, rhs); + } + } + } + + // Block sizes with accounting for potentially incomplete last block. + Index bm(Index m) const { return m + 1 < nm0_ ? bm_ : m_ + bm_ - bm_ * nm0_; } + Index bn(Index n) const { return n + 1 < nn0_ ? bn_ : n_ + bn_ - bn_ * nn0_; } + Index bk(Index k) const { return k + 1 < nk_ ? bk_ : k_ + bk_ - bk_ * nk_; } + // Task grain sizes accounting for potentially incomplete last task. + Index gm(Index m) const { return m + 1 < nm_ ? gm_ : nm0_ + gm_ - gm_ * nm_; } + Index gn(Index n) const { return n + 1 < nn_ ? gn_ : nn0_ + gn_ - gn_ * nn_; } + + EvalParallelContext(const EvalParallelContext&) = delete; + void operator=(const EvalParallelContext&) = delete; + }; + + template + using SyncEvalParallelContext = + EvalParallelContext; + + // ------------------------------------------------------------------------ // + + // EvalShardedByInnerDimContext orchestrates sync/async contraction + // evaluation, when we shard by inner dimension. When it is executed in + // asynchronous mode, it owns all the shared state that might be accessible by + // block processing tasks. + + template + struct EvalShardedByInnerDimContext { + EvalShardedByInnerDimContext(const Self* self, int num_threads, + Scalar* result_buffer, + Index m_size, Index n_size, Index k_size, + DoneCallback done_callback) + : evaluator(self), + m_lhs_inner_dim_contiguous(evaluator->m_lhs_inner_dim_contiguous), + m_rhs_inner_dim_contiguous(evaluator->m_rhs_inner_dim_contiguous), + m_rhs_inner_dim_reordered(evaluator->m_rhs_inner_dim_reordered), + result(result_buffer), + m(m_size), + n(n_size), + k(k_size), + done(std::move(done_callback)), + buffer_size_bytes(m * n * sizeof(Scalar)), + block_size(blockSize(k, num_threads)), + num_blocks(divup(k, block_size)), + num_pending_blocks(internal::convert_index(num_blocks)), + l0_ranges(divup(num_blocks, l0_size)), + l0_state(l0_ranges), + block_buffers(num_blocks) { + // Keep count of pending gemm tasks for each l0 range. + for (int i = 0; i < l0_ranges; ++i) { + const Index num_pending_tasks = actualRangeSize(l0_ranges, l0_size, i); + l0_state.emplace_back(internal::convert_index(num_pending_tasks)); + } + + // Allocate temporary buffers for each block. + for (Index block_idx = 0; block_idx < num_blocks; ++block_idx) { + Scalar* buf = block_idx == 0 + ? result + : static_cast(evaluator->m_device.allocate( + buffer_size_bytes)); + block_buffers.emplace_back(buf); + } + } + + ~EvalShardedByInnerDimContext() { + for (Index i = 1; i < num_blocks; ++i) { + evaluator->m_device.deallocate(block_buffers[i]); + } + } + + template + void run() { + Barrier barrier(internal::convert_index(num_blocks)); + eval(barrier, 0, num_blocks); + barrier.Wait(); + + // Aggregate partial sums from l0 ranges. + aggregateL0Blocks(); + + // Apply output kernel. + applyOutputKernel(); + } + + template + void runAsync() { + evalAsync(0, num_blocks); + } + + private: + // The underlying GEMM kernel assumes that k is a multiple of + // the packet size and subtle breakage occurs if this is violated. + static const Index packet_size = internal::packet_traits::size; + + const Self* evaluator; // TensorContraction evaluator + + // These fields required fromTENSOR_CONTRACTION_DISPATCH macro. + bool m_lhs_inner_dim_contiguous; + bool m_rhs_inner_dim_contiguous; + bool m_rhs_inner_dim_reordered; + + Scalar* result; + + Index m; + Index n; + Index k; + + DoneCallback done; + + // ----------------------------------------------------------------------// + // Algorithm parameters. + + // We will compute partial results into the buffers of this size. + Index buffer_size_bytes; + + Index block_size; + Index num_blocks; + + // Keep track of pending tasks when evaluate in async mode. + std::atomic num_pending_blocks; + + // We compute partial gemm results in parallel, and to get the final result + // we need to add them all together. For the large number of threads (>= 48) + // this adds a very expensive sequential step at the end. + // + // We split the [0, num_blocks) into small ranges, and when a task for the + // block finishes its partial gemm computation, it checks if it was the last + // gemm in the range, and if so, it will add all blocks of the range. + // + // After all tasks done, we need to add only these pre-aggregated blocks. + + // For now we use just a single level of ranges to compute pre-aggregated + // partial sums, but in general we can use more layers to compute tree + // aggregation in parallel and reduce the size of the sequential step. + // + // TODO(ezhulenev): Add multilevel tree aggregation? Probably will make + // sense only if number of threads >= ~128? + static const Index l0_size = 4; + Index l0_ranges; + + // Keep count of pending gemm tasks for each l0 range. + MaxSizeVector> l0_state; // [0, l0_ranges) + + // Buffers allocated for each temporary block computation. + MaxSizeVector block_buffers; // [0, num_blocks) + + template + void processBlock(Index block_idx, Index begin, Index end) { + Scalar* buf = block_buffers[block_idx]; + + TENSOR_CONTRACTION_DISPATCH( + evaluator->template evalGemmPartialWithoutOutputKernel, Alignment, + (buf, begin, end, + /*num_threads=*/internal::convert_index(num_blocks))); + + // Check if it was the last task in l0 range. + const Index l0_index = block_idx / l0_size; + const int v = l0_state[l0_index].fetch_sub(1); + eigen_assert(v >= 1); + + // If we processed the last block of the range, we can aggregate all + // partial results into the first block of the range. + if (v == 1) { + const Index rng_size = actualRangeSize(l0_ranges, l0_size, l0_index); + const Index dst_block_idx = l0_index * l0_size; + + if (rng_size == l0_size) { + addAllToBuffer( + m * n, + /*src_buf0=*/block_buffers[dst_block_idx + 1], + /*src_buf1=*/block_buffers[dst_block_idx + 2], + /*src_buf2=*/block_buffers[dst_block_idx + 3], + /*dst_buf= */ block_buffers[dst_block_idx]); + } else { + // Aggregate blocks of potentially incomplete last range. + for (int i = 1; i < rng_size; ++i) { + addToBuffer(m * n, + /*src_buf=*/block_buffers[dst_block_idx + i], + /*dst_buf=*/block_buffers[dst_block_idx]); + } + } + } + } + + // Aggregate partial sums from l0 ranges. + template + void aggregateL0Blocks() const { + Index l0_index = 1; + + for (; l0_index + 2 < l0_ranges; l0_index += 3) { + addAllToBuffer( + m * n, + /*src_buf0=*/block_buffers[(l0_index + 0) * l0_size], + /*src_buf1=*/block_buffers[(l0_index + 1) * l0_size], + /*src_buf2=*/block_buffers[(l0_index + 2) * l0_size], + /*dst_buf= */ block_buffers[0]); + } + + for (; l0_index < l0_ranges; ++l0_index) { + addToBuffer(m * n, block_buffers[l0_index * l0_size], + block_buffers[0]); + } + } + + void applyOutputKernel() const { + typedef internal::blas_data_mapper OutputMapper; + evaluator->m_output_kernel( + OutputMapper(result, m), evaluator->m_tensor_contraction_params, + static_cast(0), static_cast(0), m, n); + } + + // Compute block size with accounting for potentially incomplete last block. + Index actualBlockSize(Index block_idx) const { + return block_idx + 1 < num_blocks + ? block_size + : k + block_size - block_size * num_blocks; + }; + + // Compute range size with accounting for potentially incomplete last range. + Index actualRangeSize(Index num_ranges, Index range_size, + Index range_idx) const { + eigen_assert(range_idx < num_ranges); + return range_idx + 1 < num_ranges + ? range_size + : num_blocks + range_size - range_size * num_ranges; + }; + + template + EIGEN_STRONG_INLINE static void addToBuffer(size_t n, const Scalar* src_buf, + Scalar* tgt_buf) { + const int output_packet_size = + internal::unpacket_traits::size; + size_t i = 0; + const size_t num_packets = n / output_packet_size; + for (; i < output_packet_size * num_packets; i += output_packet_size) { + const PacketReturnType src_val = + internal::pload(src_buf + i); + const PacketReturnType tgt_val = + internal::ploadt(tgt_buf + i); + const PacketReturnType sum = internal::padd(src_val, tgt_val); + internal::pstoret(tgt_buf + i, + sum); + } + for (; i < n; ++i) { + tgt_buf[i] += src_buf[i]; + } + } + + template + EIGEN_STRONG_INLINE static void addAllToBuffer(size_t n, + const Scalar* src_buf0, + const Scalar* src_buf1, + const Scalar* src_buf2, + Scalar* dst_buf) { + using ::Eigen::internal::padd; + using ::Eigen::internal::pload; + using ::Eigen::internal::ploadt; + using ::Eigen::internal::pstoret; + + const int output_packet_size = + internal::unpacket_traits::size; + + size_t i = 0; + const size_t num_packets = n / output_packet_size; + for (; i < output_packet_size * num_packets; i += output_packet_size) { + const auto src_val0 = pload(src_buf0 + i); + const auto src_val1 = pload(src_buf1 + i); + const auto src_val2 = pload(src_buf2 + i); + + const auto dst_val = ploadt(dst_buf + i); + const auto sum = + padd(padd(dst_val, src_val0), padd(src_val1, src_val2)); + + pstoret(dst_buf + i, sum); + } + for (; i < n; ++i) { + dst_buf[i] += src_buf0[i] + src_buf1[i] + src_buf2[i]; + } + } + + template + void eval(Barrier& barrier, Index start_block_idx, Index end_block_idx) { + while (end_block_idx - start_block_idx > 1) { + Index mid_block_idx = (start_block_idx + end_block_idx) / 2; + evaluator->m_device.enqueueNoNotification( + [this, &barrier, mid_block_idx, end_block_idx]() { + eval(barrier, mid_block_idx, end_block_idx); + }); + end_block_idx = mid_block_idx; + } + + Index block_idx = start_block_idx; + Index block_start = block_idx * block_size; + Index block_end = block_start + actualBlockSize(block_idx); + + processBlock(block_idx, block_start, block_end); + barrier.Notify(); + } + + template + void evalAsync(Index start_block_idx, Index end_block_idx) { + while (end_block_idx - start_block_idx > 1) { + Index mid_block_idx = (start_block_idx + end_block_idx) / 2; + evaluator->m_device.enqueueNoNotification( + [this, mid_block_idx, end_block_idx]() { + evalAsync(mid_block_idx, end_block_idx); + }); + end_block_idx = mid_block_idx; + } + + Index block_idx = start_block_idx; + + Index block_start = block_idx * block_size; + Index block_end = block_start + actualBlockSize(block_idx); + + processBlock(block_idx, block_start, block_end); + + int v = num_pending_blocks.fetch_sub(1); + eigen_assert(v >= 1); + + if (v == 1) { + // Aggregate partial sums from l0 ranges. + aggregateL0Blocks(); + + // Apply output kernel. + applyOutputKernel(); + + // NOTE: If we call `done` callback before deleting this (context), + // it might deallocate Self* pointer captured by context, and we'll + // fail in destructor trying to deallocate temporary buffers. + + // Move done call back from context before it will be destructed. + DoneCallback done_copy = std::move(done); + + // We are confident that we are the last one who touches context. + delete this; + + // Now safely call the done callback. + done_copy(); + } + } + + // Cost model doesn't capture well the cost associated with constructing + // tensor contraction mappers and computing loop bounds in gemm_pack_lhs + // and gemm_pack_rhs, so we specify minimum desired block size. + static Index blockSize(Index k, int num_threads) { + const auto round_up = [=](Index index) -> Index { + const Index kmultiple = packet_size <= 8 ? 8 : packet_size; + return divup(index, kmultiple) * kmultiple; + }; + + const Index target_block_size = round_up(divup(k, num_threads)); + const Index desired_min_block_size = 12 * packet_size; + + return numext::mini( + k, numext::maxi(desired_min_block_size, target_block_size)); + } + + EvalShardedByInnerDimContext(const EvalShardedByInnerDimContext&) = delete; + void operator=(const EvalShardedByInnerDimContext&) = delete; + }; + + // ------------------------------------------------------------------------ // + + // Below are the function used by evalProductImpl heuristics, trying to select + // optimcal parameters for parallelization algorithm. + + // Decide whether we want to shard m x n contraction by columns or by rows. + static bool shardByCol(Index m, Index n, Index num_threads) { + // Note: we are comparing both n and m against Traits::nr, it is not + // a mistake. We are trying to figure out how both n and m will fit into + // the main sharding dimension. + + // Sharding by column is the default + // ... unless there is enough data for vectorization over rows + if (m / num_threads >= Traits::nr && + // and not enough data for vectorization over columns + (n / num_threads < Traits::nr || + // ... or barely enough data for vectorization over columns, + // but it is not evenly dividable across threads + (n / num_threads < 4 * Traits::nr && + (n % (num_threads * Traits::nr)) != 0 && + // ... and it is evenly dividable across threads for rows + ((m % (num_threads * Traits::nr)) == 0 || + // .. or it is not evenly dividable for both dimensions but + // there is much more data over rows so that corner effects are + // mitigated. + (m / n >= 6))))) + return false; + // Wait, or if matrices are just substantially prolonged over the other + // dimension. + if (n / num_threads < 16 * Traits::nr && m > n * 32) return false; + return true; + } + + Index coarsenM(Index m, Index n, Index bm, Index bn, Index bk, Index gn, + int num_threads, bool shard_by_col) const { + Index gm = 1; + Index gm1 = 1; + Index nm0 = divup(m, bm); + Index nm1 = nm0; + for (;;) { + // Find the next candidate for m grain size. It needs to result in + // different number of blocks. E.g. if we have 10 kernels, we want to try + // 5 and 10, but not 6, 7, 8 and 9. + while (gm1 <= nm0 && nm1 == divup(nm0, gm1)) gm1++; + if (gm1 > nm0) break; + // Check the candidate. + int res = checkGrain(m, n, bm, bn, bk, gm1, gn, gm, gn, num_threads, + shard_by_col); + if (res < 0) break; + nm1 = divup(nm0, gm1); + if (res == 0) continue; + // Commit new grain size. + gm = gm1; + } + return gm; + } + + Index coarsenN(Index m, Index n, Index bm, Index bn, Index bk, Index gm, + int num_threads, bool shard_by_col) const { + Index gn = 1; + Index gn1 = 1; + Index nn0 = divup(n, bn); + Index nn1 = nn0; + for (;;) { + while (gn1 <= nn0 && nn1 == divup(nn0, gn1)) gn1++; + if (gn1 > nn0) break; + int res = checkGrain(m, n, bm, bn, bk, gm, gn1, gm, gn, num_threads, + shard_by_col); + if (res < 0) break; + nn1 = divup(nn0, gn1); + if (res == 0) continue; + gn = gn1; + } + return gn; + } + + // checkGrain checks whether grain (gm, gn) is suitable and is better than + // (oldgm, oldgn). + int checkGrain(Index m, Index n, Index bm, Index bn, Index bk, Index gm, + Index gn, Index oldgm, Index oldgn, int num_threads, + bool shard_by_col) const { + const TensorOpCost cost = + contractionCost(bm * gm, bn * gn, bm, bn, bk, shard_by_col, true); + double taskSize = TensorCostModel::taskSize( + static_cast(bm) * gm * bn * gn, cost); + // If the task is too small, then we agree on it regardless of anything + // else. Otherwise synchronization overheads will dominate. + if (taskSize < 1) return 1; + // If it is too large, then we reject it and all larger tasks. + if (taskSize > 2) return -1; + // Now we are in presumably good task size range. + // The main deciding factor here is parallelism. Consider that we have 12 + // kernels and 4 threads. Grains of 2, 3 and 4 all yield good task sizes. + // But 2/4 yield 6/3 tasks, which gives us parallelism of 0.75 (at most 3/4 + // of cores will be busy). While grain size 3 gives us 4 tasks, which gives + // us parallelism of 1 (we can load all cores). + Index nm0 = divup(m, bm); + Index nn0 = divup(n, bn); + Index new_tasks = divup(nm0, gm) * divup(nn0, gn); + double new_parallelism = static_cast(new_tasks) / + (divup(new_tasks, num_threads) * num_threads); + Index old_tasks = divup(nm0, oldgm) * divup(nn0, oldgn); + double old_parallelism = static_cast(old_tasks) / + (divup(old_tasks, num_threads) * num_threads); + if (new_parallelism > old_parallelism || new_parallelism == 1) return 1; + return 0; + } + + TensorOpCost contractionCost(Index m, Index n, Index bm, Index bn, Index bk, + bool shard_by_col, bool prepacked) const { + const int packed_size = std::min(PacketType::size, + PacketType::size); + const int output_packet_size = internal::unpacket_traits::size; + const double kd = static_cast(bk); + double compute_bandwidth = computeBandwidth(false, bm, bn, bk); + // Computations. + TensorOpCost cost = TensorOpCost(0, 0, kd * compute_bandwidth, true, packed_size); + // Output stores. + cost += TensorOpCost(0, sizeof(CoeffReturnType), 0, true, output_packet_size); + if (prepacked) { + // Packing and kernels are executed in different tasks. When we calculate + // task grain size we look only at kernel cost assuming that kernel + // is more expensive than packing. + return cost; + } + // Lhs/rhs loads + computations. + TensorOpCost lhsCost = this->m_leftImpl.costPerCoeff(true) * (kd / n); + TensorOpCost rhsCost = this->m_rightImpl.costPerCoeff(true) * (kd / m); + // Lhs packing memory cost does not contribute considerably to overall + // execution time because lhs is prefetched early and accessed sequentially. + if (shard_by_col) + lhsCost.dropMemoryCost(); + else + rhsCost.dropMemoryCost(); + return cost + lhsCost + rhsCost; + } + + // Decide whether we want to shard m x k x n contraction over the inner + // (contraction) dimension (k). + static bool shardByInnerDim(Index m, Index n, Index k, int num_threads, + int num_threads_by_k) { + std::ptrdiff_t bufsize = m * n * sizeof(Scalar); + bool shard_by_k = false; + if (n == 1 || // If mat*vec or... + num_threads_by_k < 2 || // running single threaded or... + num_threads_by_k < + num_threads || // sharding by k gives less parallelism or... + bufsize > l3CacheSize() / num_threads_by_k || // need more buffer space + // than L3 cache or... + k / num_threads_by_k < 2 * Traits::nr) { // k per thread is tiny. + shard_by_k = false; + } else if (numext::maxi(m, n) / num_threads < + Traits::nr || // both other dimensions are tiny or... + // k per thread is not small and... + (k / num_threads_by_k > 8 * Traits::nr && + // one of the outer dimensions is tiny or sharding by k offers + // more parallelism. + (numext::mini(m, n) < 2 * Traits::nr || + num_threads_by_k > num_threads))) { + shard_by_k = true; + } + return shard_by_k; + } + + TensorOpCost contractionCostPerInnerDim(Index m, Index n, Index k) const { + // Compute cost. + const int output_packet_size = internal::unpacket_traits::size; + TensorOpCost cost(0, 0, (computeBandwidth(true, m, n, k) * m) * n, true, output_packet_size); + // Output stores. + cost += TensorOpCost(0, sizeof(CoeffReturnType), 0, true, output_packet_size); + TensorOpCost lhsCost = this->m_leftImpl.costPerCoeff(true) * m; + TensorOpCost rhsCost = this->m_rightImpl.costPerCoeff(true) * n; + // Since the inner gemm kernel is always sharded by column, the lhs + // load cost is negligible. + lhsCost.dropMemoryCost(); + return cost + lhsCost + rhsCost; + } + + int numThreadsInnerDim(Index m, Index n, Index k) const { + const int output_packet_size = internal::unpacket_traits::size; + TensorOpCost cost = contractionCostPerInnerDim(m, n, k); + double total_parallel_cost = + TensorCostModel::totalCost(k, cost); + // Cost of reduction step accumulating the m*n per-thread buffers into the + // result. + double reduction_cost = TensorCostModel::totalCost( + m * n, TensorOpCost(2, 1, 1, true, output_packet_size)); + int num_threads = 1; + double min_cost = total_parallel_cost; + double kPerThreadOverHead = 3000; + double kFixedOverHead = 100000; + for (int nt = 2; nt <= this->m_device.numThreads(); nt += 2) { + double sequential_cost = + kFixedOverHead + nt * (reduction_cost + kPerThreadOverHead); + double parallel_cost = total_parallel_cost / nt + sequential_cost; + if (parallel_cost < min_cost) { + num_threads = nt; + min_cost = parallel_cost; + } + } + return num_threads; + } + + double computeBandwidth(bool shard_by_col, Index bm, Index bn, + Index bk) const { + // Peak VFMA bandwidth is 0.5. However if we have not enough data for + // vectorization bandwidth drops. The 4.0 and 2.0 bandwidth is determined + // experimentally. + double computeBandwidth = + bk == 1 ? 4.0 + : (shard_by_col ? bn : bm) < Traits::nr || + (shard_by_col ? bm : bn) < Traits::mr + ? 2.0 + : 0.5; +#ifndef EIGEN_VECTORIZE_FMA + // Bandwidth of all of VFMA/MULPS/ADDPS is 0.5 on latest Intel processors. + // However for MULPS/ADDPS we have dependent sequence of 2 such + // instructions, + // so overall bandwidth is 1.0. + if (computeBandwidth == 0.5) computeBandwidth = 1.0; +#endif + return computeBandwidth; + } + +}; + +} // end namespace Eigen + +#endif // EIGEN_USE_THREADS +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONTRACTION_THREAD_POOL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h new file mode 100644 index 0000000000000000000000000000000000000000..d59c2c35da808ffc1a2f33b96fa600eb80a51a5b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h @@ -0,0 +1,452 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorConversionOp + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor conversion class. This class makes it possible to vectorize + * type casting operations when the number of scalars per packet in the source + * and the destination type differ + */ +namespace internal { +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef TargetType Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = traits::Layout; + enum { Flags = 0 }; + typedef typename TypeConversion::PointerType>::type PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorConversionOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorConversionOp type; +}; + +} // end namespace internal + + +template +struct PacketConverter; + +template +struct PacketConverter { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketConverter(const TensorEvaluator& impl) + : m_impl(impl) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const { + return internal::pcast(m_impl.template packet(index)); + } + + private: + const TensorEvaluator& m_impl; +}; + + +template +struct PacketConverter { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketConverter(const TensorEvaluator& impl) + : m_impl(impl) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const { + const int SrcPacketSize = internal::unpacket_traits::size; + + SrcPacket src1 = m_impl.template packet(index); + SrcPacket src2 = m_impl.template packet(index + SrcPacketSize); + TgtPacket result = internal::pcast(src1, src2); + return result; + } + + private: + const TensorEvaluator& m_impl; +}; + +template +struct PacketConverter { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketConverter(const TensorEvaluator& impl) + : m_impl(impl) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const { + const int SrcPacketSize = internal::unpacket_traits::size; + + SrcPacket src1 = m_impl.template packet(index); + SrcPacket src2 = m_impl.template packet(index + SrcPacketSize); + SrcPacket src3 = m_impl.template packet(index + 2 * SrcPacketSize); + SrcPacket src4 = m_impl.template packet(index + 3 * SrcPacketSize); + TgtPacket result = internal::pcast(src1, src2, src3, src4); + return result; + } + + private: + const TensorEvaluator& m_impl; +}; + +template +struct PacketConverter { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketConverter(const TensorEvaluator& impl) + : m_impl(impl) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const { + const int SrcPacketSize = internal::unpacket_traits::size; + + SrcPacket src1 = m_impl.template packet(index); + SrcPacket src2 = m_impl.template packet(index + 1 * SrcPacketSize); + SrcPacket src3 = m_impl.template packet(index + 2 * SrcPacketSize); + SrcPacket src4 = m_impl.template packet(index + 3 * SrcPacketSize); + SrcPacket src5 = m_impl.template packet(index + 4 * SrcPacketSize); + SrcPacket src6 = m_impl.template packet(index + 5 * SrcPacketSize); + SrcPacket src7 = m_impl.template packet(index + 6 * SrcPacketSize); + SrcPacket src8 = m_impl.template packet(index + 7 * SrcPacketSize); + TgtPacket result = internal::pcast(src1, src2, src3, src4, src5, src6, src7, src8); + return result; + } + + private: + const TensorEvaluator& m_impl; +}; + +template +struct PacketConverter { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketConverter(const TensorEvaluator& impl) + : m_impl(impl), m_maxIndex(impl.dimensions().TotalSize()) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TgtPacket packet(Index index) const { + const int SrcPacketSize = internal::unpacket_traits::size; + // Only call m_impl.packet() when we have direct access to the underlying data. This + // ensures that we don't compute the subexpression twice. We may however load some + // coefficients twice, but in practice this doesn't negatively impact performance. + if (m_impl.data() && (index + SrcPacketSize < m_maxIndex)) { + // Force unaligned memory loads since we can't ensure alignment anymore + return internal::pcast(m_impl.template packet(index)); + } else { + const int TgtPacketSize = internal::unpacket_traits::size; + typedef typename internal::unpacket_traits::type SrcType; + typedef typename internal::unpacket_traits::type TgtType; + internal::scalar_cast_op converter; + EIGEN_ALIGN_MAX typename internal::unpacket_traits::type values[TgtPacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < TgtPacketSize; ++i) { + values[i] = converter(m_impl.coeff(index+i)); + } + TgtPacket rslt = internal::pload(values); + return rslt; + } + } + + private: + const TensorEvaluator& m_impl; + const typename TensorEvaluator::Index m_maxIndex; +}; + +template +class TensorConversionOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef typename internal::nested::type Nested; + typedef Scalar CoeffReturnType; + typedef typename NumTraits::Real RealScalar; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConversionOp(const XprType& xpr) + : m_xpr(xpr) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; +}; + +template struct ConversionSubExprEval { + static EIGEN_STRONG_INLINE bool run(Eval& impl, EvalPointerType) { + impl.evalSubExprsIfNeeded(NULL); + return true; + } +}; + +template struct ConversionSubExprEval { + static EIGEN_STRONG_INLINE bool run(Eval& impl, EvalPointerType data) { + return impl.evalSubExprsIfNeeded(data); + } +}; + +#ifdef EIGEN_USE_THREADS +template +struct ConversionSubExprEvalAsync { + static EIGEN_STRONG_INLINE void run(Eval& impl, EvalPointerType, EvalSubExprsCallback done) { + impl.evalSubExprsIfNeededAsync(nullptr, std::move(done)); + } +}; + +template +struct ConversionSubExprEvalAsync { + static EIGEN_STRONG_INLINE void run(Eval& impl, EvalPointerType data, EvalSubExprsCallback done) { + impl.evalSubExprsIfNeededAsync(data, std::move(done)); + } +}; +#endif + +namespace internal { + +template +struct CoeffConv { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetType run(const TensorEvaluator& impl, Index index) { + internal::scalar_cast_op converter; + return converter(impl.coeff(index)); + } +}; + +template +struct CoeffConv { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetType run(const TensorEvaluator& impl, Index index) { + return impl.coeff(index); + } +}; + +template +struct PacketConv { + typedef typename internal::unpacket_traits::type SrcType; + typedef typename internal::unpacket_traits::type TargetType; + + static constexpr int PacketSize = internal::unpacket_traits::size; + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator& impl, Index index) { + internal::scalar_cast_op converter; + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = converter(impl.coeff(index+i)); + } + TargetPacket rslt = internal::pload(values); + return rslt; + } +}; + +template +struct PacketConv { + typedef typename internal::unpacket_traits::type SrcType; + typedef typename internal::unpacket_traits::type TargetType; + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator& impl, Index index) { + const int SrcCoeffRatio = internal::type_casting_traits::SrcCoeffRatio; + const int TgtCoeffRatio = internal::type_casting_traits::TgtCoeffRatio; + PacketConverter, SrcPacket, TargetPacket, + SrcCoeffRatio, TgtCoeffRatio> converter(impl); + return converter.template packet(index); + } +}; + +template +struct PacketConv { + typedef typename internal::unpacket_traits::type TargetType; + static constexpr int PacketSize = internal::unpacket_traits::size; + + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator& impl, Index index) { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + for (int i = 0; i < PacketSize; ++i) values[i] = impl.coeff(index+i); + return internal::pload(values); + } +}; + +template +struct PacketConv { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TargetPacket run(const TensorEvaluator& impl, Index index) { + return impl.template packet(index); + } +}; + +} // namespace internal + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorConversionOp XprType; + typedef typename XprType::Index Index; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef TargetType Scalar; + typedef TargetType CoeffReturnType; + typedef internal::remove_all_t::Scalar> SrcType; + typedef typename PacketType::type PacketReturnType; + typedef typename PacketType::type PacketSourceType; + static constexpr int PacketSize = PacketType::size; + static constexpr bool IsSameType = internal::is_same::value; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + enum { + IsAligned = false, + PacketAccess = + #ifndef EIGEN_USE_SYCL + true, + #else + TensorEvaluator::PacketAccess & + internal::type_casting_traits::VectorizedCast, + #endif + BlockAccess = TensorEvaluator::BlockAccess, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + RawAccess = false + }; + + static constexpr int Layout = TensorEvaluator::Layout; + static constexpr int NumDims = internal::array_size::value; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + struct TensorConversionOpBlockFactory { + template + struct XprType { + typedef TensorConversionOp type; + }; + + template + typename XprType::type expr(const ArgXprType& expr) const { + return typename XprType::type(expr); + } + }; + + typedef internal::TensorUnaryExprBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device) + { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_impl.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) + { + return ConversionSubExprEval, EvaluatorPointerType>::run(m_impl, data); + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType data, EvalSubExprsCallback done) { + ConversionSubExprEvalAsync, + EvaluatorPointerType, + EvalSubExprsCallback>::run(m_impl, data, std::move(done)); + } +#endif + + EIGEN_STRONG_INLINE void cleanup() + { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return internal::CoeffConv::run(m_impl,index); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType + packet(Index index) const { + // If we are not going to do the cast, we just need to check that base + // TensorEvaluator has packet access. Otherwise we also need to make sure, + // that we have an implementation of vectorized cast. + const bool Vectorizable = + IsSameType + ? TensorEvaluator::PacketAccess + : int(TensorEvaluator::PacketAccess) & + int(internal::type_casting_traits::VectorizedCast); + + return internal::PacketConv::run(m_impl, index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double cast_cost = TensorOpCost::CastCost(); + if (vectorized) { + const double SrcCoeffRatio = + internal::type_casting_traits::SrcCoeffRatio; + const double TgtCoeffRatio = + internal::type_casting_traits::TgtCoeffRatio; + return m_impl.costPerCoeff(vectorized) * (SrcCoeffRatio / PacketSize) + + TensorOpCost(0, 0, TgtCoeffRatio * (cast_cost / PacketSize)); + } else { + return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, cast_cost); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return m_impl.getResourceRequirements(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + return TensorBlock(m_impl.block(desc, scratch), + TensorConversionOpBlockFactory()); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + /// required by sycl in order to extract the sycl accessor + const TensorEvaluator& impl() const { return m_impl; } + + protected: + TensorEvaluator m_impl; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONVERSION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e586b7bf9c1ef9e9667266bc1367c06976d29c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h @@ -0,0 +1,1135 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorConvolution + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor convolution class. + * + * + */ +namespace internal { + +template +class IndexMapper { + public: + IndexMapper(const InputDims& input_dims, const array& kernel_dims, + const array& indices) { + + array dimensions = input_dims; + for (int i = 0; i < NumKernelDims; ++i) { + const Index index = indices[i]; + const Index input_dim = input_dims[index]; + const Index kernel_dim = kernel_dims[i]; + const Index result_dim = input_dim - kernel_dim + 1; + dimensions[index] = result_dim; + } + + array inputStrides; + array outputStrides; + if (static_cast(Layout) == static_cast(ColMajor)) { + inputStrides[0] = 1; + outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + inputStrides[i] = inputStrides[i-1] * input_dims[i-1]; + outputStrides[i] = outputStrides[i-1] * dimensions[i-1]; + } + } else { + inputStrides[NumDims - 1] = 1; + outputStrides[NumDims - 1] = 1; + for (int i = static_cast(NumDims) - 2; i >= 0; --i) { + inputStrides[i] = inputStrides[i + 1] * input_dims[i + 1]; + outputStrides[i] = outputStrides[i + 1] * dimensions[i + 1]; + } + } + + array gpuInputDimensions; + array gpuOutputDimensions; + array tmp = dimensions; + array ordering; + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + for (int i = 0; i < NumKernelDims; ++i) { + const Index index = i + offset; + ordering[index] = indices[i]; + tmp[indices[i]] = -1; + gpuInputDimensions[index] = input_dims[indices[i]]; + gpuOutputDimensions[index] = dimensions[indices[i]]; + } + + int written = static_cast(Layout) == static_cast(ColMajor) + ? NumKernelDims + : 0; + for (int i = 0; i < NumDims; ++i) { + if (tmp[i] >= 0) { + ordering[written] = i; + gpuInputDimensions[written] = input_dims[i]; + gpuOutputDimensions[written] = dimensions[i]; + ++written; + } + } + + for (int i = 0; i < NumDims; ++i) { + m_inputStrides[i] = inputStrides[ordering[i]]; + m_outputStrides[i] = outputStrides[ordering[i]]; + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < NumDims; ++i) { + if (i > NumKernelDims) { + m_gpuInputStrides[i] = + m_gpuInputStrides[i - 1] * gpuInputDimensions[i - 1]; + m_gpuOutputStrides[i] = + m_gpuOutputStrides[i - 1] * gpuOutputDimensions[i - 1]; + } else { + m_gpuInputStrides[i] = 1; + m_gpuOutputStrides[i] = 1; + } + } + } else { + for (int i = NumDims - 1; i >= 0; --i) { + if (static_cast(i + 1) < offset) { + m_gpuInputStrides[i] = + m_gpuInputStrides[i + 1] * gpuInputDimensions[i + 1]; + m_gpuOutputStrides[i] = + m_gpuOutputStrides[i + 1] * gpuOutputDimensions[i + 1]; + } else { + m_gpuInputStrides[i] = 1; + m_gpuOutputStrides[i] = 1; + } + } + } + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputPlaneToTensorInputOffset(Index p) const { + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int d = NumDims - 1; d > NumKernelDims; --d) { + const Index idx = p / m_gpuInputStrides[d]; + inputIndex += idx * m_inputStrides[d]; + p -= idx * m_gpuInputStrides[d]; + } + if (NumKernelDims < NumDims) { + inputIndex += p * m_inputStrides[NumKernelDims]; + } + } else { + std::ptrdiff_t limit = 0; + if (NumKernelDims < NumDims) { + limit = NumDims - NumKernelDims - 1; + } + for (int d = 0; d < limit; ++d) { + const Index idx = p / m_gpuInputStrides[d]; + inputIndex += idx * m_inputStrides[d]; + p -= idx * m_gpuInputStrides[d]; + } + inputIndex += p * m_inputStrides[limit]; + } + return inputIndex; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputPlaneToTensorOutputOffset(Index p) const { + Index outputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int d = NumDims - 1; d > NumKernelDims; --d) { + const Index idx = p / m_gpuOutputStrides[d]; + outputIndex += idx * m_outputStrides[d]; + p -= idx * m_gpuOutputStrides[d]; + } + if (NumKernelDims < NumDims) { + outputIndex += p * m_outputStrides[NumKernelDims]; + } + } else { + std::ptrdiff_t limit = 0; + if (NumKernelDims < NumDims) { + limit = NumDims - NumKernelDims - 1; + } + for (int d = 0; d < limit; ++d) { + const Index idx = p / m_gpuOutputStrides[d]; + outputIndex += idx * m_outputStrides[d]; + p -= idx * m_gpuOutputStrides[d]; + } + outputIndex += p * m_outputStrides[limit]; + } + return outputIndex; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_inputStrides[offset]; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_outputStrides[offset]; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i, Index j) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_inputStrides[offset] + j * m_inputStrides[offset + 1]; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i, Index j) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_outputStrides[offset] + j * m_outputStrides[offset + 1]; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuInputKernelToTensorInputOffset(Index i, Index j, Index k) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_inputStrides[offset] + j * m_inputStrides[offset + 1] + + k * m_inputStrides[offset + 2]; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Index mapGpuOutputKernelToTensorOutputOffset(Index i, Index j, Index k) const { + const size_t offset = static_cast(Layout) == static_cast(ColMajor) + ? 0 + : NumDims - NumKernelDims; + return i * m_outputStrides[offset] + j * m_outputStrides[offset + 1] + + k * m_outputStrides[offset + 2]; + } + + private: + static constexpr int NumDims = internal::array_size::value; + array m_inputStrides; + array m_outputStrides; + array m_gpuInputStrides; + array m_gpuOutputStrides; +}; + + + +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef typename promote_storage_type::ret Scalar; + typedef typename promote_storage_type::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename InputXprType::Nested LhsNested; + typedef typename KernelXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = traits::Layout; + typedef std::conditional_t::val, + typename traits::PointerType, typename traits::PointerType> PointerType; + + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorConvolutionOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorConvolutionOp type; +}; + +} // end namespace internal + + + +template +class TensorConvolutionOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename internal::promote_storage_type::ret CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConvolutionOp(const InputXprType& input, const KernelXprType& kernel, const Indices& dims) + : m_input_xpr(input), m_kernel_xpr(kernel), m_indices(dims) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Indices& indices() const { return m_indices; } + + /** \returns the nested expressions */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const internal::remove_all_t& + inputExpression() const { return m_input_xpr; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const internal::remove_all_t& + kernelExpression() const { return m_kernel_xpr; } + + protected: + typename InputXprType::Nested m_input_xpr; + typename KernelXprType::Nested m_kernel_xpr; + const Indices m_indices; +}; + + +template +struct TensorEvaluator, Device> +{ + typedef TensorConvolutionOp XprType; + + static constexpr int NumDims = internal::array_size::Dimensions>::value; + static constexpr int NumKernelDims = internal::array_size::value; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = int(TensorEvaluator::IsAligned) & int(TensorEvaluator::IsAligned), + PacketAccess = int(TensorEvaluator::PacketAccess) & int(TensorEvaluator::PacketAccess), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_inputImpl(op.inputExpression(), device), m_kernelImpl(op.kernelExpression(), device), m_kernelArg(op.kernelExpression()), m_kernel(NULL), m_local_kernel(false), m_device(device) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE); + + const typename TensorEvaluator::Dimensions& input_dims = m_inputImpl.dimensions(); + const typename TensorEvaluator::Dimensions& kernel_dims = m_kernelImpl.dimensions(); + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputStride[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_inputStride[i] = m_inputStride[i - 1] * input_dims[i - 1]; + } + } else { + m_inputStride[NumDims - 1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_inputStride[i] = m_inputStride[i + 1] * input_dims[i + 1]; + } + } + + m_dimensions = m_inputImpl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < NumKernelDims; ++i) { + const Index index = op.indices()[i]; + const Index input_dim = input_dims[index]; + const Index kernel_dim = kernel_dims[i]; + const Index result_dim = input_dim - kernel_dim + 1; + m_dimensions[index] = result_dim; + if (i > 0) { + m_kernelStride[i] = m_kernelStride[i - 1] * kernel_dims[i - 1]; + } else { + m_kernelStride[0] = 1; + } + m_indexStride[i] = m_inputStride[index]; + } + + m_outputStride[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStride[i] = m_outputStride[i - 1] * m_dimensions[i - 1]; + } + } else { + for (int i = NumKernelDims - 1; i >= 0; --i) { + const Index index = op.indices()[i]; + const Index input_dim = input_dims[index]; + const Index kernel_dim = kernel_dims[i]; + const Index result_dim = input_dim - kernel_dim + 1; + m_dimensions[index] = result_dim; + if (i < NumKernelDims - 1) { + m_kernelStride[i] = m_kernelStride[i + 1] * kernel_dims[i + 1]; + } else { + m_kernelStride[NumKernelDims - 1] = 1; + } + m_indexStride[i] = m_inputStride[index]; + } + + m_outputStride[NumDims - 1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_outputStride[i] = m_outputStride[i + 1] * m_dimensions[i + 1]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar*) { + m_inputImpl.evalSubExprsIfNeeded(NULL); + preloadKernel(); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_inputImpl.cleanup(); + if (m_local_kernel) { + m_device.deallocate((void*)m_kernel); + m_local_kernel = false; + } + m_kernel = NULL; + } + + void evalTo(typename XprType::Scalar* buffer) { + evalSubExprsIfNeeded(NULL); + for (int i = 0; i < dimensions().TotalSize(); ++i) { + buffer[i] += coeff(i); + } + cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + CoeffReturnType result = CoeffReturnType(0); + convolve(firstInput(index), 0, NumKernelDims-1, result); + return result; + } + + template + EIGEN_DEVICE_FUNC PacketReturnType packet(const Index index) const + { + Index indices[2] = {index, index+PacketSize-1}; + Index startInputs[2] = {0, 0}; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + const Index idx0 = indices[0] / m_outputStride[i]; + const Index idx1 = indices[1] / m_outputStride[i]; + startInputs[0] += idx0 * m_inputStride[i]; + startInputs[1] += idx1 * m_inputStride[i]; + indices[0] -= idx0 * m_outputStride[i]; + indices[1] -= idx1 * m_outputStride[i]; + } + } else { + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx0 = indices[0] / m_outputStride[i]; + const Index idx1 = indices[1] / m_outputStride[i]; + startInputs[0] += idx0 * m_inputStride[i]; + startInputs[1] += idx1 * m_inputStride[i]; + indices[0] -= idx0 * m_outputStride[i]; + indices[1] -= idx1 * m_outputStride[i]; + } + } + startInputs[0] += indices[0]; + startInputs[1] += indices[1]; + + if (startInputs[1]-startInputs[0] == PacketSize-1) { + PacketReturnType result = internal::pset1(0); + convolvePacket(startInputs[0], 0, NumKernelDims-1, result); + return result; + } else { + EIGEN_ALIGN_MAX Scalar data[PacketSize]; + data[0] = Scalar(0); + convolve(startInputs[0], 0, NumKernelDims-1, data[0]); + for (int i = 1; i < PacketSize-1; ++i) { + data[i] = Scalar(0); + convolve(firstInput(index+i), 0, NumKernelDims-1, data[i]); + } + data[PacketSize-1] = Scalar(0); + convolve(startInputs[1], 0, NumKernelDims-1, data[PacketSize-1]); + return internal::pload(data); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double kernel_size = m_kernelImpl.dimensions().TotalSize(); + // We ignore the use of fused multiply-add. + const double convolve_compute_cost = + TensorOpCost::AddCost() + TensorOpCost::MulCost(); + const double firstIndex_compute_cost = + NumDims * + (2 * TensorOpCost::AddCost() + 2 * TensorOpCost::MulCost() + + TensorOpCost::DivCost()); + return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) + + kernel_size * (m_inputImpl.costPerCoeff(vectorized) + + m_kernelImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, convolve_compute_cost, vectorized, + PacketSize)); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + private: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index firstInput(Index index) const { + Index startInput = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStride[i]; + startInput += idx * m_inputStride[i]; + index -= idx * m_outputStride[i]; + } + } else { + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStride[i]; + startInput += idx * m_inputStride[i]; + index -= idx * m_outputStride[i]; + } + } + startInput += index; + return startInput; + } + + EIGEN_DEVICE_FUNC void convolve(Index firstIndex, Index firstKernel, int DimIndex, CoeffReturnType& accum) const { + for (int j = 0; j < m_kernelImpl.dimensions()[DimIndex]; ++j) { + const Index input = firstIndex + j * m_indexStride[DimIndex]; + const Index kernel = firstKernel + j * m_kernelStride[DimIndex]; + if (DimIndex > 0) { + convolve(input, kernel, DimIndex-1, accum); + } else { + accum += m_inputImpl.coeff(input) * m_kernel[kernel]; + } + } + } + + template + EIGEN_DEVICE_FUNC void convolvePacket(Index firstIndex, Index firstKernel, int DimIndex, Packet& accum) const { + for (int j = 0; j < m_kernelImpl.dimensions()[DimIndex]; ++j) { + const Index input = firstIndex + j * m_indexStride[DimIndex]; + const Index kernel = firstKernel + j * m_kernelStride[DimIndex]; + if (DimIndex > 0) { + convolvePacket(input, kernel, DimIndex-1, accum); + } else { + accum = internal::pmadd(m_inputImpl.template packet(input), internal::pset1(m_kernel[kernel]), accum); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void preloadKernel() { + // Don't make a local copy of the kernel unless we have to (i.e. it's an + // expression that needs to be evaluated) + const Scalar* in_place = m_kernelImpl.data(); + if (in_place) { + m_kernel = in_place; + m_local_kernel = false; + } else { + size_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar); + Scalar* local = (Scalar*)m_device.allocate_temp(kernel_sz); + typedef TensorEvalToOp EvalTo; + EvalTo evalToTmp(local, m_kernelArg); + const bool Vectorize = internal::IsVectorizable::value; + internal::TensorExecutor::run(evalToTmp, m_device); + + m_kernel = local; + m_local_kernel = true; + } + } + + array m_inputStride; + array m_outputStride; + + array m_indexStride; + array m_kernelStride; + TensorEvaluator m_inputImpl; + TensorEvaluator m_kernelImpl; + Dimensions m_dimensions; + + KernelArgType m_kernelArg; + const Scalar* m_kernel; + bool m_local_kernel; + const Device EIGEN_DEVICE_REF m_device; +}; + + + + +// Use an optimized implementation of the evaluation code for GPUs whenever possible. +#if defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC) + +template +struct GetKernelSize { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int operator() (const int /*kernelSize*/) const { + return StaticKernelSize; + } +}; +template <> +struct GetKernelSize { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int operator() (const int kernelSize) const { + return kernelSize; + } +}; + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel1D( + InputEvaluator eval, + const internal::IndexMapper + indexMapper, + const float* __restrict kernel, const int numPlanes, const int numX, + const int maxX, const int kernelSize, float* buffer) { +#if defined(EIGEN_HIPCC) + HIP_DYNAMIC_SHARED(float, s) +#else + extern __shared__ float s[]; +#endif + + const int first_x = blockIdx.x * maxX; + const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1; + const int num_x_input = last_x - first_x + GetKernelSize()(kernelSize); + const int num_x_output = last_x - first_x + 1; + + const int first_plane = blockIdx.y * blockDim.y; + const int plane_stride = blockDim.y * gridDim.y; + + for (int p = first_plane + threadIdx.y; p < numPlanes; p += plane_stride) { + // Load inputs to shared memory + const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p); + const int plane_kernel_offset = threadIdx.y * num_x_input; + #pragma unroll + for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) { + const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x); + s[i + plane_kernel_offset] = eval.coeff(tensor_index); + } + + __syncthreads(); + + // Compute the convolution + const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p); + + #pragma unroll + for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) { + const int kernel_offset = plane_kernel_offset + i; + float result = 0.0f; + #pragma unroll + for (int k = 0; k < GetKernelSize()(kernelSize); ++k) { + result += s[k + kernel_offset] * kernel[k]; + } + const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x); + buffer[tensor_index] = result; + } + __syncthreads(); + } +}; + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel2D( + InputEvaluator eval, + const internal::IndexMapper + indexMapper, + const float* __restrict kernel, const int numPlanes, const int numX, + const int maxX, const int numY, const int maxY, const int kernelSizeX, + const int kernelSizeY, float* buffer) { +#if defined(EIGEN_HIPCC) + HIP_DYNAMIC_SHARED(float, s) +#else + extern __shared__ float s[]; +#endif + + const int first_x = blockIdx.x * maxX; + const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1; + const int num_x_input = last_x - first_x + GetKernelSize()(kernelSizeX); + const int num_x_output = last_x - first_x + 1; + + const int first_y = blockIdx.y * maxY; + const int last_y = (first_y + maxY < numY ? first_y + maxY : numY) - 1; + const int num_y_input = last_y - first_y + GetKernelSize()(kernelSizeY); + const int num_y_output = last_y - first_y + 1; + + const int first_plane = blockIdx.z * blockDim.z; + const int plane_stride = blockDim.z * gridDim.z; + + for (int p = first_plane + threadIdx.z; p < numPlanes; p += plane_stride) { + + const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p); + const int plane_kernel_offset = threadIdx.z * num_y_input; + + // Load inputs to shared memory + #pragma unroll + for (int j = threadIdx.y; j < num_y_input; j += blockDim.y) { + const int input_offset = num_x_input * (j + plane_kernel_offset); + #pragma unroll + for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) { + const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x, j+first_y); + s[i + input_offset] = eval.coeff(tensor_index); + } + } + + __syncthreads(); + + // Convolution + const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p); + + #pragma unroll + for (int j = threadIdx.y; j < num_y_output; j += blockDim.y) { + #pragma unroll + for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) { + float result = 0.0f; + #pragma unroll + for (int l = 0; l < GetKernelSize()(kernelSizeY); ++l) { + const int kernel_offset = kernelSizeX * l; + const int input_offset = i + num_x_input * (j + l + plane_kernel_offset); + #pragma unroll + for (int k = 0; k < GetKernelSize()(kernelSizeX); ++k) { + result += s[k + input_offset] * kernel[k + kernel_offset]; + } + } + const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x, j+first_y); + buffer[tensor_index] = result; + } + } + + __syncthreads(); + } +}; + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void EigenConvolutionKernel3D( + InputEvaluator eval, + const internal::IndexMapper + indexMapper, + const float* __restrict kernel, const size_t numPlanes, const size_t numX, + const size_t maxX, const size_t numY, const size_t maxY, const size_t numZ, + const size_t maxZ, const size_t kernelSizeX, const size_t kernelSizeY, + const size_t kernelSizeZ, float* buffer) { +#if defined(EIGEN_HIPCC) + HIP_DYNAMIC_SHARED(float, s) +#else + extern __shared__ float s[]; +#endif + + // Load inputs to shared memory + const int first_x = blockIdx.x * maxX; + const int last_x = (first_x + maxX < numX ? first_x + maxX : numX) - 1; + const int num_x_input = last_x - first_x + kernelSizeX; + + const int first_y = blockIdx.y * maxY; + const int last_y = (first_y + maxY < numY ? first_y + maxY : numY) - 1; + const int num_y_input = last_y - first_y + kernelSizeY; + + const int first_z = blockIdx.z * maxZ; + const int last_z = (first_z + maxZ < numZ ? first_z + maxZ : numZ) - 1; + const int num_z_input = last_z - first_z + kernelSizeZ; + + for (int p = 0; p < numPlanes; ++p) { + + const int plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p); + const int plane_kernel_offset = 0; + + for (int k = threadIdx.z; k < num_z_input; k += blockDim.z) { + for (int j = threadIdx.y; j < num_y_input; j += blockDim.y) { + for (int i = threadIdx.x; i < num_x_input; i += blockDim.x) { + const int tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i+first_x, j+first_y, k+first_z); + s[i + num_x_input * (j + num_y_input * (k + plane_kernel_offset))] = eval.coeff(tensor_index); + } + } + } + + __syncthreads(); + + // Convolution + const int num_z_output = last_z - first_z + 1; + const int num_y_output = last_y - first_y + 1; + const int num_x_output = last_x - first_x + 1; + const int plane_output_offset = indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p); + + for (int k = threadIdx.z; k < num_z_output; k += blockDim.z) { + for (int j = threadIdx.y; j < num_y_output; j += blockDim.y) { + for (int i = threadIdx.x; i < num_x_output; i += blockDim.x) { + float result = 0.0f; + for (int n = 0; n < kernelSizeZ; ++n) { + for (int m = 0; m < kernelSizeY; ++m) { + for (int l = 0; l < kernelSizeX; ++l) { + result += s[i + l + num_x_input * (j + m + num_y_input * (k + n + plane_kernel_offset))] * kernel[l + kernelSizeX * (m + kernelSizeY * n)]; + } + } + } + const int tensor_index = plane_output_offset + indexMapper.mapGpuOutputKernelToTensorOutputOffset(i+first_x, j+first_y, k+first_z); + buffer[tensor_index] = result; + } + } + } + __syncthreads(); + } +}; + + + +template +struct TensorEvaluator, GpuDevice> +{ + typedef TensorConvolutionOp XprType; + + static constexpr int NumDims = internal::array_size::Dimensions>::value; + static constexpr int NumKernelDims = internal::array_size::value; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + typedef typename TensorEvaluator::Dimensions KernelDimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned & TensorEvaluator::IsAligned, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + TensorEvaluator(const XprType& op, const GpuDevice& device) + : m_inputImpl(op.inputExpression(), device), m_kernelImpl(op.kernelExpression(), device), m_kernelArg(op.kernelExpression()), m_indices(op.indices()), m_buf(NULL), m_kernel(NULL), m_local_kernel(false), m_device(device) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE); + + const typename TensorEvaluator::Dimensions& input_dims = m_inputImpl.dimensions(); + const typename TensorEvaluator::Dimensions& kernel_dims = m_kernelImpl.dimensions(); + + m_dimensions = m_inputImpl.dimensions(); + for (int i = 0; i < NumKernelDims; ++i) { + const Index index = op.indices()[i]; + const Index input_dim = input_dims[index]; + const Index kernel_dim = kernel_dims[i]; + const Index result_dim = input_dim - kernel_dim + 1; + m_dimensions[index] = result_dim; + } + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename InputArgType::Scalar Scalar; + static constexpr int PacketSize = internal::unpacket_traits::size; + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar* data) { + preloadKernel(); + m_inputImpl.evalSubExprsIfNeeded(NULL); + if (data) { + executeEval(data); + return false; + } else { + m_buf = (Scalar*)m_device.allocate(dimensions().TotalSize() * sizeof(Scalar)); + executeEval(m_buf); + return true; + } + } + + EIGEN_STRONG_INLINE void cleanup() { + m_inputImpl.cleanup(); + if (m_buf) { + m_device.deallocate(m_buf); + m_buf = NULL; + } + if (m_local_kernel) { + m_device.deallocate((void*)m_kernel); + m_local_kernel = false; + } + m_kernel = NULL; + } + + EIGEN_STRONG_INLINE void preloadKernel() { + // Don't make a local copy of the kernel unless we have to (i.e. it's an + // expression that needs to be evaluated) + const Scalar* in_place = m_kernelImpl.data(); + if (in_place) { + m_kernel = in_place; + m_local_kernel = false; + } else { + size_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar); + Scalar* local = (Scalar*)m_device.allocate(kernel_sz); + typedef TensorEvalToOp EvalTo; + EvalTo evalToTmp(local, m_kernelArg); + const bool PacketAccess = internal::IsVectorizable::value; + internal::TensorExecutor::run(evalToTmp, m_device); + + m_kernel = local; + m_local_kernel = true; + } + } + + static unsigned int ceil(unsigned int num, unsigned int denom) { + const unsigned int rounded_toward_zero = num / denom; + if (num > rounded_toward_zero * denom) { + return rounded_toward_zero + 1; + } + return rounded_toward_zero; + } + + void executeEval(Scalar* data) const { + typedef typename TensorEvaluator::Dimensions InputDims; + + const int maxSharedMem = m_device.sharedMemPerBlock(); + const int maxThreadsPerBlock = m_device.maxGpuThreadsPerBlock(); + const int maxBlocksPerProcessor = m_device.maxGpuThreadsPerMultiProcessor() / maxThreadsPerBlock; + const int numMultiProcessors = m_device.getNumGpuMultiProcessors(); + const int warpSize = 32; + + switch (NumKernelDims) { + case 1: { + const int kernel_size = m_kernelImpl.dimensions().TotalSize(); + + const int numX = dimensions()[m_indices[0]]; + const int numP = dimensions().TotalSize() / numX; + int maxX; + dim3 block_size; + + const int single_stride_dim = + static_cast(Layout) == static_cast(ColMajor) + ? 0 + : m_inputImpl.dimensions().rank() - 1; + if (m_indices[0] == single_stride_dim) { + // Maximum the reuse + const int inner_dim = ((maxSharedMem / (sizeof(Scalar)) - kernel_size + 1 + 31) / 32) * 32; + maxX = numext::mini(inner_dim, numX); + const int maxP = numext::mini(maxSharedMem / ((kernel_size - 1 + maxX) * sizeof(Scalar)), numP); + block_size.x = numext::mini(maxThreadsPerBlock, maxX); + block_size.y = numext::mini(maxThreadsPerBlock / block_size.x, maxP); + } + else { + // Read as much as possible alongside the inner most dimension, that is the plane + const int inner_dim = maxSharedMem / ((warpSize + kernel_size) * sizeof(Scalar)); + const int maxP = numext::mini(inner_dim, numP); + maxX = numext::mini(maxSharedMem / (inner_dim * sizeof(Scalar)) - kernel_size + 1, numX); + + block_size.x = numext::mini(warpSize, maxX); + block_size.y = numext::mini(maxThreadsPerBlock/block_size.x, maxP); + } + + const int shared_mem = block_size.y * (maxX + kernel_size - 1) * sizeof(Scalar); + gpu_assert(shared_mem <= maxSharedMem); + + const int num_x_blocks = ceil(numX, maxX); + const int blocksPerProcessor = numext::mini(maxBlocksPerProcessor, maxSharedMem / shared_mem); + const int num_y_blocks = ceil(numMultiProcessors * blocksPerProcessor, num_x_blocks); + + dim3 num_blocks(num_x_blocks, numext::mini(num_y_blocks, ceil(numP, block_size.y))); + + + //cout << "launching 1D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " maxX: " << maxX << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl; + + const array indices(m_indices[0]); + const array kernel_dims(m_kernelImpl.dimensions()[0]); + internal::IndexMapper indexMapper( + m_inputImpl.dimensions(), kernel_dims, indices); + switch(kernel_size) { + case 4: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D, Index, InputDims, 4>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, 4, data); + break; + } + case 7: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D, Index, InputDims, 7>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, 7, data); + break; + } + default: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel1D, Index, InputDims, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, kernel_size, data); + } + } + break; + } + + case 2: { + const int idxX = + static_cast(Layout) == static_cast(ColMajor) ? 0 : 1; + const int idxY = + static_cast(Layout) == static_cast(ColMajor) ? 1 : 0; + const int kernel_size_x = m_kernelImpl.dimensions()[idxX]; + const int kernel_size_y = m_kernelImpl.dimensions()[idxY]; + + const int numX = dimensions()[m_indices[idxX]]; + const int numY = dimensions()[m_indices[idxY]]; + const int numP = dimensions().TotalSize() / (numX*numY); + + const float scaling_factor = sqrtf(static_cast(maxSharedMem) / (sizeof(Scalar) * kernel_size_y * kernel_size_x)); + + // Snap maxX to warp size + int inner_dim = ((static_cast(scaling_factor * kernel_size_x) - kernel_size_x + 1 + 32) / 32) * 32; + const int maxX = numext::mini(inner_dim, numX); + const int maxY = numext::mini(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1)) - kernel_size_y + 1, numY); + const int maxP = numext::mini(maxSharedMem / ((kernel_size_x - 1 + maxX) * (kernel_size_y - 1 + maxY) * sizeof(Scalar)), numP); + + dim3 block_size; + block_size.x = numext::mini(1024, maxX); + block_size.y = numext::mini(1024/block_size.x, maxY); + block_size.z = numext::mini(1024/(block_size.x*block_size.y), maxP); + + const int shared_mem = block_size.z * (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1) * sizeof(Scalar); + gpu_assert(shared_mem <= maxSharedMem); + + const int num_x_blocks = ceil(numX, maxX); + const int num_y_blocks = ceil(numY, maxY); + const int blocksPerProcessor = numext::mini(maxBlocksPerProcessor, maxSharedMem / shared_mem); + const int num_z_blocks = ceil(numMultiProcessors * blocksPerProcessor, num_x_blocks * num_y_blocks); + + dim3 num_blocks(num_x_blocks, num_y_blocks, numext::mini(num_z_blocks, ceil(numP, block_size.z))); + + + //cout << "launching 2D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " block_size.z: " << block_size.z << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " num_blocks.z: " << num_blocks.z << " maxX: " << maxX << " maxY: " << maxY << " maxP: " << maxP << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl; + + const array indices(m_indices[idxX], m_indices[idxY]); + const array kernel_dims(m_kernelImpl.dimensions()[idxX], + m_kernelImpl.dimensions()[idxY]); + internal::IndexMapper indexMapper( + m_inputImpl.dimensions(), kernel_dims, indices); + switch (kernel_size_x) { + case 4: { + switch (kernel_size_y) { + case 7: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D, Index, InputDims, 4, 7>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 4, 7, data); + break; + } + default: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D, Index, InputDims, 4, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 4, kernel_size_y, data); + break; + } + } + break; + } + case 7: { + switch (kernel_size_y) { + case 4: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D, Index, InputDims, 7, 4>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 7, 4, data); + break; + } + default: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D, Index, InputDims, 7, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, 7, kernel_size_y, data); + break; + } + } + break; + } + default: { + LAUNCH_GPU_KERNEL((EigenConvolutionKernel2D, Index, InputDims, Dynamic, Dynamic>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, kernel_size_x, kernel_size_y, data); + break; + } + } + break; + } + + case 3: { + const int idxX = + static_cast(Layout) == static_cast(ColMajor) ? 0 : 2; + const int idxY = + static_cast(Layout) == static_cast(ColMajor) ? 1 : 1; + const int idxZ = + static_cast(Layout) == static_cast(ColMajor) ? 2 : 0; + + const int kernel_size_x = m_kernelImpl.dimensions()[idxX]; + const int kernel_size_y = m_kernelImpl.dimensions()[idxY]; + const int kernel_size_z = m_kernelImpl.dimensions()[idxZ]; + + const int numX = dimensions()[m_indices[idxX]]; + const int numY = dimensions()[m_indices[idxY]]; + const int numZ = dimensions()[m_indices[idxZ]]; + const int numP = dimensions().TotalSize() / (numX*numY*numZ); + + const int maxX = numext::mini(128, numext::mini(maxSharedMem / (sizeof(Scalar) * kernel_size_y * kernel_size_z) - kernel_size_x + 1, numX)); + const int maxY = numext::mini(128, numext::mini(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1) * kernel_size_z) - kernel_size_y + 1, numY)); + const int maxZ = numext::mini(128, numext::mini(maxSharedMem / (sizeof(Scalar) * (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1)) - kernel_size_z + 1, numZ)); + + dim3 block_size; + block_size.x = numext::mini(32, maxX); + block_size.y = numext::mini(32, maxY); + block_size.z = numext::mini(1024/(block_size.x*block_size.y), maxZ); + dim3 num_blocks(ceil(numX, maxX), ceil(numY, maxY), ceil(numZ, maxZ)); + + const int shared_mem = (maxX + kernel_size_x - 1) * (maxY + kernel_size_y - 1) * (maxZ + kernel_size_z - 1) * sizeof(Scalar); + gpu_assert(shared_mem <= maxSharedMem); + + //cout << "launching 3D kernel with block_size.x: " << block_size.x << " block_size.y: " << block_size.y << " block_size.z: " << block_size.z << " num_blocks.x: " << num_blocks.x << " num_blocks.y: " << num_blocks.y << " num_blocks.z: " << num_blocks.z << " shared_mem: " << shared_mem << " in stream " << m_device.stream() << endl; + const array indices(m_indices[idxX], m_indices[idxY], + m_indices[idxZ]); + const array kernel_dims(m_kernelImpl.dimensions()[idxX], + m_kernelImpl.dimensions()[idxY], + m_kernelImpl.dimensions()[idxZ]); + internal::IndexMapper indexMapper( + m_inputImpl.dimensions(), kernel_dims, indices); + + LAUNCH_GPU_KERNEL((EigenConvolutionKernel3D, Index, InputDims>), num_blocks, block_size, shared_mem, m_device, m_inputImpl, indexMapper, m_kernel, numP, numX, maxX, numY, maxY, numZ, maxZ, kernel_size_x, kernel_size_y, kernel_size_z, data); + break; + } + + default: { + EIGEN_STATIC_ASSERT((NumKernelDims >= 1 && NumKernelDims <= 3), THIS_METHOD_IS_ONLY_FOR_OBJECTS_OF_A_SPECIFIC_SIZE); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + eigen_assert(m_buf); + eigen_assert(index < m_dimensions.TotalSize()); + return m_buf[index]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(const Index index) const + { + eigen_assert(m_buf); + eigen_assert(index < m_dimensions.TotalSize()); + return internal::ploadt(m_buf+index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + // TODO(rmlarsen): FIXME: For now, this is just a copy of the CPU cost + // model. + const double kernel_size = m_kernelImpl.dimensions().TotalSize(); + // We ignore the use of fused multiply-add. + const double convolve_compute_cost = + TensorOpCost::AddCost() + TensorOpCost::MulCost(); + const double firstIndex_compute_cost = + NumDims * + (2 * TensorOpCost::AddCost() + 2 * TensorOpCost::MulCost() + + TensorOpCost::DivCost()); + return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) + + kernel_size * (m_inputImpl.costPerCoeff(vectorized) + + m_kernelImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, convolve_compute_cost, vectorized, + PacketSize)); + } + + private: + TensorEvaluator m_inputImpl; + TensorEvaluator m_kernelImpl; + KernelArgType m_kernelArg; + Indices m_indices; + Dimensions m_dimensions; + Scalar* m_buf; + const Scalar* m_kernel; + bool m_local_kernel; + + const GpuDevice& m_device; +}; +#endif + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h new file mode 100644 index 0000000000000000000000000000000000000000..f2795688a1b2370e70b10c0c260b57d7806c9548 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h @@ -0,0 +1,540 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Mehdi Goli Codeplay Software Ltd. +// Ralph Potter Codeplay Software Ltd. +// Luke Iwanski Codeplay Software Ltd. +// Contact: +// Copyright (C) 2016 Benoit Steiner + +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_SYCL_H +#define EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_SYCL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorConvolution + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor convolution class. + * + * + */ + +enum class convolution_type { CONV1D, CONV2D, CONV3D }; +template +struct EigenConvolutionKernel; +template +struct EigenConvolutionKernel { + typedef cl::sycl::accessor + Local_accessor; + Local_accessor local_acc; + Evaluator device_evaluator; + Kernel_accessor kernel_filter; + Buffer_accessor buffer_acc; + internal::IndexMapper indexMapper; + const size_t kernelSize; + const cl::sycl::range<2> input_range; + EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_, + Buffer_accessor buffer_acc_, + internal::IndexMapper indexMapper_, + const size_t kernelSize_, const cl::sycl::range<2> input_range_) + : local_acc(local_acc_), + device_evaluator(device_evaluator_), + kernel_filter(kernel_filter_), + buffer_acc(buffer_acc_), + indexMapper(indexMapper_), + kernelSize(kernelSize_), + input_range(input_range_) {} + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim2 boolean_check) const { + return (boolean_check[0] && boolean_check[1]); + } + void operator()(cl::sycl::nd_item<2> itemID) const { + auto buffer_ptr = buffer_acc; + auto kernel_ptr = kernel_filter; + // the required row to be calculated for the for each plane in shered memory + const size_t num_input = (itemID.get_local_range()[0] + kernelSize - 1); + const size_t plane_kernel_offset = itemID.get_local_id(1) * num_input; + const size_t input_offset = itemID.get_group(0) * itemID.get_local_range()[0]; + const size_t plane_tensor_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(itemID.get_global_id(1)); + /// fill the shared memory + for (size_t i = itemID.get_local_id(0); i < num_input; i += itemID.get_local_range()[0]) { + const size_t local_index = i + plane_kernel_offset; + const size_t tensor_index = + plane_tensor_offset + indexMapper.mapGpuInputKernelToTensorInputOffset(i + input_offset); + + local_acc[local_index] = + (((i + input_offset) < (input_range[0] + kernelSize - 1)) && itemID.get_global_id(1) < input_range[1]) + ? device_evaluator.coeff(tensor_index) + : CoeffReturnType(0); + } + + itemID.barrier(cl::sycl::access::fence_space::local_space); + + // calculate the convolution // output start x + const size_t first_output_start = itemID.get_group(0) * (itemID.get_local_range()[0]); + if (boundary_check(itemID.get_global_id() < input_range)) { + CoeffReturnType result = static_cast(0); + const size_t index = plane_kernel_offset + itemID.get_local_id(0); + for (size_t k = 0; k < kernelSize; ++k) { + result += (local_acc[k + index] * kernel_ptr[k]); + } + const size_t tensor_index = + indexMapper.mapGpuOutputPlaneToTensorOutputOffset(itemID.get_global_id(1)) + + indexMapper.mapGpuOutputKernelToTensorOutputOffset(itemID.get_local_id(0) + first_output_start); + buffer_ptr[tensor_index] = result; + } + } +}; + +template +struct EigenConvolutionKernel { + typedef cl::sycl::accessor + Local_accessor; + Local_accessor local_acc; + Evaluator device_evaluator; + Kernel_accessor kernel_filter; + Buffer_accessor buffer_acc; + internal::IndexMapper indexMapper; + const cl::sycl::range<2> kernel_size; + const cl::sycl::range<3> input_range; + EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_, + Buffer_accessor buffer_acc_, + internal::IndexMapper indexMapper_, + const cl::sycl::range<2> kernel_size_, const cl::sycl::range<3> input_range_) + : local_acc(local_acc_), + device_evaluator(device_evaluator_), + kernel_filter(kernel_filter_), + buffer_acc(buffer_acc_), + indexMapper(indexMapper_), + kernel_size(kernel_size_), + input_range(input_range_) {} + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim3 boolean_check) const { + return (boolean_check[0] && boolean_check[1] && boolean_check[2]); + } + + void operator()(cl::sycl::nd_item<3> itemID) const { + auto buffer_ptr = buffer_acc; + auto kernel_ptr = kernel_filter; + // the required row to be calculated for the for each plane in shered memory + const auto num_input = cl::sycl::range<2>{ + (cl::sycl::range<2>(itemID.get_local_range()[0], itemID.get_local_range()[1]) + kernel_size - 1)}; + + const size_t plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(itemID.get_global_id(2)); + const size_t plane_kernel_offset = itemID.get_local_id(2) * num_input[1]; + + const auto input_offset = cl::sycl::range<2>{itemID.get_group(0) * itemID.get_local_range()[0], + itemID.get_group(1) * itemID.get_local_range()[1]}; + + // fill the local memory + bool in_range_dim2 = itemID.get_global_id(2) < input_range[2]; + for (size_t j = itemID.get_local_id(1); j < num_input[1]; j += itemID.get_local_range()[1]) { + const size_t local_input_offset = num_input[0] * (j + plane_kernel_offset); + bool in_range_dim1 = ((j + input_offset[1]) < (input_range[1] + kernel_size[1] - 1)); + for (size_t i = itemID.get_local_id(0); i < num_input[0]; i += itemID.get_local_range()[0]) { + const size_t local_index = i + local_input_offset; + const size_t tensor_index = plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset( + i + input_offset[0], j + input_offset[1]); + local_acc[local_index] = (((i + input_offset[0]) < (input_range[0] + kernel_size[0] - 1)) && + in_range_dim1 && in_range_dim2) + ? device_evaluator.coeff(tensor_index) + : CoeffReturnType(0); + } + } + + itemID.barrier(cl::sycl::access::fence_space::local_space); + + // output offset start for each thread + const auto output_offset = cl::sycl::range<2>{itemID.get_group(0) * itemID.get_local_range()[0], + itemID.get_group(1) * itemID.get_local_range()[1]}; + + if (boundary_check(itemID.get_global_id() < input_range)) { + CoeffReturnType result = static_cast(0); + + for (size_t j = 0; j < kernel_size[1]; j++) { + size_t kernel_offset = kernel_size[0] * j; + const size_t index = + (num_input[0] * (plane_kernel_offset + j + itemID.get_local_id(1))) + itemID.get_local_id(0); + for (size_t i = 0; i < kernel_size[0]; i++) { + result += (local_acc[i + index] * kernel_ptr[i + kernel_offset]); + } + } + const size_t tensor_index = + indexMapper.mapGpuOutputPlaneToTensorOutputOffset(itemID.get_global_id(2)) + + indexMapper.mapGpuOutputKernelToTensorOutputOffset(itemID.get_local_id(0) + output_offset[0], + itemID.get_local_id(1) + output_offset[1]); + + buffer_ptr[tensor_index] = result; + } + } +}; + +template +struct EigenConvolutionKernel { + typedef cl::sycl::accessor + Local_accessor; + Local_accessor local_acc; + Evaluator device_evaluator; + Kernel_accessor kernel_filter; + Buffer_accessor buffer_acc; + internal::IndexMapper indexMapper; + const cl::sycl::range<3> kernel_size; + const cl::sycl::range<3> input_range; + const size_t numP; + + EigenConvolutionKernel(Local_accessor local_acc_, Evaluator device_evaluator_, Kernel_accessor kernel_filter_, + Buffer_accessor buffer_acc_, + internal::IndexMapper indexMapper_, + const cl::sycl::range<3> kernel_size_, const cl::sycl::range<3> input_range_, + const size_t numP_) + : local_acc(local_acc_), + device_evaluator(device_evaluator_), + kernel_filter(kernel_filter_), + buffer_acc(buffer_acc_), + indexMapper(indexMapper_), + kernel_size(kernel_size_), + input_range(input_range_), + numP(numP_) {} + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool boundary_check(const BooleanDim3 boolean_check) const { + return (boolean_check[0] && boolean_check[1] && boolean_check[2]); + } + void operator()(cl::sycl::nd_item<3> itemID) const { + auto buffer_ptr = buffer_acc; + auto kernel_ptr = kernel_filter; + const auto num_input = cl::sycl::range<3>{itemID.get_local_range() + kernel_size - 1}; + + const auto input_offset = cl::sycl::range<3>{itemID.get_group().get_id() * itemID.get_local_range()}; + + const auto output_offset = + cl::sycl::range<3>{itemID.get_group().get_id() * itemID.get_local_range() + itemID.get_local_id()}; + + for (size_t p = 0; p < numP; p++) { + /// fill the shared memory + const size_t plane_input_offset = indexMapper.mapGpuInputPlaneToTensorInputOffset(p); + for (size_t k = itemID.get_local_id(2); k < num_input[2]; k += itemID.get_local_range()[2]) { + size_t local_index_dim2 = num_input[0] * num_input[1] * k; + bool cond_k_dim = (k + input_offset[2] < (input_range[2] + kernel_size[2] - 1)); + for (size_t j = itemID.get_local_id(1); j < num_input[1]; j += itemID.get_local_range()[1]) { + bool cond_j_dim = cond_k_dim && (j + input_offset[1] < (input_range[1] + kernel_size[1] - 1)); + size_t local_index_dim1 = (num_input[0] * j) + local_index_dim2; + for (size_t i = itemID.get_local_id(0); i < num_input[0]; i += itemID.get_local_range()[0]) { + bool conds = cond_j_dim && (i + input_offset[0] < (input_range[0] + kernel_size[0] - 1)); + const size_t local_index = local_index_dim1 + i; + const size_t tensor_index = + plane_input_offset + indexMapper.mapGpuInputKernelToTensorInputOffset( + i + input_offset[0], j + input_offset[1], k + input_offset[2]); + local_acc[local_index] = conds ? device_evaluator.coeff(tensor_index) : CoeffReturnType(0); + } + } + } + itemID.barrier(cl::sycl::access::fence_space::local_space); + + // calculate the convolution + + if (boundary_check(itemID.get_global_id() < input_range)) { + CoeffReturnType result = static_cast(0); + for (size_t k = 0; k < kernel_size[2]; k++) { + for (size_t j = 0; j < kernel_size[1]; j++) { + for (size_t i = 0; i < kernel_size[0]; i++) { + const size_t kernel_index = i + kernel_size[0] * (j + kernel_size[1] * k); + const size_t local_index = + ((i + itemID.get_local_id(0)) + + num_input[0] * ((j + itemID.get_local_id(1)) + num_input[1] * (k + itemID.get_local_id(2)))); + + result += (local_acc[local_index] * kernel_ptr[kernel_index]); + } + } + } + const size_t tensor_index = + indexMapper.mapGpuOutputPlaneToTensorOutputOffset(p) + + indexMapper.mapGpuOutputKernelToTensorOutputOffset(output_offset[0], output_offset[1], output_offset[2]); + buffer_ptr[tensor_index] = result; + } + + itemID.barrier(cl::sycl::access::fence_space::local_space); + } + } +}; + +template +struct TensorEvaluator, Eigen::SyclDevice> { + typedef TensorConvolutionOp XprType; + + static constexpr int NumDims = + internal::array_size::Dimensions>::value; + static constexpr int NumKernelDims = internal::array_size::value; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + typedef typename TensorEvaluator::Dimensions KernelDimensions; + typedef const Eigen::SyclDevice Device; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename InputArgType::Scalar Scalar; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + typedef StorageMemory KernelStorage; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned & + TensorEvaluator::IsAligned, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + TensorEvaluator(const XprType &op, const Eigen::SyclDevice &device) + : m_inputImpl(op.inputExpression(), device), + m_kernelArg(op.kernelExpression()), + m_kernelImpl(op.kernelExpression(), device), + m_indices(op.indices()), + m_buf(NULL), + m_kernel(NULL), + m_local_kernel(false), + m_device(device) { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == + static_cast(TensorEvaluator::Layout)), + YOU_MADE_A_PROGRAMMING_MISTAKE); + + const typename TensorEvaluator::Dimensions &input_dims = m_inputImpl.dimensions(); + const typename TensorEvaluator::Dimensions &kernel_dims = + m_kernelImpl.dimensions(); + + m_dimensions = m_inputImpl.dimensions(); + for (int i = 0; i < NumKernelDims; ++i) { + const Index index = op.indices()[i]; + const Index input_dim = input_dims[index]; + const Index kernel_dim = kernel_dims[i]; + const Index result_dim = input_dim - kernel_dim + 1; + m_dimensions[index] = result_dim; + } + } + + EIGEN_DEVICE_FUNC const Dimensions &dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + preloadKernel(); + m_inputImpl.evalSubExprsIfNeeded(NULL); + if (data) { + executeEval(data); + return false; + } else { + m_buf = (EvaluatorPointerType)m_device.get( + (Scalar *)m_device.allocate_temp(dimensions().TotalSize() * sizeof(Scalar))); + executeEval(m_buf); + return true; + } + } + + EIGEN_STRONG_INLINE void cleanup() { + m_inputImpl.cleanup(); + if (m_buf) { + m_device.deallocate_temp(m_buf); + m_buf = NULL; + } + if (m_local_kernel) { + m_device.deallocate_temp(m_kernel); + m_local_kernel = false; + } + m_kernel = NULL; + } + /// used by sycl in order to build the sycl buffer + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Device &device() const { return m_device; } + /// used by sycl in order to build the sycl buffer + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return m_buf; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void preloadKernel() { + // Don't make a local copy of the kernel unless we have to (i.e. it's an + // expression that needs to be evaluated) + typename KernelStorage::Type in_place = m_kernelImpl.data(); + if (in_place) { + m_kernel = in_place; + m_local_kernel = false; + } else { + ptrdiff_t kernel_sz = m_kernelImpl.dimensions().TotalSize() * sizeof(Scalar); + EvaluatorPointerType local = (EvaluatorPointerType)m_device.get((Scalar *)m_device.allocate_temp(kernel_sz)); + typedef TensorEvalToOp EvalTo; + EvalTo evalToTmp(m_device.get(local), m_kernelArg); + const bool PacketAccess = internal::IsVectorizable::value; + internal::TensorExecutor::run(evalToTmp, m_device); + m_kernel = local; + m_local_kernel = true; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void executeEval(EvaluatorPointerType data) const { + typedef TensorEvaluator InputEvaluator; + typedef typename InputEvaluator::Dimensions InputDims; + switch (NumKernelDims) { + case 1: { + const size_t numX = dimensions()[m_indices[0]]; + const size_t numP = dimensions().TotalSize() / numX; + const auto input_dim = std::array{numX, numP}; + auto global_range = cl::sycl::range<2>{1, 1}; + auto local_range = cl::sycl::range<2>{1, 1}; + const size_t kernel_size = m_kernelImpl.dimensions().TotalSize(); + + m_device.parallel_for_setup(input_dim, global_range, local_range); + const size_t local_memory_size = (local_range[0] + kernel_size - 1) * (local_range[1]); + gpu_assert(static_cast(local_memory_size) <= m_device.sharedMemPerBlock()); + const array indices{{m_indices[0]}}; + const array kernel_dims{{m_kernelImpl.dimensions()[0]}}; + internal::IndexMapper indexMapper(m_inputImpl.dimensions(), kernel_dims, indices); + + typedef EigenConvolutionKernel + ConvKernel; + + m_device.template binary_kernel_launcher( + m_inputImpl, m_kernel, data, cl::sycl::nd_range<2>(global_range, local_range), local_memory_size, + indexMapper, kernel_size, cl::sycl::range<2>(input_dim[0], input_dim[1])).wait(); + break; + } + + case 2: { + auto kernel_index = std::array{static_cast(Layout) == static_cast(ColMajor) ? 0 : 1, + static_cast(Layout) == static_cast(ColMajor) ? 1 : 0}; + auto kernel_size = cl::sycl::range<2>{(size_t)m_kernelImpl.dimensions()[kernel_index[0]], + (size_t)m_kernelImpl.dimensions()[kernel_index[1]]}; + const size_t numX = dimensions()[m_indices[kernel_index[0]]]; + const size_t numY = dimensions()[m_indices[kernel_index[1]]]; + const size_t numP = dimensions().TotalSize() / (numX * numY); + auto input_dim = std::array{numX, numY, numP}; + + auto global_range = cl::sycl::range<3>{1, 1, 1}; + auto local_range = cl::sycl::range<3>{1, 1, 1}; + + m_device.parallel_for_setup(input_dim, global_range, local_range); + + const size_t local_memory_size = + (local_range[0] + kernel_size[0] - 1) * (local_range[1] + kernel_size[1] - 1) * local_range[2]; + gpu_assert(static_cast(local_memory_size) <= m_device.sharedMemPerBlock()); + const array indices{{m_indices[kernel_index[0]], m_indices[kernel_index[1]]}}; + const array kernel_dims{ + {m_kernelImpl.dimensions()[kernel_index[0]], m_kernelImpl.dimensions()[kernel_index[1]]}}; + internal::IndexMapper indexMapper(m_inputImpl.dimensions(), kernel_dims, indices); + typedef EigenConvolutionKernel + ConvKernel; + m_device.template binary_kernel_launcher( + m_inputImpl, m_kernel, data, cl::sycl::nd_range<3>(global_range, local_range), local_memory_size, + indexMapper, kernel_size, cl::sycl::range<3>{input_dim[0], input_dim[1], input_dim[2]}).wait(); + break; + } + + case 3: { + auto kernel_index = std::array{static_cast(Layout) == static_cast(ColMajor) ? 0 : 2, + static_cast(Layout) == static_cast(ColMajor) ? 1 : 1, + static_cast(Layout) == static_cast(ColMajor) ? 2 : 0}; + + auto kernel_size = cl::sycl::range<3>{(size_t)m_kernelImpl.dimensions()[kernel_index[0]], + (size_t)m_kernelImpl.dimensions()[kernel_index[1]], + (size_t)m_kernelImpl.dimensions()[kernel_index[2]]}; + + const size_t numX = dimensions()[m_indices[kernel_index[0]]]; + const size_t numY = dimensions()[m_indices[kernel_index[1]]]; + const size_t numZ = dimensions()[m_indices[kernel_index[2]]]; + auto input_dim = std::array{numX, numY, numZ}; + const size_t numP = dimensions().TotalSize() / (numX * numY * numZ); + + const array indices{ + {m_indices[kernel_index[0]], m_indices[kernel_index[1]], m_indices[kernel_index[2]]}}; + const array kernel_dims{{m_kernelImpl.dimensions()[kernel_index[0]], + m_kernelImpl.dimensions()[kernel_index[1]], + m_kernelImpl.dimensions()[kernel_index[2]]}}; + + internal::IndexMapper indexMapper(m_inputImpl.dimensions(), kernel_dims, indices); + + auto global_range = cl::sycl::range<3>{1, 1, 1}; + auto local_range = cl::sycl::range<3>{1, 1, 1}; + + m_device.parallel_for_setup(input_dim, global_range, local_range); + auto local_memory_range = (local_range + kernel_size - 1); + const size_t local_memory_size = local_memory_range[0] * local_memory_range[1] * local_memory_range[2]; + + gpu_assert(static_cast(local_memory_size) <= m_device.sharedMemPerBlock()); + typedef EigenConvolutionKernel + ConvKernel; + m_device.template binary_kernel_launcher( + m_inputImpl, m_kernel, data, cl::sycl::nd_range<3>(global_range, local_range), local_memory_size, + indexMapper, kernel_size, cl::sycl::range<3>(input_dim[0], input_dim[1], input_dim[2]), numP).wait(); + break; + } + + default: { + EIGEN_STATIC_ASSERT((NumKernelDims >= 1 && NumKernelDims <= 3), + THIS_METHOD_IS_ONLY_FOR_OBJECTS_OF_A_SPECIFIC_SIZE); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + eigen_assert(m_buf != NULL); + eigen_assert(index < m_dimensions.TotalSize()); + return m_buf[index]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(const Index index) const { + eigen_assert(m_buf != NULL); + eigen_assert(index < m_dimensions.TotalSize()); + return internal::ploadt(m_buf + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + // TODO(rmlarsen): FIXME: For now, this is just a copy of the CPU cost + // model. + const double kernel_size = m_kernelImpl.dimensions().TotalSize(); + // We ignore the use of fused multiply-add. + const double convolve_compute_cost = TensorOpCost::AddCost() + TensorOpCost::MulCost(); + const double firstIndex_compute_cost = + NumDims * + (2 * TensorOpCost::AddCost() + 2 * TensorOpCost::MulCost() + TensorOpCost::DivCost()); + return TensorOpCost(0, 0, firstIndex_compute_cost, vectorized, PacketSize) + + kernel_size * (m_inputImpl.costPerCoeff(vectorized) + m_kernelImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, convolve_compute_cost, vectorized, PacketSize)); + } + + + private: + // No assignment (copies are needed by the kernels) + TensorEvaluator &operator=(const TensorEvaluator &); + TensorEvaluator m_inputImpl; + KernelArgType m_kernelArg; + TensorEvaluator m_kernelImpl; + Indices m_indices; + Dimensions m_dimensions; + EvaluatorPointerType m_buf; + typename KernelStorage::Type m_kernel; + bool m_local_kernel; + const Eigen::SyclDevice EIGEN_DEVICE_REF m_device; +}; // namespace Eigen + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CONVOLUTION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h new file mode 100644 index 0000000000000000000000000000000000000000..c3f4bddfad09de0f1d1029acad00984858bace97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h @@ -0,0 +1,216 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Rasmus Munk Larsen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H +#define EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorEvaluator + * \ingroup CXX11_Tensor_Module + * + * \brief A cost model used to limit the number of threads used for evaluating + * tensor expression. + * + */ + +// Class storing the cost of evaluating a tensor expression in terms of the +// estimated number of operand bytes loads, bytes stored, and compute cycles. +class TensorOpCost { + public: + // TODO(rmlarsen): Fix the scalar op costs in Eigen proper. Even a simple + // model based on minimal reciprocal throughput numbers from Intel or + // Agner Fog's tables would be better than what is there now. + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int MulCost() { + return internal::functor_traits< + internal::scalar_product_op >::Cost; + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int AddCost() { + return internal::functor_traits >::Cost; + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int DivCost() { + return internal::functor_traits< + internal::scalar_quotient_op >::Cost; + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int ModCost() { + return internal::functor_traits >::Cost; + } + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int CastCost() { + return internal::functor_traits< + internal::scalar_cast_op >::Cost; + } + + EIGEN_DEVICE_FUNC + TensorOpCost() : bytes_loaded_(0), bytes_stored_(0), compute_cycles_(0) {} + EIGEN_DEVICE_FUNC + TensorOpCost(double bytes_loaded, double bytes_stored, double compute_cycles) + : bytes_loaded_(bytes_loaded), + bytes_stored_(bytes_stored), + compute_cycles_(compute_cycles) {} + + EIGEN_DEVICE_FUNC + TensorOpCost(double bytes_loaded, double bytes_stored, double compute_cycles, + bool vectorized, double packet_size) + : bytes_loaded_(bytes_loaded), + bytes_stored_(bytes_stored), + compute_cycles_(vectorized ? compute_cycles / packet_size + : compute_cycles) { + eigen_assert(bytes_loaded >= 0 && (numext::isfinite)(bytes_loaded)); + eigen_assert(bytes_stored >= 0 && (numext::isfinite)(bytes_stored)); + eigen_assert(compute_cycles >= 0 && (numext::isfinite)(compute_cycles)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double bytes_loaded() const { + return bytes_loaded_; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double bytes_stored() const { + return bytes_stored_; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double compute_cycles() const { + return compute_cycles_; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double total_cost( + double load_cost, double store_cost, double compute_cost) const { + return load_cost * bytes_loaded_ + store_cost * bytes_stored_ + + compute_cost * compute_cycles_; + } + + // Drop memory access component. Intended for cases when memory accesses are + // sequential or are completely masked by computations. + EIGEN_DEVICE_FUNC void dropMemoryCost() { + bytes_loaded_ = 0; + bytes_stored_ = 0; + } + + // TODO(rmlarsen): Define min in terms of total cost, not elementwise. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost cwiseMin( + const TensorOpCost& rhs) const { + double bytes_loaded = numext::mini(bytes_loaded_, rhs.bytes_loaded()); + double bytes_stored = numext::mini(bytes_stored_, rhs.bytes_stored()); + double compute_cycles = numext::mini(compute_cycles_, rhs.compute_cycles()); + return TensorOpCost(bytes_loaded, bytes_stored, compute_cycles); + } + + // TODO(rmlarsen): Define max in terms of total cost, not elementwise. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost cwiseMax( + const TensorOpCost& rhs) const { + double bytes_loaded = numext::maxi(bytes_loaded_, rhs.bytes_loaded()); + double bytes_stored = numext::maxi(bytes_stored_, rhs.bytes_stored()); + double compute_cycles = numext::maxi(compute_cycles_, rhs.compute_cycles()); + return TensorOpCost(bytes_loaded, bytes_stored, compute_cycles); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost& operator+=( + const TensorOpCost& rhs) { + bytes_loaded_ += rhs.bytes_loaded(); + bytes_stored_ += rhs.bytes_stored(); + compute_cycles_ += rhs.compute_cycles(); + return *this; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost& operator*=(double rhs) { + bytes_loaded_ *= rhs; + bytes_stored_ *= rhs; + compute_cycles_ *= rhs; + return *this; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator+( + TensorOpCost lhs, const TensorOpCost& rhs) { + lhs += rhs; + return lhs; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator*( + TensorOpCost lhs, double rhs) { + lhs *= rhs; + return lhs; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend TensorOpCost operator*( + double lhs, TensorOpCost rhs) { + rhs *= lhs; + return rhs; + } + + friend std::ostream& operator<<(std::ostream& os, const TensorOpCost& tc) { + return os << "[bytes_loaded = " << tc.bytes_loaded() + << ", bytes_stored = " << tc.bytes_stored() + << ", compute_cycles = " << tc.compute_cycles() << "]"; + } + + private: + double bytes_loaded_; + double bytes_stored_; + double compute_cycles_; +}; + +// TODO(rmlarsen): Implement a policy that chooses an "optimal" number of theads +// in [1:max_threads] instead of just switching multi-threading off for small +// work units. +template +class TensorCostModel { + public: + // Scaling from Eigen compute cost to device cycles. + static const int kDeviceCyclesPerComputeCycle = 1; + + // Costs in device cycles. + static const int kStartupCycles = 100000; + static const int kPerThreadCycles = 100000; + static const int kTaskSize = 40000; + + // Returns the number of threads in [1:max_threads] to use for + // evaluating an expression with the given output size and cost per + // coefficient. + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int numThreads( + double output_size, const TensorOpCost& cost_per_coeff, int max_threads) { + double cost = totalCost(output_size, cost_per_coeff); + double threads = (cost - kStartupCycles) / kPerThreadCycles + 0.9; + // Make sure we don't invoke undefined behavior when we convert to an int. + threads = numext::mini(threads, GenericNumTraits::highest()); + return numext::mini(max_threads, + numext::maxi(1, static_cast(threads))); + } + + // taskSize assesses parallel task size. + // Value of 1.0 means ideal parallel task size. Values < 1.0 mean that task + // granularity needs to be increased to mitigate parallelization overheads. + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double taskSize( + double output_size, const TensorOpCost& cost_per_coeff) { + return totalCost(output_size, cost_per_coeff) / kTaskSize; + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double totalCost( + double output_size, const TensorOpCost& cost_per_coeff) { + // Cost of memory fetches from L2 cache. 64 is typical cache line size. + // 11 is L2 cache latency on Haswell. + // We don't know whether data is in L1, L2 or L3. But we are most interested + // in single-threaded computational time around 100us-10ms (smaller time + // is too small for parallelization, larger time is not interesting + // either because we are probably using all available threads already). + // And for the target time range, L2 seems to be what matters. Data set + // fitting into L1 is too small to take noticeable time. Data set fitting + // only into L3 presumably will take more than 10ms to load and process. + const double kLoadCycles = 1.0 / 64 * 11; + const double kStoreCycles = 1.0 / 64 * 11; + // Scaling from Eigen compute cost to device cycles. + return output_size * + cost_per_coeff.total_cost(kLoadCycles, kStoreCycles, + kDeviceCyclesPerComputeCycle); + } +}; + +} // namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_COST_MODEL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCustomOp.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCustomOp.h new file mode 100644 index 0000000000000000000000000000000000000000..5fa0709630010196edf918c31d74952e6b228f8b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorCustomOp.h @@ -0,0 +1,336 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_CUSTOM_OP_H +#define EIGEN_CXX11_TENSOR_TENSOR_CUSTOM_OP_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorCustomUnaryOp + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor custom class. + * + * + */ +namespace internal { +template +struct traits > +{ + typedef typename XprType::Scalar Scalar; + typedef typename XprType::StorageKind StorageKind; + typedef typename XprType::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = traits::Layout; + typedef typename traits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorCustomUnaryOpEIGEN_DEVICE_REF type; +}; + +template +struct nested > +{ + typedef TensorCustomUnaryOp type; +}; + +} // end namespace internal + + + +template +class TensorCustomUnaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCustomUnaryOp(const XprType& expr, const CustomUnaryFunc& func) + : m_expr(expr), m_func(func) {} + + EIGEN_DEVICE_FUNC + const CustomUnaryFunc& func() const { return m_func; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_expr; } + + protected: + typename XprType::Nested m_expr; + const CustomUnaryFunc m_func; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorCustomUnaryOp ArgType; + typedef typename internal::traits::Index Index; + static constexpr int NumDims = internal::traits::NumDimensions; + typedef DSizes Dimensions; + typedef std::remove_const_t Scalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename Eigen::internal::traits::PointerType TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const ArgType& op, const Device& device) + : m_op(op), m_device(device), m_result(NULL) + { + m_dimensions = op.func().dimensions(op.expression()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + if (data) { + evalTo(data); + return false; + } else { + m_result = static_cast(m_device.get( (CoeffReturnType*) + m_device.allocate_temp(dimensions().TotalSize() * sizeof(Scalar)))); + evalTo(m_result); + return true; + } + } + + EIGEN_STRONG_INLINE void cleanup() { + if (m_result) { + m_device.deallocate_temp(m_result); + m_result = NULL; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + return m_result[index]; + } + + template + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const { + return internal::ploadt(m_result + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + // TODO(rmlarsen): Extend CustomOp API to return its cost estimate. + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_result; } + + protected: + void evalTo(EvaluatorPointerType data) { + TensorMap > result(m_device.get(data), m_dimensions); + m_op.func().eval(m_op.expression(), result, m_device); + } + + Dimensions m_dimensions; + const ArgType m_op; + const Device EIGEN_DEVICE_REF m_device; + EvaluatorPointerType m_result; +}; + + + +/** \class TensorCustomBinaryOp + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor custom class. + * + * + */ +namespace internal { +template +struct traits > +{ + typedef typename internal::promote_storage_type::ret Scalar; + typedef typename internal::promote_storage_type::ret CoeffReturnType; + typedef typename promote_storage_type::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename LhsXprType::Nested LhsNested; + typedef typename RhsXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = traits::Layout; + typedef std::conditional_t::val, + typename traits::PointerType, typename traits::PointerType> PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorCustomBinaryOp& type; +}; + +template +struct nested > +{ + typedef TensorCustomBinaryOp type; +}; + +} // end namespace internal + + + +template +class TensorCustomBinaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename internal::traits::CoeffReturnType CoeffReturnType; + typedef typename internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCustomBinaryOp(const LhsXprType& lhs, const RhsXprType& rhs, const CustomBinaryFunc& func) + + : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_func(func) {} + + EIGEN_DEVICE_FUNC + const CustomBinaryFunc& func() const { return m_func; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + lhsExpression() const { return m_lhs_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + rhsExpression() const { return m_rhs_xpr; } + + protected: + typename LhsXprType::Nested m_lhs_xpr; + typename RhsXprType::Nested m_rhs_xpr; + const CustomBinaryFunc m_func; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorCustomBinaryOp XprType; + typedef typename internal::traits::Index Index; + static constexpr int NumDims = internal::traits::NumDimensions; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + + typedef typename Eigen::internal::traits::PointerType TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_op(op), m_device(device), m_result(NULL) + { + m_dimensions = op.func().dimensions(op.lhsExpression(), op.rhsExpression()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + if (data) { + evalTo(data); + return false; + } else { + m_result = static_cast(m_device.get( (CoeffReturnType*) + m_device.allocate_temp(dimensions().TotalSize() * sizeof(CoeffReturnType)))); + evalTo(m_result); + return true; + } + } + + EIGEN_STRONG_INLINE void cleanup() { + if (m_result != NULL) { + m_device.deallocate_temp(m_result); + m_result = NULL; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + return m_result[index]; + } + + template + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const { + return internal::ploadt(m_result + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + // TODO(rmlarsen): Extend CustomOp API to return its cost estimate. + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_result; } + + + protected: + void evalTo(EvaluatorPointerType data) { + TensorMap > result(m_device.get(data), m_dimensions); + m_op.func().eval(m_op.lhsExpression(), m_op.rhsExpression(), result, m_device); + } + + Dimensions m_dimensions; + const XprType m_op; + const Device EIGEN_DEVICE_REF m_device; + EvaluatorPointerType m_result; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_CUSTOM_OP_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDevice.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDevice.h new file mode 100644 index 0000000000000000000000000000000000000000..81484415b16b5cb4174609907bca62c19a836baa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDevice.h @@ -0,0 +1,139 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H +#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorDevice + * \ingroup CXX11_Tensor_Module + * + * \brief Pseudo expression providing an operator = that will evaluate its argument + * on the specified computing 'device' (GPU, thread pool, ...) + * + * Example: + * C.device(EIGEN_GPU) = A + B; + * + * Todo: operator *= and /=. + */ + +template class TensorDevice { + public: + TensorDevice(const DeviceType& device, ExpressionType& expression) : m_device(device), m_expression(expression) {} + + EIGEN_DEFAULT_COPY_CONSTRUCTOR(TensorDevice) + + template + EIGEN_STRONG_INLINE TensorDevice& operator=(const OtherDerived& other) { + typedef TensorAssignOp Assign; + Assign assign(m_expression, other); + internal::TensorExecutor::run(assign, m_device); + return *this; + } + + template + EIGEN_STRONG_INLINE TensorDevice& operator+=(const OtherDerived& other) { + typedef typename OtherDerived::Scalar Scalar; + typedef TensorCwiseBinaryOp, const ExpressionType, const OtherDerived> Sum; + Sum sum(m_expression, other); + typedef TensorAssignOp Assign; + Assign assign(m_expression, sum); + internal::TensorExecutor::run(assign, m_device); + return *this; + } + + template + EIGEN_STRONG_INLINE TensorDevice& operator-=(const OtherDerived& other) { + typedef typename OtherDerived::Scalar Scalar; + typedef TensorCwiseBinaryOp, const ExpressionType, const OtherDerived> Difference; + Difference difference(m_expression, other); + typedef TensorAssignOp Assign; + Assign assign(m_expression, difference); + internal::TensorExecutor::run(assign, m_device); + return *this; + } + + protected: + const DeviceType& m_device; + ExpressionType& m_expression; +}; + +/** \class TensorAsyncDevice + * \ingroup CXX11_Tensor_Module + * + * \brief Pseudo expression providing an operator = that will evaluate its + * argument asynchronously on the specified device. Currently only + * ThreadPoolDevice implements proper asynchronous execution, while the default + * and GPU devices just run the expression synchronously and call m_done() on + * completion.. + * + * Example: + * auto done = []() { ... expression evaluation done ... }; + * C.device(thread_pool_device, std::move(done)) = A + B; + */ + +template +class TensorAsyncDevice { + public: + TensorAsyncDevice(const DeviceType& device, ExpressionType& expression, + DoneCallback done) + : m_device(device), m_expression(expression), m_done(std::move(done)) {} + + template + EIGEN_STRONG_INLINE TensorAsyncDevice& operator=(const OtherDerived& other) { + typedef TensorAssignOp Assign; + typedef internal::TensorExecutor Executor; + + Assign assign(m_expression, other); + Executor::run(assign, m_device); + m_done(); + + return *this; + } + + protected: + const DeviceType& m_device; + ExpressionType& m_expression; + DoneCallback m_done; +}; + + +#ifdef EIGEN_USE_THREADS +template +class TensorAsyncDevice { + public: + TensorAsyncDevice(const ThreadPoolDevice& device, ExpressionType& expression, + DoneCallback done) + : m_device(device), m_expression(expression), m_done(std::move(done)) {} + + template + EIGEN_STRONG_INLINE TensorAsyncDevice& operator=(const OtherDerived& other) { + typedef TensorAssignOp Assign; + typedef internal::TensorAsyncExecutor Executor; + + // WARNING: After assignment 'm_done' callback will be in undefined state. + Assign assign(m_expression, other); + Executor::runAsync(assign, m_device, std::move(m_done)); + + return *this; + } + + protected: + const ThreadPoolDevice& m_device; + ExpressionType& m_expression; + DoneCallback m_done; +}; +#endif + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h new file mode 100644 index 0000000000000000000000000000000000000000..f7792393353cda937b40b53cddf467b2360e3307 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h @@ -0,0 +1,6 @@ + +#if defined(__clang__) || defined(__GNUC__) +#warning "Deprecated header file, please either include the main Eigen/CXX11/Tensor header or the respective TensorDeviceGpu.h file" +#endif + +#include "TensorDeviceGpu.h" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceDefault.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceDefault.h new file mode 100644 index 0000000000000000000000000000000000000000..7864a2abc7e79636a090ccd2f14f2d0464df9e17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceDefault.h @@ -0,0 +1,121 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_DEVICE_DEFAULT_H +#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_DEFAULT_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +// Default device for the machine (typically a single cpu core) +struct DefaultDevice { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void* allocate(size_t num_bytes) const { + return internal::aligned_malloc(num_bytes); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void deallocate(void* buffer) const { + internal::aligned_free(buffer); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void* allocate_temp(size_t num_bytes) const { + return allocate(num_bytes); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void deallocate_temp(void* buffer) const { + deallocate(buffer); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memcpy(void* dst, const void* src, size_t n) const { + ::memcpy(dst, src, n); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memcpyHostToDevice(void* dst, const void* src, size_t n) const { + memcpy(dst, src, n); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memcpyDeviceToHost(void* dst, const void* src, size_t n) const { + memcpy(dst, src, n); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memset(void* buffer, int c, size_t n) const { + ::memset(buffer, c, n); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void fill(T* begin, T* end, const T& value) const { +#ifdef EIGEN_GPU_COMPILE_PHASE + // std::fill is not a device function, so resort to simple loop. + for (T* it = begin; it != end; ++it) { + *it = value; + } +#else + std::fill(begin, end, value); +#endif + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Type get(Type data) const { + return data; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE size_t numThreads() const { +#if !defined(EIGEN_GPU_COMPILE_PHASE) + // Running on the host CPU + return 1; +#elif defined(EIGEN_HIP_DEVICE_COMPILE) + // Running on a HIP device + return 64; +#else + // Running on a CUDA device + return 32; +#endif + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const { +#if !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(SYCL_DEVICE_ONLY) + // Running on the host CPU + return l1CacheSize(); +#elif defined(EIGEN_HIP_DEVICE_COMPILE) + // Running on a HIP device + return 48*1024; // FIXME : update this number for HIP +#else + // Running on a CUDA device, return the amount of shared memory available. + return 48*1024; +#endif + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const { +#if !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(SYCL_DEVICE_ONLY) + // Running single threaded on the host CPU + return l3CacheSize(); +#elif defined(EIGEN_HIP_DEVICE_COMPILE) + // Running on a HIP device + return firstLevelCacheSize(); // FIXME : update this number for HIP +#else + // Running on a CUDA device + return firstLevelCacheSize(); +#endif + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void synchronize() const { + // Nothing. Default device operations are synchronous. + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int majorDeviceVersion() const { +#if !defined(EIGEN_GPU_COMPILE_PHASE) + // Running single threaded on the host CPU + // Should return an enum that encodes the ISA supported by the CPU + return 1; +#elif defined(EIGEN_HIP_DEVICE_COMPILE) + // Running on a HIP device + // return 1 as major for HIP + return 1; +#else + // Running on a CUDA device + return EIGEN_CUDA_ARCH / 100; +#endif + } +}; + +} // namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_DEFAULT_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceGpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceGpu.h new file mode 100644 index 0000000000000000000000000000000000000000..b477907044eda2504827c24f3ec41c871e68efe0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceGpu.h @@ -0,0 +1,442 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if defined(EIGEN_USE_GPU) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_GPU_H) +#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_GPU_H + +// This header file container defines fo gpu* macros which will resolve to +// their equivalent hip* or cuda* versions depending on the compiler in use +// A separate header (included at the end of this file) will undefine all +#include "TensorGpuHipCudaDefines.h" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +static const int kGpuScratchSize = 1024; + +// This defines an interface that GPUDevice can take to use +// HIP / CUDA streams underneath. +class StreamInterface { + public: + virtual ~StreamInterface() {} + + virtual const gpuStream_t& stream() const = 0; + virtual const gpuDeviceProp_t& deviceProperties() const = 0; + + // Allocate memory on the actual device where the computation will run + virtual void* allocate(size_t num_bytes) const = 0; + virtual void deallocate(void* buffer) const = 0; + + // Return a scratchpad buffer of size 1k + virtual void* scratchpad() const = 0; + + // Return a semaphore. The semaphore is initially initialized to 0, and + // each kernel using it is responsible for resetting to 0 upon completion + // to maintain the invariant that the semaphore is always equal to 0 upon + // each kernel start. + virtual unsigned int* semaphore() const = 0; +}; + +class GpuDeviceProperties { + public: + GpuDeviceProperties() : + initialized_(false), first_(true), device_properties_(nullptr) {} + + ~GpuDeviceProperties() { + if (device_properties_) { + delete[] device_properties_; + } + } + + EIGEN_STRONG_INLINE const gpuDeviceProp_t& get(int device) const { + return device_properties_[device]; + } + + EIGEN_STRONG_INLINE bool isInitialized() const { + return initialized_; + } + + void initialize() { + if (!initialized_) { + // Attempts to ensure proper behavior in the case of multiple threads + // calling this function simultaneously. This would be trivial to + // implement if we could use std::mutex, but unfortunately mutex don't + // compile with nvcc, so we resort to atomics and thread fences instead. + // Note that if the caller uses a compiler that doesn't support c++11 we + // can't ensure that the initialization is thread safe. + if (first_.exchange(false)) { + // We're the first thread to reach this point. + int num_devices; + gpuError_t status = gpuGetDeviceCount(&num_devices); + if (status != gpuSuccess) { + std::cerr << "Failed to get the number of GPU devices: " + << gpuGetErrorString(status) + << std::endl; + gpu_assert(status == gpuSuccess); + } + device_properties_ = new gpuDeviceProp_t[num_devices]; + for (int i = 0; i < num_devices; ++i) { + status = gpuGetDeviceProperties(&device_properties_[i], i); + if (status != gpuSuccess) { + std::cerr << "Failed to initialize GPU device #" + << i + << ": " + << gpuGetErrorString(status) + << std::endl; + gpu_assert(status == gpuSuccess); + } + } + + std::atomic_thread_fence(std::memory_order_release); + initialized_ = true; + } else { + // Wait for the other thread to inititialize the properties. + while (!initialized_) { + std::atomic_thread_fence(std::memory_order_acquire); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + } + } + } + + private: + volatile bool initialized_; + std::atomic first_; + gpuDeviceProp_t* device_properties_; +}; + +EIGEN_ALWAYS_INLINE const GpuDeviceProperties& GetGpuDeviceProperties() { + static GpuDeviceProperties* deviceProperties = new GpuDeviceProperties(); + if (!deviceProperties->isInitialized()) { + deviceProperties->initialize(); + } + return *deviceProperties; +} + +EIGEN_ALWAYS_INLINE const gpuDeviceProp_t& GetGpuDeviceProperties(int device) { + return GetGpuDeviceProperties().get(device); +} + +static const gpuStream_t default_stream = gpuStreamDefault; + +class GpuStreamDevice : public StreamInterface { + public: + // Use the default stream on the current device + GpuStreamDevice() : stream_(&default_stream), scratch_(NULL), semaphore_(NULL) { + gpuError_t status = gpuGetDevice(&device_); + if (status != gpuSuccess) { + std::cerr << "Failed to get the GPU devices " + << gpuGetErrorString(status) + << std::endl; + gpu_assert(status == gpuSuccess); + } + } + // Use the default stream on the specified device + GpuStreamDevice(int device) : stream_(&default_stream), device_(device), scratch_(NULL), semaphore_(NULL) {} + // Use the specified stream. Note that it's the + // caller responsibility to ensure that the stream can run on + // the specified device. If no device is specified the code + // assumes that the stream is associated to the current gpu device. + GpuStreamDevice(const gpuStream_t* stream, int device = -1) + : stream_(stream), device_(device), scratch_(NULL), semaphore_(NULL) { + if (device < 0) { + gpuError_t status = gpuGetDevice(&device_); + if (status != gpuSuccess) { + std::cerr << "Failed to get the GPU devices " + << gpuGetErrorString(status) + << std::endl; + gpu_assert(status == gpuSuccess); + } + } else { + int num_devices; + gpuError_t err = gpuGetDeviceCount(&num_devices); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + gpu_assert(device < num_devices); + device_ = device; + } + } + + virtual ~GpuStreamDevice() { + if (scratch_) { + deallocate(scratch_); + } + } + + const gpuStream_t& stream() const { return *stream_; } + const gpuDeviceProp_t& deviceProperties() const { + return GetGpuDeviceProperties(device_); + } + virtual void* allocate(size_t num_bytes) const { + gpuError_t err = gpuSetDevice(device_); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + void* result; + err = gpuMalloc(&result, num_bytes); + gpu_assert(err == gpuSuccess); + gpu_assert(result != NULL); + return result; + } + virtual void deallocate(void* buffer) const { + gpuError_t err = gpuSetDevice(device_); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + gpu_assert(buffer != NULL); + err = gpuFree(buffer); + gpu_assert(err == gpuSuccess); + } + + virtual void* scratchpad() const { + if (scratch_ == NULL) { + scratch_ = allocate(kGpuScratchSize + sizeof(unsigned int)); + } + return scratch_; + } + + virtual unsigned int* semaphore() const { + if (semaphore_ == NULL) { + char* scratch = static_cast(scratchpad()) + kGpuScratchSize; + semaphore_ = reinterpret_cast(scratch); + gpuError_t err = gpuMemsetAsync(semaphore_, 0, sizeof(unsigned int), *stream_); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + } + return semaphore_; + } + + private: + const gpuStream_t* stream_; + int device_; + mutable void* scratch_; + mutable unsigned int* semaphore_; +}; + +struct GpuDevice { + // The StreamInterface is not owned: the caller is + // responsible for its initialization and eventual destruction. + explicit GpuDevice(const StreamInterface* stream) : stream_(stream), max_blocks_(INT_MAX) { + eigen_assert(stream); + } + explicit GpuDevice(const StreamInterface* stream, int num_blocks) : stream_(stream), max_blocks_(num_blocks) { + eigen_assert(stream); + } + // TODO(bsteiner): This is an internal API, we should not expose it. + EIGEN_STRONG_INLINE const gpuStream_t& stream() const { + return stream_->stream(); + } + + EIGEN_STRONG_INLINE void* allocate(size_t num_bytes) const { + return stream_->allocate(num_bytes); + } + + EIGEN_STRONG_INLINE void deallocate(void* buffer) const { + stream_->deallocate(buffer); + } + + EIGEN_STRONG_INLINE void* allocate_temp(size_t num_bytes) const { + return stream_->allocate(num_bytes); + } + + EIGEN_STRONG_INLINE void deallocate_temp(void* buffer) const { + stream_->deallocate(buffer); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Type get(Type data) const { + return data; + } + + EIGEN_STRONG_INLINE void* scratchpad() const { + return stream_->scratchpad(); + } + + EIGEN_STRONG_INLINE unsigned int* semaphore() const { + return stream_->semaphore(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memcpy(void* dst, const void* src, size_t n) const { +#ifndef EIGEN_GPU_COMPILE_PHASE + gpuError_t err = gpuMemcpyAsync(dst, src, n, gpuMemcpyDeviceToDevice, + stream_->stream()); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); +#else + EIGEN_UNUSED_VARIABLE(dst); + EIGEN_UNUSED_VARIABLE(src); + EIGEN_UNUSED_VARIABLE(n); + eigen_assert(false && "The default device should be used instead to generate kernel code"); +#endif + } + + EIGEN_STRONG_INLINE void memcpyHostToDevice(void* dst, const void* src, size_t n) const { + gpuError_t err = + gpuMemcpyAsync(dst, src, n, gpuMemcpyHostToDevice, stream_->stream()); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + } + + EIGEN_STRONG_INLINE void memcpyDeviceToHost(void* dst, const void* src, size_t n) const { + gpuError_t err = + gpuMemcpyAsync(dst, src, n, gpuMemcpyDeviceToHost, stream_->stream()); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void memset(void* buffer, int c, size_t n) const { +#ifndef EIGEN_GPU_COMPILE_PHASE + gpuError_t err = gpuMemsetAsync(buffer, c, n, stream_->stream()); + EIGEN_UNUSED_VARIABLE(err) + gpu_assert(err == gpuSuccess); +#else + EIGEN_UNUSED_VARIABLE(buffer) + EIGEN_UNUSED_VARIABLE(c) + EIGEN_UNUSED_VARIABLE(n) + eigen_assert(false && "The default device should be used instead to generate kernel code"); +#endif + } + + template + EIGEN_STRONG_INLINE void fill(T* begin, T* end, const T& value) const { +#ifndef EIGEN_GPU_COMPILE_PHASE + const size_t count = end - begin; + // Split value into bytes and run memset with stride. + const int value_size = sizeof(value); + char* buffer = (char*)begin; + char* value_bytes = (char*)(&value); + gpuError_t err; + EIGEN_UNUSED_VARIABLE(err) + + // If all value bytes are equal, then a single memset can be much faster. + bool use_single_memset = true; + for (int i=1; istream()); + gpu_assert(err == gpuSuccess); + } else { + for (int b=0; bstream()); + gpu_assert(err == gpuSuccess); + } + } +#else + EIGEN_UNUSED_VARIABLE(begin) + EIGEN_UNUSED_VARIABLE(end) + EIGEN_UNUSED_VARIABLE(value) + eigen_assert(false && "The default device should be used instead to generate kernel code"); +#endif + } + + EIGEN_STRONG_INLINE size_t numThreads() const { + // FIXME + return 32; + } + + EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const { + // FIXME + return 48*1024; + } + + EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const { + // We won't try to take advantage of the l2 cache for the time being, and + // there is no l3 cache on hip/cuda devices. + return firstLevelCacheSize(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void synchronize() const { +#ifndef EIGEN_GPU_COMPILE_PHASE + gpuError_t err = gpuStreamSynchronize(stream_->stream()); + if (err != gpuSuccess) { + std::cerr << "Error detected in GPU stream: " + << gpuGetErrorString(err) + << std::endl; + gpu_assert(err == gpuSuccess); + } +#else + gpu_assert(false && "The default device should be used instead to generate kernel code"); +#endif + } + + EIGEN_STRONG_INLINE int getNumGpuMultiProcessors() const { + return stream_->deviceProperties().multiProcessorCount; + } + EIGEN_STRONG_INLINE int maxGpuThreadsPerBlock() const { + return stream_->deviceProperties().maxThreadsPerBlock; + } + EIGEN_STRONG_INLINE int maxGpuThreadsPerMultiProcessor() const { + return stream_->deviceProperties().maxThreadsPerMultiProcessor; + } + EIGEN_STRONG_INLINE int sharedMemPerBlock() const { + return static_cast(stream_->deviceProperties().sharedMemPerBlock); + } + EIGEN_STRONG_INLINE int majorDeviceVersion() const { + return stream_->deviceProperties().major; + } + EIGEN_STRONG_INLINE int minorDeviceVersion() const { + return stream_->deviceProperties().minor; + } + + EIGEN_STRONG_INLINE int maxBlocks() const { + return max_blocks_; + } + + // This function checks if the GPU runtime recorded an error for the + // underlying stream device. + inline bool ok() const { +#ifdef EIGEN_GPUCC + gpuError_t error = gpuStreamQuery(stream_->stream()); + return (error == gpuSuccess) || (error == gpuErrorNotReady); +#else + return false; +#endif + } + + private: + const StreamInterface* stream_; + int max_blocks_; +}; + +#if defined(EIGEN_HIPCC) + +#define LAUNCH_GPU_KERNEL(kernel, gridsize, blocksize, sharedmem, device, ...) \ + hipLaunchKernelGGL(kernel, dim3(gridsize), dim3(blocksize), (sharedmem), (device).stream(), __VA_ARGS__); \ + gpu_assert(hipGetLastError() == hipSuccess); + +#else + +#define LAUNCH_GPU_KERNEL(kernel, gridsize, blocksize, sharedmem, device, ...) \ + (kernel) <<< (gridsize), (blocksize), (sharedmem), (device).stream() >>> (__VA_ARGS__); \ + gpu_assert(cudaGetLastError() == cudaSuccess); + +#endif + +// FIXME: Should be device and kernel specific. +#ifdef EIGEN_GPUCC +static EIGEN_DEVICE_FUNC inline void setGpuSharedMemConfig(gpuSharedMemConfig config) { +#ifndef EIGEN_GPU_COMPILE_PHASE + gpuError_t status = gpuDeviceSetSharedMemConfig(config); + EIGEN_UNUSED_VARIABLE(status) + gpu_assert(status == gpuSuccess); +#else + EIGEN_UNUSED_VARIABLE(config) +#endif +} +#endif + +} // end namespace Eigen + +// undefine all the gpu* macros we defined at the beginning of the file +#include "TensorGpuHipCudaUndefines.h" + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_GPU_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceSycl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceSycl.h new file mode 100644 index 0000000000000000000000000000000000000000..7ff95d0f864513929674a81b8ac783698b40334a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceSycl.h @@ -0,0 +1,704 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Mehdi Goli Codeplay Software Ltd. +// Ralph Potter Codeplay Software Ltd. +// Luke Iwanski Codeplay Software Ltd. +// Contact: +// Copyright (C) 2016 Benoit Steiner + +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if defined(EIGEN_USE_SYCL) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_SYCL_H) +#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_SYCL_H +#include + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace TensorSycl { +namespace internal { + +/// Cache all the device information needed +struct SyclDeviceInfo { + SyclDeviceInfo(cl::sycl::queue queue) + : local_mem_type( + queue.get_device() + .template get_info()), + max_work_item_sizes( + queue.get_device() + .template get_info< + cl::sycl::info::device::max_work_item_sizes<3>>()), + max_mem_alloc_size( + queue.get_device() + .template get_info< + cl::sycl::info::device::max_mem_alloc_size>()), + max_compute_units(queue.get_device() + .template get_info< + cl::sycl::info::device::max_compute_units>()), + max_work_group_size( + queue.get_device() + .template get_info< + cl::sycl::info::device::max_work_group_size>()), + local_mem_size( + queue.get_device() + .template get_info()), + platform_name(queue.get_device() + .get_platform() + .template get_info()), + device_name(queue.get_device() + .template get_info()), + device_vendor( + queue.get_device() + .template get_info()) {} + + cl::sycl::info::local_mem_type local_mem_type; + cl::sycl::id<3> max_work_item_sizes; + unsigned long max_mem_alloc_size; + unsigned long max_compute_units; + unsigned long max_work_group_size; + size_t local_mem_size; + std::string platform_name; + std::string device_name; + std::string device_vendor; +}; + +} // end namespace internal +} // end namespace TensorSycl + +// All devices (even AMD CPU with intel OpenCL runtime) that support OpenCL and +// can consume SPIR or SPIRV can use the Eigen SYCL backend and consequently +// TensorFlow via the Eigen SYCL Backend. +EIGEN_STRONG_INLINE auto get_sycl_supported_devices() + -> decltype(cl::sycl::device::get_devices()) { +#ifdef EIGEN_SYCL_USE_DEFAULT_SELECTOR + return {cl::sycl::device(cl::sycl::default_selector())}; +#else + std::vector supported_devices; + auto platform_list = cl::sycl::platform::get_platforms(); + for (const auto &platform : platform_list) { + auto device_list = platform.get_devices(); + auto platform_name = + platform.template get_info(); + std::transform(platform_name.begin(), platform_name.end(), + platform_name.begin(), ::tolower); + for (const auto &device : device_list) { + auto vendor = device.template get_info(); + std::transform(vendor.begin(), vendor.end(), vendor.begin(), ::tolower); + bool unsupported_condition = + (device.is_cpu() && platform_name.find("amd") != std::string::npos && + vendor.find("apu") == std::string::npos) || + (platform_name.find("experimental") != std::string::npos) || + device.is_host(); + if (!unsupported_condition) { + supported_devices.push_back(device); + } + } + } + return supported_devices; +#endif +} + +class QueueInterface { + public: + /// Creating device by using cl::sycl::selector or cl::sycl::device. + template + explicit QueueInterface( + const DeviceOrSelector &dev_or_sel, cl::sycl::async_handler handler, + unsigned num_threads = std::thread::hardware_concurrency()) + : m_queue{dev_or_sel, handler, {sycl::property::queue::in_order()}}, + m_thread_pool(num_threads), + m_device_info(m_queue) {} + + template + explicit QueueInterface( + const DeviceOrSelector &dev_or_sel, + unsigned num_threads = std::thread::hardware_concurrency()) + : QueueInterface( + dev_or_sel, + [this](cl::sycl::exception_list l) { + this->exception_caught_ = this->sycl_async_handler(l); + }, + num_threads) {} + + explicit QueueInterface( + const cl::sycl::queue &q, + unsigned num_threads = std::thread::hardware_concurrency()) + : m_queue(q), m_thread_pool(num_threads), m_device_info(m_queue) {} + + EIGEN_STRONG_INLINE void *allocate(size_t num_bytes) const { +#if EIGEN_MAX_ALIGN_BYTES > 0 + return (void *)cl::sycl::aligned_alloc_device(EIGEN_MAX_ALIGN_BYTES, + num_bytes, m_queue); +#else + return (void *)cl::sycl::malloc_device(num_bytes, m_queue); +#endif + } + + EIGEN_STRONG_INLINE void *allocate_temp(size_t num_bytes) const { + return (void *)cl::sycl::malloc_device(num_bytes, m_queue); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE data_t *get(data_t *data) const { + return data; + } + + EIGEN_STRONG_INLINE void deallocate_temp(void *p) const { deallocate(p); } + + EIGEN_STRONG_INLINE void deallocate_temp(const void *p) const { + deallocate_temp(const_cast(p)); + } + + EIGEN_STRONG_INLINE void deallocate(void *p) const { + cl::sycl::free(p, m_queue); + } + + /// The memcpyHostToDevice is used to copy the data from host to device + /// The destination pointer could be deleted before the copy happened which is + /// why a callback function is needed. By default if none is provided, the + /// function is blocking. + EIGEN_STRONG_INLINE void memcpyHostToDevice( + void *dst, const void *src, size_t n, + std::function callback) const { + auto e = m_queue.memcpy(dst, src, n); + synchronize_and_callback(e, callback); + } + + /// The memcpyDeviceToHost is used to copy the data from device to host. + /// The source pointer could be deleted before the copy happened which is + /// why a callback function is needed. By default if none is provided, the + /// function is blocking. + EIGEN_STRONG_INLINE void memcpyDeviceToHost( + void *dst, const void *src, size_t n, + std::function callback) const { + if (n == 0) { + if (callback) callback(); + return; + } + auto e = m_queue.memcpy(dst, src, n); + synchronize_and_callback(e, callback); + } + + /// The memcpy function. + /// No callback is required here as both arguments are on the device + /// and SYCL can handle the dependency. + EIGEN_STRONG_INLINE void memcpy(void *dst, const void *src, size_t n) const { + if (n == 0) { + return; + } + m_queue.memcpy(dst, src, n).wait(); + } + + /// the memset function. + /// No callback is required here as both arguments are on the device + /// and SYCL can handle the dependency. + EIGEN_STRONG_INLINE void memset(void *data, int c, size_t n) const { + if (n == 0) { + return; + } + m_queue.memset(data, c, n).wait(); + } + + template + EIGEN_STRONG_INLINE void fill(T *begin, T *end, const T &value) const { + if (begin == end) { + return; + } + const size_t count = end - begin; + m_queue.fill(begin, value, count).wait(); + } + + template + EIGEN_ALWAYS_INLINE cl::sycl::event binary_kernel_launcher( + const Lhs &lhs, const Rhs &rhs, OutPtr outptr, Range thread_range, + Index scratchSize, T... var) const { + auto kernel_functor = [=](cl::sycl::handler &cgh) { + typedef cl::sycl::accessor + LocalAccessor; + + LocalAccessor scratch(cl::sycl::range<1>(scratchSize), cgh); + cgh.parallel_for(thread_range, + sycl_kernel(scratch, lhs, rhs, outptr, var...)); + }; + + return m_queue.submit(kernel_functor); + } + + template + EIGEN_ALWAYS_INLINE cl::sycl::event unary_kernel_launcher(const InPtr &inptr, + OutPtr &outptr, + Range thread_range, + Index scratchSize, + T... var) const { + auto kernel_functor = [=](cl::sycl::handler &cgh) { + typedef cl::sycl::accessor + LocalAccessor; + + LocalAccessor scratch(cl::sycl::range<1>(scratchSize), cgh); + cgh.parallel_for(thread_range, + sycl_kernel(scratch, inptr, outptr, var...)); + }; + return m_queue.submit(kernel_functor); + } + + template + EIGEN_ALWAYS_INLINE cl::sycl::event nullary_kernel_launcher( + const InPtr &inptr, Range thread_range, Index scratchSize, + T... var) const { + auto kernel_functor = [=](cl::sycl::handler &cgh) { + typedef cl::sycl::accessor + LocalAccessor; + + LocalAccessor scratch(cl::sycl::range<1>(scratchSize), cgh); + cgh.parallel_for(thread_range, sycl_kernel(scratch, inptr, var...)); + }; + + return m_queue.submit(kernel_functor); + } + + EIGEN_STRONG_INLINE void synchronize() const { +#ifdef EIGEN_EXCEPTIONS + m_queue.wait_and_throw(); +#else + m_queue.wait(); +#endif + } + + template + EIGEN_STRONG_INLINE void parallel_for_setup(Index n, Index &tileSize, + Index &rng, Index &GRange) const { + tileSize = static_cast(getNearestPowerOfTwoWorkGroupSize()); + tileSize = std::min(static_cast(EIGEN_SYCL_LOCAL_THREAD_DIM0 * + EIGEN_SYCL_LOCAL_THREAD_DIM1), + static_cast(tileSize)); + rng = n; + if (rng == 0) rng = static_cast(1); + GRange = rng; + if (tileSize > GRange) + tileSize = GRange; + else if (GRange > tileSize) { + Index xMode = static_cast(GRange % tileSize); + if (xMode != 0) GRange += static_cast(tileSize - xMode); + } + } + + /// This is used to prepare the number of threads and also the number of + /// threads per block for sycl kernels + template + EIGEN_STRONG_INLINE void parallel_for_setup( + const std::array &input_dim, cl::sycl::range<2> &global_range, + cl::sycl::range<2> &local_range) const { + std::array input_range = input_dim; + Index max_workgroup_Size = + static_cast(getNearestPowerOfTwoWorkGroupSize()); + max_workgroup_Size = + std::min(static_cast(EIGEN_SYCL_LOCAL_THREAD_DIM0 * + EIGEN_SYCL_LOCAL_THREAD_DIM1), + static_cast(max_workgroup_Size)); + Index pow_of_2 = static_cast(std::log2(max_workgroup_Size)); + local_range[1] = + static_cast(std::pow(2, static_cast(pow_of_2 / 2))); + input_range[1] = input_dim[1]; + if (input_range[1] == 0) input_range[1] = static_cast(1); + global_range[1] = input_range[1]; + if (local_range[1] > global_range[1]) + local_range[1] = global_range[1]; + else if (global_range[1] > local_range[1]) { + Index xMode = static_cast(global_range[1] % local_range[1]); + if (xMode != 0) + global_range[1] += static_cast(local_range[1] - xMode); + } + local_range[0] = static_cast(max_workgroup_Size / local_range[1]); + input_range[0] = input_dim[0]; + if (input_range[0] == 0) input_range[0] = static_cast(1); + global_range[0] = input_range[0]; + if (local_range[0] > global_range[0]) + local_range[0] = global_range[0]; + else if (global_range[0] > local_range[0]) { + Index xMode = static_cast(global_range[0] % local_range[0]); + if (xMode != 0) + global_range[0] += static_cast(local_range[0] - xMode); + } + } + + /// This is used to prepare the number of threads and also the number of + /// threads per block for sycl kernels + template + EIGEN_STRONG_INLINE void parallel_for_setup( + const std::array &input_dim, cl::sycl::range<3> &global_range, + cl::sycl::range<3> &local_range) const { + std::array input_range = input_dim; + Index max_workgroup_Size = + static_cast(getNearestPowerOfTwoWorkGroupSize()); + max_workgroup_Size = + std::min(static_cast(EIGEN_SYCL_LOCAL_THREAD_DIM0 * + EIGEN_SYCL_LOCAL_THREAD_DIM1), + static_cast(max_workgroup_Size)); + Index pow_of_2 = static_cast(std::log2(max_workgroup_Size)); + local_range[2] = + static_cast(std::pow(2, static_cast(pow_of_2 / 3))); + input_range[2] = input_dim[2]; + if (input_range[2] == 0) input_range[1] = static_cast(1); + global_range[2] = input_range[2]; + if (local_range[2] > global_range[2]) + local_range[2] = global_range[2]; + else if (global_range[2] > local_range[2]) { + Index xMode = static_cast(global_range[2] % local_range[2]); + if (xMode != 0) + global_range[2] += static_cast(local_range[2] - xMode); + } + pow_of_2 = static_cast( + std::log2(static_cast(max_workgroup_Size / local_range[2]))); + local_range[1] = + static_cast(std::pow(2, static_cast(pow_of_2 / 2))); + input_range[1] = input_dim[1]; + if (input_range[1] == 0) input_range[1] = static_cast(1); + global_range[1] = input_range[1]; + if (local_range[1] > global_range[1]) + local_range[1] = global_range[1]; + else if (global_range[1] > local_range[1]) { + Index xMode = static_cast(global_range[1] % local_range[1]); + if (xMode != 0) + global_range[1] += static_cast(local_range[1] - xMode); + } + local_range[0] = static_cast(max_workgroup_Size / + (local_range[1] * local_range[2])); + input_range[0] = input_dim[0]; + if (input_range[0] == 0) input_range[0] = static_cast(1); + global_range[0] = input_range[0]; + if (local_range[0] > global_range[0]) + local_range[0] = global_range[0]; + else if (global_range[0] > local_range[0]) { + Index xMode = static_cast(global_range[0] % local_range[0]); + if (xMode != 0) + global_range[0] += static_cast(local_range[0] - xMode); + } + } + + EIGEN_STRONG_INLINE bool has_local_memory() const { +#if !defined(EIGEN_SYCL_LOCAL_MEM) && defined(EIGEN_SYCL_NO_LOCAL_MEM) + return false; +#elif defined(EIGEN_SYCL_LOCAL_MEM) && !defined(EIGEN_SYCL_NO_LOCAL_MEM) + return true; +#else + return m_device_info.local_mem_type == + cl::sycl::info::local_mem_type::local; +#endif + } + + EIGEN_STRONG_INLINE unsigned long max_buffer_size() const { + return m_device_info.max_mem_alloc_size; + } + + EIGEN_STRONG_INLINE unsigned long getNumSyclMultiProcessors() const { + return m_device_info.max_compute_units; + } + + EIGEN_STRONG_INLINE unsigned long maxSyclThreadsPerBlock() const { + return m_device_info.max_work_group_size; + } + + EIGEN_STRONG_INLINE cl::sycl::id<3> maxWorkItemSizes() const { + return m_device_info.max_work_item_sizes; + } + + /// No need for sycl it should act the same as CPU version + EIGEN_STRONG_INLINE int majorDeviceVersion() const { return 1; } + + EIGEN_STRONG_INLINE unsigned long maxSyclThreadsPerMultiProcessor() const { + // OpenCL does not have such a concept + return 2; + } + + EIGEN_STRONG_INLINE size_t sharedMemPerBlock() const { + return m_device_info.local_mem_size; + } + + // This function returns the nearest power of 2 Work-group size which is <= + // maximum device workgroup size. + EIGEN_STRONG_INLINE size_t getNearestPowerOfTwoWorkGroupSize() const { + return getPowerOfTwo(m_device_info.max_work_group_size, false); + } + + EIGEN_STRONG_INLINE std::string getPlatformName() const { + return m_device_info.platform_name; + } + + EIGEN_STRONG_INLINE std::string getDeviceName() const { + return m_device_info.device_name; + } + + EIGEN_STRONG_INLINE std::string getDeviceVendor() const { + return m_device_info.device_vendor; + } + + // This function returns the nearest power of 2 + // if roundup is true returns result>=wgsize + // else it return result <= wgsize + EIGEN_STRONG_INLINE size_t getPowerOfTwo(size_t wGSize, bool roundUp) const { + if (roundUp) --wGSize; + wGSize |= (wGSize >> 1); + wGSize |= (wGSize >> 2); + wGSize |= (wGSize >> 4); + wGSize |= (wGSize >> 8); + wGSize |= (wGSize >> 16); +#if EIGEN_ARCH_x86_64 || EIGEN_ARCH_ARM64 || EIGEN_OS_WIN64 + wGSize |= (wGSize >> 32); +#endif + return ((!roundUp) ? (wGSize - (wGSize >> 1)) : ++wGSize); + } + + EIGEN_STRONG_INLINE cl::sycl::queue &sycl_queue() const { return m_queue; } + + // This function checks if the runtime recorded an error for the + // underlying stream device. + EIGEN_STRONG_INLINE bool ok() const { + if (!exception_caught_) { + synchronize(); + } + return !exception_caught_; + } + + protected: + void synchronize_and_callback(cl::sycl::event e, + const std::function &callback) const { + if (callback) { + auto callback_ = [=]() { +#ifdef EIGEN_EXCEPTIONS + cl::sycl::event(e).wait_and_throw(); +#else + cl::sycl::event(e).wait(); +#endif + callback(); + }; + m_thread_pool.Schedule(std::move(callback_)); + } else { +#ifdef EIGEN_EXCEPTIONS + m_queue.wait_and_throw(); +#else + m_queue.wait(); +#endif + } + } + + bool sycl_async_handler(cl::sycl::exception_list exceptions) const { + bool exception_caught = false; + for (const auto &e : exceptions) { + if (e) { + exception_caught = true; + EIGEN_THROW_X(e); + } + } + return exception_caught; + } + + /// class members: + bool exception_caught_ = false; + /// sycl queue + mutable cl::sycl::queue m_queue; + /// The thread pool is used to wait on events and call callbacks + /// asynchronously + mutable Eigen::ThreadPool m_thread_pool; + + const TensorSycl::internal::SyclDeviceInfo m_device_info; +}; + +struct SyclDeviceBase { + /// QueueInterface is not owned. it is the caller's responsibility to destroy + /// it + const QueueInterface *m_queue_stream; + explicit SyclDeviceBase(const QueueInterface *queue_stream) + : m_queue_stream(queue_stream) {} + EIGEN_STRONG_INLINE const QueueInterface *queue_stream() const { + return m_queue_stream; + } +}; + +// Here is a sycl device struct which accept the sycl queue interface +// as an input +struct SyclDevice : public SyclDeviceBase { + explicit SyclDevice(const QueueInterface *queue_stream) + : SyclDeviceBase(queue_stream) {} + + /// This is used to prepare the number of threads and also the number of + /// threads per block for sycl kernels + template + EIGEN_STRONG_INLINE void parallel_for_setup(Index n, Index &tileSize, + Index &rng, Index &GRange) const { + queue_stream()->parallel_for_setup(n, tileSize, rng, GRange); + } + + /// This is used to prepare the number of threads and also the number of + /// threads per block for sycl kernels + template + EIGEN_STRONG_INLINE void parallel_for_setup( + const std::array &input_dim, cl::sycl::range<2> &global_range, + cl::sycl::range<2> &local_range) const { + queue_stream()->parallel_for_setup(input_dim, global_range, local_range); + } + + /// This is used to prepare the number of threads and also the number of + /// threads per block for sycl kernels + template + EIGEN_STRONG_INLINE void parallel_for_setup( + const std::array &input_dim, cl::sycl::range<3> &global_range, + cl::sycl::range<3> &local_range) const { + queue_stream()->parallel_for_setup(input_dim, global_range, local_range); + } + + /// allocate device memory + EIGEN_STRONG_INLINE void *allocate(size_t num_bytes) const { + return queue_stream()->allocate(num_bytes); + } + + EIGEN_STRONG_INLINE void *allocate_temp(size_t num_bytes) const { + return queue_stream()->allocate_temp(num_bytes); + } + + /// deallocate device memory + EIGEN_STRONG_INLINE void deallocate(void *p) const { + queue_stream()->deallocate(p); + } + + EIGEN_STRONG_INLINE void deallocate_temp(void *buffer) const { + queue_stream()->deallocate_temp(buffer); + } + + EIGEN_STRONG_INLINE void deallocate_temp(const void *buffer) const { + queue_stream()->deallocate_temp(buffer); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE data_t *get(data_t *data) const { + return data; + } + + // some runtime conditions that can be applied here + EIGEN_STRONG_INLINE bool isDeviceSuitable() const { return true; } + + /// memcpyHostToDevice + template + EIGEN_STRONG_INLINE void memcpyHostToDevice( + Index *dst, const Index *src, size_t n, + std::function callback = {}) const { + queue_stream()->memcpyHostToDevice(dst, src, n, callback); + } + /// memcpyDeviceToHost + template + EIGEN_STRONG_INLINE void memcpyDeviceToHost( + void *dst, const Index *src, size_t n, + std::function callback = {}) const { + queue_stream()->memcpyDeviceToHost(dst, src, n, callback); + } + /// the memcpy function + template + EIGEN_STRONG_INLINE void memcpy(void *dst, const Index *src, size_t n) const { + queue_stream()->memcpy(dst, src, n); + } + /// the memset function + EIGEN_STRONG_INLINE void memset(void *data, int c, size_t n) const { + queue_stream()->memset(data, c, n); + } + /// the fill function + template + EIGEN_STRONG_INLINE void fill(T *begin, T *end, const T &value) const { + queue_stream()->fill(begin, end, value); + } + /// returning the sycl queue + EIGEN_STRONG_INLINE cl::sycl::queue &sycl_queue() const { + return queue_stream()->sycl_queue(); + } + + EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const { return 48 * 1024; } + + EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const { + // We won't try to take advantage of the l2 cache for the time being, and + // there is no l3 cache on sycl devices. + return firstLevelCacheSize(); + } + EIGEN_STRONG_INLINE unsigned long getNumSyclMultiProcessors() const { + return queue_stream()->getNumSyclMultiProcessors(); + } + EIGEN_STRONG_INLINE unsigned long maxSyclThreadsPerBlock() const { + return queue_stream()->maxSyclThreadsPerBlock(); + } + EIGEN_STRONG_INLINE cl::sycl::id<3> maxWorkItemSizes() const { + return queue_stream()->maxWorkItemSizes(); + } + EIGEN_STRONG_INLINE unsigned long maxSyclThreadsPerMultiProcessor() const { + // OpenCL does not have such a concept + return queue_stream()->maxSyclThreadsPerMultiProcessor(); + } + EIGEN_STRONG_INLINE size_t sharedMemPerBlock() const { + return queue_stream()->sharedMemPerBlock(); + } + EIGEN_STRONG_INLINE size_t getNearestPowerOfTwoWorkGroupSize() const { + return queue_stream()->getNearestPowerOfTwoWorkGroupSize(); + } + + EIGEN_STRONG_INLINE size_t getPowerOfTwo(size_t val, bool roundUp) const { + return queue_stream()->getPowerOfTwo(val, roundUp); + } + /// No need for sycl it should act the same as CPU version + EIGEN_STRONG_INLINE int majorDeviceVersion() const { + return queue_stream()->majorDeviceVersion(); + } + + EIGEN_STRONG_INLINE void synchronize() const { + queue_stream()->synchronize(); + } + + // This function checks if the runtime recorded an error for the + // underlying stream device. + EIGEN_STRONG_INLINE bool ok() const { return queue_stream()->ok(); } + + EIGEN_STRONG_INLINE bool has_local_memory() const { + return queue_stream()->has_local_memory(); + } + EIGEN_STRONG_INLINE long max_buffer_size() const { + return queue_stream()->max_buffer_size(); + } + EIGEN_STRONG_INLINE std::string getPlatformName() const { + return queue_stream()->getPlatformName(); + } + EIGEN_STRONG_INLINE std::string getDeviceName() const { + return queue_stream()->getDeviceName(); + } + EIGEN_STRONG_INLINE std::string getDeviceVendor() const { + return queue_stream()->getDeviceVendor(); + } + template + EIGEN_ALWAYS_INLINE cl::sycl::event binary_kernel_launcher(T... var) const { + return queue_stream() + ->template binary_kernel_launcher(var...); + } + template + EIGEN_ALWAYS_INLINE cl::sycl::event unary_kernel_launcher(T... var) const { + return queue_stream() + ->template unary_kernel_launcher(var...); + } + + template + EIGEN_ALWAYS_INLINE cl::sycl::event nullary_kernel_launcher(T... var) const { + return queue_stream() + ->template nullary_kernel_launcher(var...); + } +}; +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_SYCL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h new file mode 100644 index 0000000000000000000000000000000000000000..8858cbc8045c0e5d55a9448ddd39c7d05a441c4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h @@ -0,0 +1,420 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if defined(EIGEN_USE_THREADS) && !defined(EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H) +#define EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +// Runs an arbitrary function and then calls Notify() on the passed in +// Notification. +template struct FunctionWrapperWithNotification +{ + static void run(Notification* n, Function f, Args... args) { + f(args...); + if (n) { + n->Notify(); + } + } +}; + +template struct FunctionWrapperWithBarrier +{ + static void run(Barrier* b, Function f, Args... args) { + f(args...); + if (b) { + b->Notify(); + } + } +}; + +template +static EIGEN_STRONG_INLINE void wait_until_ready(SyncType* n) { + if (n) { + n->Wait(); + } +} + +// An abstract interface to a device specific memory allocator. +class Allocator { + public: + virtual ~Allocator() {} + virtual void* allocate(size_t num_bytes) const = 0; + virtual void deallocate(void* buffer) const = 0; +}; + +// Build a thread pool device on top the an existing pool of threads. +struct ThreadPoolDevice { + // The ownership of the thread pool remains with the caller. + ThreadPoolDevice(ThreadPoolInterface* pool, int num_cores, Allocator* allocator = nullptr) + : pool_(pool), num_threads_(num_cores), allocator_(allocator) { } + + EIGEN_STRONG_INLINE void* allocate(size_t num_bytes) const { + return allocator_ ? allocator_->allocate(num_bytes) + : internal::aligned_malloc(num_bytes); + } + + EIGEN_STRONG_INLINE void deallocate(void* buffer) const { + if (allocator_) { + allocator_->deallocate(buffer); + } else { + internal::aligned_free(buffer); + } + } + + EIGEN_STRONG_INLINE void* allocate_temp(size_t num_bytes) const { + return allocate(num_bytes); + } + + EIGEN_STRONG_INLINE void deallocate_temp(void* buffer) const { + deallocate(buffer); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Type get(Type data) const { + return data; + } + + EIGEN_STRONG_INLINE void memcpy(void* dst, const void* src, size_t n) const { +#ifdef __ANDROID__ + ::memcpy(dst, src, n); +#else + // TODO(rmlarsen): Align blocks on cache lines. + // We have observed that going beyond 4 threads usually just wastes + // CPU cycles due to the threads competing for memory bandwidth, so we + // statically schedule at most 4 block copies here. + const size_t kMinBlockSize = 32768; + const size_t num_threads = CostModel::numThreads(n, TensorOpCost(1.0, 1.0, 0), 4); + if (n <= kMinBlockSize || num_threads < 2) { + ::memcpy(dst, src, n); + } else { + const char* src_ptr = static_cast(src); + char* dst_ptr = static_cast(dst); + const size_t blocksize = (n + (num_threads - 1)) / num_threads; + Barrier barrier(static_cast(num_threads - 1)); + // Launch the last 3 blocks on worker threads. + for (size_t i = 1; i < num_threads; ++i) { + enqueue_with_barrier(&barrier, [n, i, src_ptr, dst_ptr, blocksize] { + ::memcpy(dst_ptr + i * blocksize, src_ptr + i * blocksize, + numext::mini(blocksize, n - (i * blocksize))); + }); + } + // Launch the first block on the main thread. + ::memcpy(dst_ptr, src_ptr, blocksize); + barrier.Wait(); + } +#endif + } + EIGEN_STRONG_INLINE void memcpyHostToDevice(void* dst, const void* src, size_t n) const { + memcpy(dst, src, n); + } + EIGEN_STRONG_INLINE void memcpyDeviceToHost(void* dst, const void* src, size_t n) const { + memcpy(dst, src, n); + } + + EIGEN_STRONG_INLINE void memset(void* buffer, int c, size_t n) const { + ::memset(buffer, c, n); + } + + template + EIGEN_STRONG_INLINE void fill(T* begin, T* end, const T& value) const { + std::fill(begin, end, value); + } + + EIGEN_STRONG_INLINE int numThreads() const { + return num_threads_; + } + + // Number of theads available in the underlying thread pool. This number can + // be different from the value returned by numThreads(). + EIGEN_STRONG_INLINE int numThreadsInPool() const { + return pool_->NumThreads(); + } + + EIGEN_STRONG_INLINE size_t firstLevelCacheSize() const { + return l1CacheSize(); + } + + EIGEN_STRONG_INLINE size_t lastLevelCacheSize() const { + // The l3 cache size is shared between all the cores. + return l3CacheSize() / num_threads_; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void synchronize() const { + // Nothing. Threadpool device operations are synchronous. + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE int majorDeviceVersion() const { + // Should return an enum that encodes the ISA supported by the CPU + return 1; + } + + template + EIGEN_STRONG_INLINE Notification* enqueue(Function&& f, + Args&&... args) const { + Notification* n = new Notification(); + pool_->Schedule( + std::bind(&FunctionWrapperWithNotification::run, n, + std::forward(f), args...)); + return n; + } + + template + EIGEN_STRONG_INLINE void enqueue_with_barrier(Barrier* b, Function&& f, + Args&&... args) const { + pool_->Schedule( + std::bind(&FunctionWrapperWithBarrier::run, b, + std::forward(f), args...)); + } + + template + EIGEN_STRONG_INLINE void enqueueNoNotification(Function&& f, + Args&&... args) const { + if (sizeof...(args) > 0) { + pool_->Schedule(std::bind(std::forward(f), args...)); + } else { + pool_->Schedule(std::forward(f)); + } + } + + // Returns a logical thread index between 0 and pool_->NumThreads() - 1 if + // called from one of the threads in pool_. Returns -1 otherwise. + EIGEN_STRONG_INLINE int currentThreadId() const { + return pool_->CurrentThreadId(); + } + + // WARNING: This function is synchronous and will block the calling thread. + // + // Synchronous parallelFor executes f with [0, n) arguments in parallel and + // waits for completion. F accepts a half-open interval [first, last). Block + // size is chosen based on the iteration cost and resulting parallel + // efficiency. If block_align is not nullptr, it is called to round up the + // block size. + void parallelFor(Index n, const TensorOpCost& cost, + std::function block_align, + std::function f) const { + if (EIGEN_PREDICT_FALSE(n <= 0)){ + return; + // Compute small problems directly in the caller thread. + } else if (n == 1 || numThreads() == 1 || + CostModel::numThreads(n, cost, static_cast(numThreads())) == 1) { + f(0, n); + return; + } + + // Compute block size and total count of blocks. + ParallelForBlock block = CalculateParallelForBlock(n, cost, block_align); + + // Recursively divide size into halves until we reach block_size. + // Division code rounds mid to block_size, so we are guaranteed to get + // block_count leaves that do actual computations. + Barrier barrier(static_cast(block.count)); + std::function handleRange; + handleRange = [=, &handleRange, &barrier, &f](Index firstIdx, + Index lastIdx) { + while (lastIdx - firstIdx > block.size) { + // Split into halves and schedule the second half on a different thread. + const Index midIdx = firstIdx + divup((lastIdx - firstIdx) / 2, block.size) * block.size; + pool_->Schedule([=, &handleRange]() { handleRange(midIdx, lastIdx); }); + lastIdx = midIdx; + } + // Single block or less, execute directly. + f(firstIdx, lastIdx); + barrier.Notify(); + }; + + if (block.count <= numThreads()) { + // Avoid a thread hop by running the root of the tree and one block on the + // main thread. + handleRange(0, n); + } else { + // Execute the root in the thread pool to avoid running work on more than + // numThreads() threads. + pool_->Schedule([=, &handleRange]() { handleRange(0, n); }); + } + + barrier.Wait(); + } + + // Convenience wrapper for parallelFor that does not align blocks. + void parallelFor(Index n, const TensorOpCost& cost, + std::function f) const { + parallelFor(n, cost, nullptr, std::move(f)); + } + + // WARNING: This function is asynchronous and will not block the calling thread. + // + // Asynchronous parallelFor executes f with [0, n) arguments in parallel + // without waiting for completion. When the last block finished, it will call + // 'done' callback. F accepts a half-open interval [first, last). Block size + // is chosen based on the iteration cost and resulting parallel efficiency. If + // block_align is not nullptr, it is called to round up the block size. + void parallelForAsync(Index n, const TensorOpCost& cost, + std::function block_align, + std::function f, + std::function done) const { + // Compute small problems directly in the caller thread. + if (n <= 1 || numThreads() == 1 || + CostModel::numThreads(n, cost, static_cast(numThreads())) == 1) { + f(0, n); + done(); + return; + } + + // Compute block size and total count of blocks. + ParallelForBlock block = CalculateParallelForBlock(n, cost, block_align); + + ParallelForAsyncContext* const ctx = + new ParallelForAsyncContext(block.count, std::move(f), std::move(done)); + + // Recursively divide size into halves until we reach block_size. + // Division code rounds mid to block_size, so we are guaranteed to get + // block_count leaves that do actual computations. + ctx->handle_range = [this, ctx, block](Index firstIdx, Index lastIdx) { + while (lastIdx - firstIdx > block.size) { + // Split into halves and schedule the second half on a different thread. + const Index midIdx = firstIdx + divup((lastIdx - firstIdx) / 2, block.size) * block.size; + pool_->Schedule( + [ctx, midIdx, lastIdx]() { ctx->handle_range(midIdx, lastIdx); }); + lastIdx = midIdx; + } + + // Single block or less, execute directly. + ctx->f(firstIdx, lastIdx); + + // Delete async context if it was the last block. + if (ctx->count.fetch_sub(1) == 1) delete ctx; + }; + + if (block.count <= numThreads()) { + // Avoid a thread hop by running the root of the tree and one block on the + // main thread. + ctx->handle_range(0, n); + } else { + // Execute the root in the thread pool to avoid running work on more than + // numThreads() threads. + pool_->Schedule([ctx, n]() { ctx->handle_range(0, n); }); + } + } + + // Convenience wrapper for parallelForAsync that does not align blocks. + void parallelForAsync(Index n, const TensorOpCost& cost, + std::function f, + std::function done) const { + parallelForAsync(n, cost, nullptr, std::move(f), std::move(done)); + } + + // Thread pool accessor. + ThreadPoolInterface* getPool() const { return pool_; } + + // Allocator accessor. + Allocator* allocator() const { return allocator_; } + + private: + typedef TensorCostModel CostModel; + + // For parallelForAsync we must keep passed in closures on the heap, and + // delete them only after `done` callback finished. + struct ParallelForAsyncContext { + ParallelForAsyncContext(Index block_count, + std::function block_f, + std::function done_callback) + : count(block_count), + f(std::move(block_f)), + done(std::move(done_callback)) {} + ~ParallelForAsyncContext() { done(); } + + std::atomic count; + std::function f; + std::function done; + + std::function handle_range; + }; + + struct ParallelForBlock { + Index size; // block size + Index count; // number of blocks + }; + + // Calculates block size based on (1) the iteration cost and (2) parallel + // efficiency. We want blocks to be not too small to mitigate parallelization + // overheads; not too large to mitigate tail effect and potential load + // imbalance and we also want number of blocks to be evenly dividable across + // threads. + ParallelForBlock CalculateParallelForBlock( + const Index n, const TensorOpCost& cost, + std::function block_align) const { + const double block_size_f = 1.0 / CostModel::taskSize(1, cost); + const Index max_oversharding_factor = 4; + Index block_size = numext::mini( + n, numext::maxi( + divup(n, max_oversharding_factor * numThreads()), + block_size_f)); + const Index max_block_size = numext::mini(n, 2 * block_size); + + if (block_align) { + Index new_block_size = block_align(block_size); + eigen_assert(new_block_size >= block_size); + block_size = numext::mini(n, new_block_size); + } + + Index block_count = divup(n, block_size); + + // Calculate parallel efficiency as fraction of total CPU time used for + // computations: + double max_efficiency = + static_cast(block_count) / + (divup(block_count, numThreads()) * numThreads()); + + // Now try to increase block size up to max_block_size as long as it + // doesn't decrease parallel efficiency. + for (Index prev_block_count = block_count; + max_efficiency < 1.0 && prev_block_count > 1;) { + // This is the next block size that divides size into a smaller number + // of blocks than the current block_size. + Index coarser_block_size = divup(n, prev_block_count - 1); + if (block_align) { + Index new_block_size = block_align(coarser_block_size); + eigen_assert(new_block_size >= coarser_block_size); + coarser_block_size = numext::mini(n, new_block_size); + } + if (coarser_block_size > max_block_size) { + break; // Reached max block size. Stop. + } + // Recalculate parallel efficiency. + const Index coarser_block_count = divup(n, coarser_block_size); + eigen_assert(coarser_block_count < prev_block_count); + prev_block_count = coarser_block_count; + const double coarser_efficiency = + static_cast(coarser_block_count) / + (divup(coarser_block_count, numThreads()) * numThreads()); + if (coarser_efficiency + 0.01 >= max_efficiency) { + // Taking it. + block_size = coarser_block_size; + block_count = coarser_block_count; + if (max_efficiency < coarser_efficiency) { + max_efficiency = coarser_efficiency; + } + } + } + + return {block_size, block_count}; + } + + ThreadPoolInterface* pool_; + int num_threads_; + Allocator* allocator_; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DEVICE_THREAD_POOL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensionList.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensionList.h new file mode 100644 index 0000000000000000000000000000000000000000..c58838e6537b8bb2f772203cd71dc6332a0232ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensionList.h @@ -0,0 +1,143 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_DIMENSION_LIST_H +#define EIGEN_CXX11_TENSOR_TENSOR_DIMENSION_LIST_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \internal + * + * \class TensorDimensionList + * \ingroup CXX11_Tensor_Module + * + * \brief Special case of tensor index list used to list all the dimensions of a tensor of rank n. + * + * \sa Tensor + */ + +template struct DimensionList { + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + const Index operator[] (const Index i) const { return i; } +}; + +namespace internal { + +template struct array_size > { + static const size_t value = Rank; +}; +template struct array_size > { + static const size_t value = Rank; +}; + +template const Index array_get(DimensionList&) { + return n; +} +template const Index array_get(const DimensionList&) { + return n; +} + +template +struct index_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex) { + return true; + } +}; +template +struct index_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex) { + return true; + } +}; + +template +struct all_indices_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return true; + } +}; +template +struct all_indices_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return true; + } +}; + +template +struct indices_statically_known_to_increase_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return true; + } +}; +template +struct indices_statically_known_to_increase_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return true; + } +}; + +template +struct index_statically_eq_impl > { + static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i == value; + } +}; +template +struct index_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i == value; + } +}; + +template +struct index_statically_ne_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i != value; + } +}; +template +struct index_statically_ne_impl > { + static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i != value; + } +}; + +template +struct index_statically_gt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i > value; + } +}; +template +struct index_statically_gt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i > value; + } +}; + +template +struct index_statically_lt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i < value; + } +}; +template +struct index_statically_lt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const DenseIndex i, const DenseIndex value) { + return i < value; + } +}; + +} // end namespace internal +} // end namespace Eigen + + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DIMENSION_LIST_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h new file mode 100644 index 0000000000000000000000000000000000000000..914140deab313b45596b8046ff8e8524e236dac1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h @@ -0,0 +1,447 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_DIMENSIONS_H +#define EIGEN_CXX11_TENSOR_TENSOR_DIMENSIONS_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \internal + * + * \class TensorDimensions + * \ingroup CXX11_Tensor_Module + * + * \brief Set of classes used to encode and store the dimensions of a Tensor. + * + * The Sizes class encodes as part of the type the number of dimensions and the + * sizes corresponding to each dimension. It uses no storage space since it is + * entirely known at compile time. + * The DSizes class is its dynamic sibling: the number of dimensions is known + * at compile time but the sizes are set during execution. + * + * \sa Tensor + */ + +// Boilerplate code +namespace internal { + +template struct dget { + static const std::ptrdiff_t value = get::value; +}; + + +template +struct fixed_size_tensor_index_linearization_helper +{ + template EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Index run(array const& indices, + const Dimensions& dimensions) + { + return array_get(indices) + + dget::value * + fixed_size_tensor_index_linearization_helper::run(indices, dimensions); + } +}; + +template +struct fixed_size_tensor_index_linearization_helper +{ + template EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Index run(array const&, const Dimensions&) + { + return 0; + } +}; + +template +struct fixed_size_tensor_index_extraction_helper +{ + template EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Index run(const Index index, + const Dimensions& dimensions) + { + const Index mult = (index == n-1) ? 1 : 0; + return array_get(dimensions) * mult + + fixed_size_tensor_index_extraction_helper::run(index, dimensions); + } +}; + +template +struct fixed_size_tensor_index_extraction_helper +{ + template EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Index run(const Index, + const Dimensions&) + { + return 0; + } + }; + +} // end namespace internal + + +// Fixed size +#ifndef EIGEN_EMULATE_CXX11_META_H +template +struct Sizes { + typedef internal::numeric_list Base; + const Base t = Base(); + static const std::ptrdiff_t total_size = internal::arg_prod(Indices...); + static const ptrdiff_t count = Base::count; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t rank() const { + return Base::count; + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t TotalSize() { + return internal::arg_prod(Indices...); + } + + EIGEN_DEVICE_FUNC Sizes() { } + template + explicit EIGEN_DEVICE_FUNC Sizes(const array& /*indices*/) { + // todo: add assertion + } + template EIGEN_DEVICE_FUNC Sizes(DenseIndex...) { } + explicit EIGEN_DEVICE_FUNC Sizes(std::initializer_list /*l*/) { + // todo: add assertion + } + + template Sizes& operator = (const T& /*other*/) { + // add assertion failure if the size of other is different + return *this; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t operator[] (const std::ptrdiff_t index) const { + return internal::fixed_size_tensor_index_extraction_helper::run(index, t); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + ptrdiff_t IndexOfColMajor(const array& indices) const { + return internal::fixed_size_tensor_index_linearization_helper::run(indices, t); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + ptrdiff_t IndexOfRowMajor(const array& indices) const { + return internal::fixed_size_tensor_index_linearization_helper::run(indices, t); + } +}; + +namespace internal { +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t array_prod(const Sizes&) { + return Sizes::total_size; +} +} + +#else + +template +struct non_zero_size { + typedef internal::type2val type; +}; +template <> +struct non_zero_size<0> { + typedef internal::null_type type; +}; + +template struct Sizes { + typedef typename internal::make_type_list::type, typename non_zero_size::type, typename non_zero_size::type, typename non_zero_size::type, typename non_zero_size::type >::type Base; + static const std::ptrdiff_t count = Base::count; + static const std::ptrdiff_t total_size = internal::arg_prod::value; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ptrdiff_t rank() const { + return count; + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ptrdiff_t TotalSize() { + return internal::arg_prod::value; + } + + Sizes() { } + template + explicit Sizes(const array& /*indices*/) { + // todo: add assertion + } + + template Sizes& operator = (const T& /*other*/) { + // add assertion failure if the size of other is different + return *this; + } + + template Sizes(DenseIndex... /*indices*/) { } + explicit Sizes(std::initializer_list) { + // todo: add assertion + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index operator[] (const Index index) const { + switch (index) { + case 0: + return internal::get<0, Base>::value; + case 1: + return internal::get<1, Base>::value; + case 2: + return internal::get<2, Base>::value; + case 3: + return internal::get<3, Base>::value; + case 4: + return internal::get<4, Base>::value; + default: + eigen_assert(false && "index overflow"); + return static_cast(-1); + } + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + ptrdiff_t IndexOfColMajor(const array& indices) const { + return internal::fixed_size_tensor_index_linearization_helper::run(indices, *reinterpret_cast(this)); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + ptrdiff_t IndexOfRowMajor(const array& indices) const { + return internal::fixed_size_tensor_index_linearization_helper::run(indices, *reinterpret_cast(this)); + } +}; + +namespace internal { +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t array_prod(const Sizes&) { + return Sizes::total_size; +} +} + +#endif + +// Boilerplate +namespace internal { +template +struct tensor_index_linearization_helper +{ + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index run(array const& indices, array const& dimensions) + { + return array_get(indices) + + array_get(dimensions) * + tensor_index_linearization_helper::run(indices, dimensions); + } +}; + +template +struct tensor_index_linearization_helper +{ + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index run(array const& indices, array const&) + { + return array_get(indices); + } +}; +} // end namespace internal + + + +// Dynamic size +template +struct DSizes : array { + typedef array Base; + static const int count = NumDims; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rank() const { + return NumDims; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex TotalSize() const { + return (NumDims == 0) ? 1 : internal::array_prod(*static_cast(this)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DSizes() { + for (int i = 0 ; i < NumDims; ++i) { + (*this)[i] = 0; + } + } + EIGEN_DEVICE_FUNC explicit DSizes(const array& a) : Base(a) { } + + EIGEN_DEVICE_FUNC explicit DSizes(const DenseIndex i0) { + eigen_assert(NumDims == 1); + (*this)[0] = i0; + } + + EIGEN_DEVICE_FUNC DSizes(const DimensionList& a) { + for (int i = 0 ; i < NumDims; ++i) { + (*this)[i] = a[i]; + } + } + + // Enable DSizes index type promotion only if we are promoting to the + // larger type, e.g. allow to promote dimensions of type int to long. + template + EIGEN_DEVICE_FUNC + explicit DSizes(const array& other, + // Default template parameters require c++11. + std::enable_if_t< + internal::is_same< + DenseIndex, + typename internal::promote_index_type< + DenseIndex, + OtherIndex + >::type + >::value, void*> = 0) { + for (int i = 0; i < NumDims; ++i) { + (*this)[i] = static_cast(other[i]); + } + } + + template + EIGEN_DEVICE_FUNC + explicit DSizes(const Eigen::IndexList& dimensions) { + for (int i = 0; i < dimensions.count; ++i) { + (*this)[i] = dimensions[i]; + } + } + +#ifndef EIGEN_EMULATE_CXX11_META_H + template + EIGEN_DEVICE_FUNC DSizes(const Sizes& a) { + for (int i = 0 ; i < NumDims; ++i) { + (*this)[i] = a[i]; + } + } +#else + template + EIGEN_DEVICE_FUNC DSizes(const Sizes& a) { + for (int i = 0 ; i < NumDims; ++i) { + (*this)[i] = a[i]; + } + } +#endif + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE explicit DSizes(DenseIndex firstDimension, DenseIndex secondDimension, IndexTypes... otherDimensions) : Base({{firstDimension, secondDimension, otherDimensions...}}) { + EIGEN_STATIC_ASSERT(sizeof...(otherDimensions) + 2 == NumDims, YOU_MADE_A_PROGRAMMING_MISTAKE) + } + + EIGEN_DEVICE_FUNC DSizes& operator = (const array& other) { + *static_cast(this) = other; + return *this; + } + + // A constexpr would be so much better here + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex IndexOfColMajor(const array& indices) const { + return internal::tensor_index_linearization_helper::run(indices, *static_cast(this)); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex IndexOfRowMajor(const array& indices) const { + return internal::tensor_index_linearization_helper::run(indices, *static_cast(this)); + } +}; + +template +std::ostream& operator<<(std::ostream& os, + const DSizes& dims) { + os << "["; + for (int i = 0; i < NumDims; ++i) { + if (i > 0) os << ", "; + os << dims[i]; + } + os << "]"; + return os; +} + +// Boilerplate +namespace internal { +template +struct tensor_vsize_index_linearization_helper +{ + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index run(array const& indices, std::vector const& dimensions) + { + return array_get(indices) + + array_get(dimensions) * + tensor_vsize_index_linearization_helper::run(indices, dimensions); + } +}; + +template +struct tensor_vsize_index_linearization_helper +{ + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index run(array const& indices, std::vector const&) + { + return array_get(indices); + } +}; +} // end namespace internal + + +namespace internal { + +template struct array_size > { + static const ptrdiff_t value = NumDims; +}; +template struct array_size > { + static const ptrdiff_t value = NumDims; +}; +#ifndef EIGEN_EMULATE_CXX11_META_H +template struct array_size > { +static const std::ptrdiff_t value = Sizes::count; +}; +template struct array_size > { +static const std::ptrdiff_t value = Sizes::count; +}; +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t array_get(const Sizes&) { + return get >::value; +} +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t array_get(const Sizes<>&) { + eigen_assert(false && "should never be called"); + return -1; +} +#else +template struct array_size > { + static const ptrdiff_t value = Sizes::count; +}; +template struct array_size > { + static const ptrdiff_t value = Sizes::count; +}; +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::ptrdiff_t array_get(const Sizes&) { + return get::Base>::value; +} + +#endif + + +template +struct sizes_match_below_dim { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool run(Dims1&, Dims2&) { + return false; + } +}; +template +struct sizes_match_below_dim { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool run(Dims1& dims1, Dims2& dims2) { + return numext::equal_strict(array_get(dims1), array_get(dims2)) && + sizes_match_below_dim::run(dims1, dims2); + } +}; +template +struct sizes_match_below_dim { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool run(Dims1&, Dims2&) { + return true; + } +}; + +} // end namespace internal + + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool dimensions_match(Dims1 dims1, Dims2 dims2) { + return internal::sizes_match_below_dim::value, internal::array_size::value>::run(dims1, dims2); +} + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_DIMENSIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvalTo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvalTo.h new file mode 100644 index 0000000000000000000000000000000000000000..461763203a8410fc5dd4df0472eac5aa06450d25 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvalTo.h @@ -0,0 +1,233 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_EVAL_TO_H +#define EIGEN_CXX11_TENSOR_TENSOR_EVAL_TO_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorForcedEval + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor reshaping class. + * + * + */ +namespace internal { +template class MakePointer_> +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename MakePointer_::Type PointerType; + + enum { + Flags = 0 + }; + template + struct MakePointer { + // Intermediate typedef to workaround MSVC issue. + typedef MakePointer_ MakePointerT; + typedef typename MakePointerT::Type Type; + + + }; +}; + +template class MakePointer_> +struct eval, Eigen::Dense> +{ + typedef const TensorEvalToOp& type; +}; + +template class MakePointer_> +struct nested, 1, typename eval >::type> +{ + typedef TensorEvalToOp type; +}; + +} // end namespace internal + + + + +template class MakePointer_> +class TensorEvalToOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename MakePointer_::Type PointerType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + static constexpr int NumDims = Eigen::internal::traits::NumDimensions; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorEvalToOp(PointerType buffer, const XprType& expr) + : m_xpr(expr), m_buffer(buffer) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_DEVICE_FUNC PointerType buffer() const { return m_buffer; } + + protected: + typename XprType::Nested m_xpr; + PointerType m_buffer; +}; + + + +template class MakePointer_> +struct TensorEvaluator, Device> +{ + typedef TensorEvalToOp XprType; + typedef typename ArgType::Scalar Scalar; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef typename XprType::Index Index; + typedef std::remove_const_t CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename Eigen::internal::traits::PointerType TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = true, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = true + }; + + static constexpr int Layout = TensorEvaluator::Layout; + static constexpr int NumDims = internal::traits::NumDimensions; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + typedef internal::TensorBlockAssignment< + CoeffReturnType, NumDims, typename ArgTensorBlock::XprType, Index> + TensorBlockAssignment; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_buffer(device.get(op.buffer())), m_expression(op.expression()){} + + + EIGEN_STRONG_INLINE ~TensorEvaluator() { + } + + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_impl.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType scalar) { + EIGEN_UNUSED_VARIABLE(scalar); + eigen_assert(scalar == NULL); + return m_impl.evalSubExprsIfNeeded(m_buffer); + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType scalar, EvalSubExprsCallback done) { + EIGEN_UNUSED_VARIABLE(scalar); + eigen_assert(scalar == NULL); + m_impl.evalSubExprsIfNeededAsync(m_buffer, std::move(done)); + } +#endif + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalScalar(Index i) const { + m_buffer[i] = m_impl.coeff(i); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalPacket(Index i) const { + internal::pstoret(m_buffer + i, m_impl.template packet::IsAligned ? Aligned : Unaligned>(i)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return m_impl.getResourceRequirements(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalBlock( + TensorBlockDesc& desc, TensorBlockScratch& scratch) { + // Add `m_buffer` as destination buffer to the block descriptor. + desc.template AddDestinationBuffer( + /*dst_base=*/m_buffer + desc.offset(), + /*dst_strides=*/internal::strides(m_impl.dimensions())); + + ArgTensorBlock block = + m_impl.block(desc, scratch, /*root_of_expr_ast=*/true); + + // If block was evaluated into a destination buffer, there is no need to do + // an assignment. + if (block.kind() != internal::TensorBlockKind::kMaterializedInOutput) { + TensorBlockAssignment::Run( + TensorBlockAssignment::target( + desc.dimensions(), internal::strides(m_impl.dimensions()), + m_buffer, desc.offset()), + block.expr()); + } + block.cleanup(); + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_buffer[index]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return internal::ploadt(m_buffer + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + // We assume that evalPacket or evalScalar is called to perform the + // assignment and account for the cost of the write here. + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, sizeof(CoeffReturnType), 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_buffer; } + ArgType expression() const { return m_expression; } + + + + + private: + TensorEvaluator m_impl; + EvaluatorPointerType m_buffer; + const ArgType m_expression; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_EVAL_TO_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h new file mode 100644 index 0000000000000000000000000000000000000000..e5beb82a29f1fc52b6f0079a301d3e279c1dc3f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h @@ -0,0 +1,967 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_EVALUATOR_H +#define EIGEN_CXX11_TENSOR_TENSOR_EVALUATOR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorEvaluator + * \ingroup CXX11_Tensor_Module + * + * \brief The tensor evaluator classes. + * + * These classes are responsible for the evaluation of the tensor expression. + * + * TODO: add support for more types of expressions, in particular expressions + * leading to lvalues (slicing, reshaping, etc...) + */ + +// Generic evaluator +template +struct TensorEvaluator +{ + typedef typename Derived::Index Index; + typedef typename Derived::Scalar Scalar; + typedef typename Derived::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename Derived::Dimensions Dimensions; + typedef Derived XprType; + static constexpr int PacketSize = PacketType::size; + typedef typename internal::traits::template MakePointer::Type TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + // NumDimensions is -1 for variable dim tensors + static constexpr int NumCoords = internal::traits::NumDimensions > 0 ? + internal::traits::NumDimensions : 0; + static constexpr int Layout = Derived::Layout; + + enum { + IsAligned = Derived::IsAligned, + PacketAccess = (PacketType::size > 1), + BlockAccess = internal::is_arithmetic>::value, + PreferBlockAccess = false, + CoordAccess = NumCoords > 0, + RawAccess = true + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorEvaluator(const Derived& m, const Device& device) + : m_data(device.get((const_cast(m.data())))), + m_dims(m.dimensions()), + m_device(device) + { } + + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dims; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType dest) { + if (!NumTraits>::RequireInitialization && dest) { + m_device.memcpy((void*)(m_device.get(dest)), m_device.get(m_data), m_dims.TotalSize() * sizeof(Scalar)); + return false; + } + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType dest, EvalSubExprsCallback done) { + // TODO(ezhulenev): ThreadPoolDevice memcpy is blockign operation. + done(evalSubExprsIfNeeded(dest)); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + eigen_assert(m_data != NULL); + return m_data[index]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const{ + eigen_assert(m_data != NULL); + return m_data[index]; + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketReturnType packet(Index index) const + { + return internal::ploadt(m_data + index); + } + + // Return a packet starting at `index` where `umask` specifies which elements + // have to be loaded. Type/size of mask depends on PacketReturnType, e.g. for + // Packet16f, `umask` is of type uint16_t and if a bit is 1, corresponding + // float element will be loaded, otherwise 0 will be loaded. + // Function has been templatized to enable Sfinae. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t::masked_load_available, PacketReturnTypeT> + partialPacket(Index index, typename internal::unpacket_traits::mask_t umask) const + { + return internal::ploadu(m_data + index, umask); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + return internal::pstoret(m_data + index, x); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(const array& coords) const { + eigen_assert(m_data != NULL); + if (static_cast(Layout) == static_cast(ColMajor)) { + return m_data[m_dims.IndexOfColMajor(coords)]; + } else { + return m_data[m_dims.IndexOfRowMajor(coords)]; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& + coeffRef(const array& coords) const { + eigen_assert(m_data != NULL); + if (static_cast(Layout) == static_cast(ColMajor)) { + return m_data[m_dims.IndexOfColMajor(coords)]; + } else { + return m_data[m_dims.IndexOfRowMajor(coords)]; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, + PacketType::size); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return internal::TensorBlockResourceRequirements::any(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + eigen_assert(m_data != NULL); + return TensorBlock::materialize(m_data, m_dims, desc, scratch); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock( + const TensorBlockDesc& desc, const TensorBlock& block) { + eigen_assert(m_data != NULL); + + typedef typename TensorBlock::XprType TensorBlockExpr; + typedef internal::TensorBlockAssignment + TensorBlockAssign; + + TensorBlockAssign::Run( + TensorBlockAssign::target(desc.dimensions(), + internal::strides(m_dims), m_data, + desc.offset()), + block.expr()); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_data; } + + protected: + EvaluatorPointerType m_data; + Dimensions m_dims; + const Device EIGEN_DEVICE_REF m_device; +}; + +namespace internal { +template EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T loadConstant(const T* address) { + return *address; +} +// Use the texture cache on CUDA devices whenever possible +#if defined(EIGEN_CUDA_ARCH) && EIGEN_CUDA_ARCH >= 350 +template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float loadConstant(const float* address) { + return __ldg(address); +} +template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double loadConstant(const double* address) { + return __ldg(address); +} +template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +Eigen::half loadConstant(const Eigen::half* address) { + return Eigen::half(half_impl::raw_uint16_to_half(__ldg(&address->x))); +} +#endif + +} // namespace internal + +// Default evaluator for rvalues +template +struct TensorEvaluator +{ + typedef typename Derived::Index Index; + typedef typename Derived::Scalar Scalar; + typedef typename Derived::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename Derived::Dimensions Dimensions; + typedef const Derived XprType; + typedef typename internal::traits::template MakePointer::Type TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + typedef std::remove_const_t ScalarNoConst; + + // NumDimensions is -1 for variable dim tensors + static constexpr int NumCoords = internal::traits::NumDimensions > 0 ? + internal::traits::NumDimensions : 0; + static constexpr int PacketSize = PacketType::size; + static constexpr int Layout = Derived::Layout; + + enum { + IsAligned = Derived::IsAligned, + PacketAccess = (PacketType::size > 1), + BlockAccess = internal::is_arithmetic::value, + PreferBlockAccess = false, + CoordAccess = NumCoords > 0, + RawAccess = true + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC + TensorEvaluator(const Derived& m, const Device& device) + : m_data(device.get(m.data())), m_dims(m.dimensions()), m_device(device) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dims; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + if (!NumTraits>::RequireInitialization && data) { + m_device.memcpy((void*)(m_device.get(data)),m_device.get(m_data), m_dims.TotalSize() * sizeof(Scalar)); + return false; + } + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType dest, EvalSubExprsCallback done) { + // TODO(ezhulenev): ThreadPoolDevice memcpy is a blockign operation. + done(evalSubExprsIfNeeded(dest)); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + eigen_assert(m_data != NULL); + return internal::loadConstant(m_data+index); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketReturnType packet(Index index) const + { + return internal::ploadt_ro(m_data + index); + } + + // Return a packet starting at `index` where `umask` specifies which elements + // have to be loaded. Type/size of mask depends on PacketReturnType, e.g. for + // Packet16f, `umask` is of type uint16_t and if a bit is 1, corresponding + // float element will be loaded, otherwise 0 will be loaded. + // Function has been templatized to enable Sfinae. + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + std::enable_if_t::masked_load_available, PacketReturnTypeT> + partialPacket(Index index, typename internal::unpacket_traits::mask_t umask) const + { + return internal::ploadu(m_data + index, umask); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(const array& coords) const { + eigen_assert(m_data != NULL); + const Index index = (static_cast(Layout) == static_cast(ColMajor)) ? m_dims.IndexOfColMajor(coords) + : m_dims.IndexOfRowMajor(coords); + return internal::loadConstant(m_data+index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, + PacketType::size); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return internal::TensorBlockResourceRequirements::any(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + eigen_assert(m_data != NULL); + return TensorBlock::materialize(m_data, m_dims, desc, scratch); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_data; } + + protected: + EvaluatorPointerType m_data; + Dimensions m_dims; + const Device EIGEN_DEVICE_REF m_device; +}; + + + + +// -------------------- CwiseNullaryOp -------------------- + +template +struct TensorEvaluator, Device> +{ + typedef TensorCwiseNullaryOp XprType; + + EIGEN_DEVICE_FUNC + TensorEvaluator(const XprType& op, const Device& device) + : m_functor(op.functor()), m_argImpl(op.nestedExpression(), device), m_wrapper() + { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename internal::traits::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = true, + PacketAccess = internal::functor_traits::PacketAccess + #ifdef EIGEN_USE_SYCL + && (PacketType::size >1) + #endif + , + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_argImpl.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { return true; } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + done(true); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { } + + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_wrapper(m_functor, index); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_wrapper.template packetOp(m_functor, index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, + PacketType::size); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + private: + const NullaryOp m_functor; + TensorEvaluator m_argImpl; + const internal::nullary_wrapper m_wrapper; +}; + + + +// -------------------- CwiseUnaryOp -------------------- + +template +struct TensorEvaluator, Device> +{ + typedef TensorCwiseUnaryOp XprType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = int(TensorEvaluator::PacketAccess) & + int(internal::functor_traits::PacketAccess), + BlockAccess = TensorEvaluator::BlockAccess, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + EIGEN_DEVICE_FUNC + TensorEvaluator(const XprType& op, const Device& device) + : m_device(device), + m_functor(op.functor()), + m_argImpl(op.nestedExpression(), device) + { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef std::remove_const_t ScalarNoConst; + typedef typename internal::traits::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + static constexpr int NumDims = internal::array_size::value; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + typedef internal::TensorCwiseUnaryBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_argImpl.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_argImpl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_argImpl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_argImpl.cleanup(); + } + + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_functor(m_argImpl.coeff(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_functor.packetOp(m_argImpl.template packet(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + const double functor_cost = internal::functor_traits::Cost; + return m_argImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, functor_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + static const double functor_cost = internal::functor_traits::Cost; + return m_argImpl.getResourceRequirements().addCostPerCoeff( + {0, 0, functor_cost / PacketSize}); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + return TensorBlock(m_argImpl.block(desc, scratch), m_functor); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + private: + const Device EIGEN_DEVICE_REF m_device; + const UnaryOp m_functor; + TensorEvaluator m_argImpl; +}; + + +// -------------------- CwiseBinaryOp -------------------- + +template +struct TensorEvaluator, Device> +{ + typedef TensorCwiseBinaryOp XprType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = int(TensorEvaluator::IsAligned) & + int(TensorEvaluator::IsAligned), + PacketAccess = int(TensorEvaluator::PacketAccess) & + int(TensorEvaluator::PacketAccess) & + int(internal::functor_traits::PacketAccess), + BlockAccess = int(TensorEvaluator::BlockAccess) & + int(TensorEvaluator::BlockAccess), + PreferBlockAccess = int(TensorEvaluator::PreferBlockAccess) | + int(TensorEvaluator::PreferBlockAccess), + CoordAccess = false, // to be implemented + RawAccess = false + }; + + EIGEN_DEVICE_FUNC + TensorEvaluator(const XprType& op, const Device& device) + : m_device(device), + m_functor(op.functor()), + m_leftImpl(op.lhsExpression(), device), + m_rightImpl(op.rhsExpression(), device) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout) || internal::traits::NumDimensions <= 1), YOU_MADE_A_PROGRAMMING_MISTAKE); + eigen_assert(dimensions_match(m_leftImpl.dimensions(), m_rightImpl.dimensions())); + } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename internal::traits::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int NumDims = internal::array_size< + typename TensorEvaluator::Dimensions>::value; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + LeftTensorBlock; + typedef typename TensorEvaluator::TensorBlock + RightTensorBlock; + + typedef internal::TensorCwiseBinaryBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const + { + // TODO: use right impl instead if right impl dimensions are known at compile time. + return m_leftImpl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_leftImpl.evalSubExprsIfNeeded(NULL); + m_rightImpl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + // TODO(ezhulenev): Evaluate two expression in parallel? + m_leftImpl.evalSubExprsIfNeededAsync(nullptr, [this, done](bool) { + m_rightImpl.evalSubExprsIfNeededAsync(nullptr, + [done](bool) { done(true); }); + }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_leftImpl.cleanup(); + m_rightImpl.cleanup(); + } + + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_functor(m_leftImpl.coeff(index), m_rightImpl.coeff(index)); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_functor.packetOp(m_leftImpl.template packet(index), m_rightImpl.template packet(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double functor_cost = internal::functor_traits::Cost; + return m_leftImpl.costPerCoeff(vectorized) + + m_rightImpl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, functor_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + static const double functor_cost = internal::functor_traits::Cost; + return internal::TensorBlockResourceRequirements::merge( + m_leftImpl.getResourceRequirements(), + m_rightImpl.getResourceRequirements()) + .addCostPerCoeff({0, 0, functor_cost / PacketSize}); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + desc.DropDestinationBuffer(); + return TensorBlock(m_leftImpl.block(desc, scratch), + m_rightImpl.block(desc, scratch), m_functor); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + private: + const Device EIGEN_DEVICE_REF m_device; + const BinaryOp m_functor; + TensorEvaluator m_leftImpl; + TensorEvaluator m_rightImpl; +}; + +// -------------------- CwiseTernaryOp -------------------- + +template +struct TensorEvaluator, Device> +{ + typedef TensorCwiseTernaryOp XprType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned & TensorEvaluator::IsAligned & TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess && + internal::functor_traits::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + EIGEN_DEVICE_FUNC + TensorEvaluator(const XprType& op, const Device& device) + : m_functor(op.functor()), + m_arg1Impl(op.arg1Expression(), device), + m_arg2Impl(op.arg2Expression(), device), + m_arg3Impl(op.arg3Expression(), device) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout) || internal::traits::NumDimensions <= 1), YOU_MADE_A_PROGRAMMING_MISTAKE); + + EIGEN_STATIC_ASSERT((internal::is_same::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + EIGEN_STATIC_ASSERT((internal::is_same::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + EIGEN_STATIC_ASSERT((internal::is_same::Index, + typename internal::traits::Index>::value), + STORAGE_INDEX_MUST_MATCH) + EIGEN_STATIC_ASSERT((internal::is_same::Index, + typename internal::traits::Index>::value), + STORAGE_INDEX_MUST_MATCH) + + eigen_assert(dimensions_match(m_arg1Impl.dimensions(), m_arg2Impl.dimensions()) && dimensions_match(m_arg1Impl.dimensions(), m_arg3Impl.dimensions())); + } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename internal::traits::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const + { + // TODO: use arg2 or arg3 dimensions if they are known at compile time. + return m_arg1Impl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_arg1Impl.evalSubExprsIfNeeded(NULL); + m_arg2Impl.evalSubExprsIfNeeded(NULL); + m_arg3Impl.evalSubExprsIfNeeded(NULL); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_arg1Impl.cleanup(); + m_arg2Impl.cleanup(); + m_arg3Impl.cleanup(); + } + + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_functor(m_arg1Impl.coeff(index), m_arg2Impl.coeff(index), m_arg3Impl.coeff(index)); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_functor.packetOp(m_arg1Impl.template packet(index), + m_arg2Impl.template packet(index), + m_arg3Impl.template packet(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double functor_cost = internal::functor_traits::Cost; + return m_arg1Impl.costPerCoeff(vectorized) + + m_arg2Impl.costPerCoeff(vectorized) + + m_arg3Impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, functor_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + private: + const TernaryOp m_functor; + TensorEvaluator m_arg1Impl; + TensorEvaluator m_arg2Impl; + TensorEvaluator m_arg3Impl; +}; + + +// -------------------- SelectOp -------------------- + +template +struct TensorEvaluator, Device> +{ + typedef TensorSelectOp XprType; + typedef typename XprType::Scalar Scalar; + + using TernarySelectOp = internal::scalar_boolean_select_op::Scalar, + typename internal::traits::Scalar, + typename internal::traits::Scalar>; + static constexpr bool TernaryPacketAccess = + TensorEvaluator::PacketAccess && TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess && internal::functor_traits::PacketAccess; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned & + TensorEvaluator::IsAligned, + PacketAccess = (TensorEvaluator::PacketAccess && + TensorEvaluator::PacketAccess && + PacketType::HasBlend) || TernaryPacketAccess, + BlockAccess = TensorEvaluator::BlockAccess && + TensorEvaluator::BlockAccess && + TensorEvaluator::BlockAccess, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess || + TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + EIGEN_DEVICE_FUNC + TensorEvaluator(const XprType& op, const Device& device) + : m_condImpl(op.ifExpression(), device), + m_thenImpl(op.thenExpression(), device), + m_elseImpl(op.elseExpression(), device) + { + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT((static_cast(TensorEvaluator::Layout) == static_cast(TensorEvaluator::Layout)), YOU_MADE_A_PROGRAMMING_MISTAKE); + eigen_assert(dimensions_match(m_condImpl.dimensions(), m_thenImpl.dimensions())); + eigen_assert(dimensions_match(m_thenImpl.dimensions(), m_elseImpl.dimensions())); + } + + typedef typename XprType::Index Index; + typedef typename internal::traits::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int NumDims = internal::array_size::value; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + IfArgTensorBlock; + typedef typename TensorEvaluator::TensorBlock + ThenArgTensorBlock; + typedef typename TensorEvaluator::TensorBlock + ElseArgTensorBlock; + + struct TensorSelectOpBlockFactory { + template + struct XprType { + typedef TensorSelectOp type; + }; + + template + typename XprType::type expr( + const IfArgXprType& if_expr, const ThenArgXprType& then_expr, const ElseArgXprType& else_expr) const { + return typename XprType::type(if_expr, then_expr, else_expr); + } + }; + + typedef internal::TensorTernaryExprBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const + { + // TODO: use then or else impl instead if they happen to be known at compile time. + return m_condImpl.dimensions(); + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_condImpl.evalSubExprsIfNeeded(NULL); + m_thenImpl.evalSubExprsIfNeeded(NULL); + m_elseImpl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_condImpl.evalSubExprsIfNeeded(nullptr, [this, done](bool) { + m_thenImpl.evalSubExprsIfNeeded(nullptr, [this, done](bool) { + m_elseImpl.evalSubExprsIfNeeded(nullptr, [done](bool) { done(true); }); + }); + }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_condImpl.cleanup(); + m_thenImpl.cleanup(); + m_elseImpl.cleanup(); + } + + EIGEN_DEVICE_FUNC CoeffReturnType coeff(Index index) const + { + return m_condImpl.coeff(index) ? m_thenImpl.coeff(index) : m_elseImpl.coeff(index); + } + + template = true> + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const + { + internal::Selector select; + EIGEN_UNROLL_LOOP + for (Index i = 0; i < PacketSize; ++i) { + select.select[i] = m_condImpl.coeff(index+i); + } + return internal::pblend(select, + m_thenImpl.template packet(index), + m_elseImpl.template packet(index)); + + } + + template = true> + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const { + return TernarySelectOp().template packetOp(m_thenImpl.template packet(index), + m_elseImpl.template packet(index), + m_condImpl.template packet(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + return m_condImpl.costPerCoeff(vectorized) + + m_thenImpl.costPerCoeff(vectorized) + .cwiseMax(m_elseImpl.costPerCoeff(vectorized)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + auto then_req = m_thenImpl.getResourceRequirements(); + auto else_req = m_elseImpl.getResourceRequirements(); + + auto merged_req = + internal::TensorBlockResourceRequirements::merge(then_req, else_req); + merged_req.cost_per_coeff = + then_req.cost_per_coeff.cwiseMax(else_req.cost_per_coeff); + + return internal::TensorBlockResourceRequirements::merge( + m_condImpl.getResourceRequirements(), merged_req); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + // It's unsafe to pass destination buffer to underlying expressions, because + // output might be aliased with one of the inputs. + desc.DropDestinationBuffer(); + + return TensorBlock( + m_condImpl.block(desc, scratch), m_thenImpl.block(desc, scratch), + m_elseImpl.block(desc, scratch), TensorSelectOpBlockFactory()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return NULL; } + +#ifdef EIGEN_USE_SYCL + // binding placeholder accessors to a command group handler for SYCL + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void bind(cl::sycl::handler &cgh) const { + m_condImpl.bind(cgh); + m_thenImpl.bind(cgh); + m_elseImpl.bind(cgh); + } +#endif + private: + TensorEvaluator m_condImpl; + TensorEvaluator m_thenImpl; + TensorEvaluator m_elseImpl; +}; + +} // end namespace Eigen + +#if defined(EIGEN_USE_SYCL) && defined(SYCL_COMPILER_IS_DPCPP) +template +struct cl::sycl::is_device_copyable< + Eigen::TensorEvaluator, + std::enable_if_t>::value>> : std::true_type {}; +#endif + +#endif // EIGEN_CXX11_TENSOR_TENSOR_EVALUATOR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExecutor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExecutor.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b99e963b0bec1195885c5bc69b20ffd3e4a5ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExecutor.h @@ -0,0 +1,758 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_EXECUTOR_H +#define EIGEN_CXX11_TENSOR_TENSOR_EXECUTOR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** + * \class TensorExecutor + * \ingroup CXX11_Tensor_Module + * + * \brief The tensor executor class. + * + * This class is responsible for launch the evaluation of the expression on + * the specified computing device. + * + * @tparam Vectorizable can use packet math (SSE/AVX/etc... registers and + * instructions) + * @tparam Tiling can use block based tensor evaluation + * (see TensorBlock.h) + */ +namespace internal { + +/** + * Evaluating TensorBroadcastingOp via coefficient of packet path is extremely + * expensive. If expression has at least one broadcast op in it, and it supports + * block based evaluation, we always prefer it, even for the small tensors. For + * all other tileable ops, block evaluation overhead for small tensors (fits + * into L1) is too large, and we fallback on vectorized evaluation. + */ + +// TODO(ezhulenev): Add specializations for all other types of Tensor ops. + +template +struct ExpressionHasTensorBroadcastingOp { + enum { value = false }; +}; + +template +struct ExpressionHasTensorBroadcastingOp< + const TensorAssignOp > { + enum { value = ExpressionHasTensorBroadcastingOp::value }; +}; + +template +struct ExpressionHasTensorBroadcastingOp< + const TensorCwiseUnaryOp > { + enum { value = ExpressionHasTensorBroadcastingOp::value }; +}; + +template +struct ExpressionHasTensorBroadcastingOp< + const TensorCwiseBinaryOp > { + enum { + value = ExpressionHasTensorBroadcastingOp::value || + ExpressionHasTensorBroadcastingOp::value + }; +}; + +template +struct ExpressionHasTensorBroadcastingOp< + const TensorBroadcastingOp > { + enum { value = true }; +}; + +// -------------------------------------------------------------------------- // + +/** + * Default strategy: the expression is evaluated sequentially with a single cpu + * thread, without vectorization and block evaluation. + */ +template +class TensorExecutor { + public: + typedef typename Expression::Index StorageIndex; + + // Including `unsupported/Eigen/CXX11/Tensor` in different translation units + // with/without `EIGEN_USE_THREADS` or `EIGEN_USE_GPU` is a potential ODR + // violation. If this template is instantiated with a non-default device, it + // means that this header file was included without defining + // `EIGEN_USE_THREADS`, `EIGEN_USE_GPU` or `EIGEN_USE_SYCL`. + static_assert(std::is_same::value, + "Default executor instantiated with non-default device. " + "You must #define EIGEN_USE_THREADS, EIGEN_USE_GPU or " + "EIGEN_USE_SYCL before including Eigen headers."); + + static EIGEN_STRONG_INLINE void run(const Expression& expr, + const Device& device = DefaultDevice()) { + TensorEvaluator evaluator(expr, device); + const bool needs_assign = evaluator.evalSubExprsIfNeeded(NULL); + if (needs_assign) { + const StorageIndex size = array_prod(evaluator.dimensions()); + for (StorageIndex i = 0; i < size; ++i) { + evaluator.evalScalar(i); + } + } + evaluator.cleanup(); + } +}; + +/** + * Default async execution strategy is not implemented. Currently it's only + * available for ThreadPoolDevice (see definition below). + */ +template +class TensorAsyncExecutor {}; + +/** + * Process all the data with a single cpu thread, using vectorized instructions. + */ +template +class TensorExecutor { + public: + typedef typename Expression::Index StorageIndex; + + static EIGEN_STRONG_INLINE void run( + const Expression& expr, const DefaultDevice& device = DefaultDevice()) { + TensorEvaluator evaluator(expr, device); + const bool needs_assign = evaluator.evalSubExprsIfNeeded(NULL); + if (needs_assign) { + const StorageIndex size = array_prod(evaluator.dimensions()); + const int PacketSize = unpacket_traits::PacketReturnType>::size; + + // Give compiler a strong possibility to unroll the loop. But don't insist + // on unrolling, because if the function is expensive compiler should not + // unroll the loop at the expense of inlining. + const StorageIndex UnrolledSize = + (size / (4 * PacketSize)) * 4 * PacketSize; + for (StorageIndex i = 0; i < UnrolledSize; i += 4 * PacketSize) { + for (StorageIndex j = 0; j < 4; j++) { + evaluator.evalPacket(i + j * PacketSize); + } + } + const StorageIndex VectorizedSize = (size / PacketSize) * PacketSize; + for (StorageIndex i = UnrolledSize; i < VectorizedSize; i += PacketSize) { + evaluator.evalPacket(i); + } + for (StorageIndex i = VectorizedSize; i < size; ++i) { + evaluator.evalScalar(i); + } + } + evaluator.cleanup(); + } +}; + +/** + * Process all the data with a single cpu thread, using blocks of data. By + * sizing a block to fit L1 cache we get better cache performance. + */ +template +class TensorExecutor { + public: + typedef typename traits::Scalar Scalar; + typedef std::remove_const_t ScalarNoConst; + + typedef TensorEvaluator Evaluator; + typedef typename traits::Index StorageIndex; + + static constexpr int NumDims = traits::NumDimensions; + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void run(const Expression& expr, + const DefaultDevice& device = DefaultDevice()) { + typedef TensorBlockMapper + TensorBlockMapper; + + typedef internal::TensorBlockDescriptor + TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator + TensorBlockScratch; + + Evaluator evaluator(expr, device); + + // TODO(ezhulenev): Do not use tiling for small tensors? + const bool needs_assign = evaluator.evalSubExprsIfNeeded(NULL); + + if (needs_assign) { + // Query expression tree for desired block size/shape. + const TensorBlockResourceRequirements requirements = + evaluator.getResourceRequirements(); + + const TensorBlockMapper block_mapper( + typename TensorBlockDesc::Dimensions(evaluator.dimensions()), + requirements); + + // Share scratch memory allocator between all blocks. + TensorBlockScratch scratch(device); + + const StorageIndex total_block_count = block_mapper.blockCount(); + for (StorageIndex i = 0; i < total_block_count; ++i) { + TensorBlockDesc desc = block_mapper.blockDescriptor(i); + evaluator.evalBlock(desc, scratch); + scratch.reset(); + } + } + evaluator.cleanup(); + } +}; + +/** + * Multicore strategy: the index space is partitioned and each partition is + * executed on a single core. + * + * (1) TensorExecutor will submit work to the ThreadPoolDevice managed thread + * pool, and will block the caller thread until all tasks are finished. + * + * (2) TensorAsyncExecutor is a non-blocking version, that will submit work to + * the ThreadPoolDevice managed thread pool, and will return immediately. + * It will call 'done' callback after all tasks are finished. + */ +#ifdef EIGEN_USE_THREADS + +template +struct TensorExecutorTilingContext { + TensorExecutorTilingContext() = default; + TensorExecutorTilingContext(const TensorBlockMapper& b_mapper, + const TensorOpCost& b_cost, size_t b_aligned_size) + : block_mapper(b_mapper), + cost(b_cost), + aligned_blocksize(b_aligned_size) {} + + TensorBlockMapper block_mapper; // navigate through blocks + TensorOpCost cost; // cost of computing a single block + size_t aligned_blocksize; // block size after memory alignment +}; + +// Computes a block evaluation parameters, and allocates temporary memory buffer +// for blocks. See TensorExecutor/TensorAsyncExecutor (Tiling=On) below. +template +TensorExecutorTilingContext GetTensorExecutorTilingContext( + const Evaluator& evaluator) { + // Query expression tree for desired block size/shape. + TensorBlockResourceRequirements requirements = + evaluator.getResourceRequirements(); + + // Update target block size based on cost model. + double taskSize = TensorCostModel::taskSize( + 1, requirements.cost_per_coeff); + requirements.size = static_cast(1.0 / taskSize); + + TensorBlockMapper block_mapper( + typename TensorBlockMapper::Dimensions(evaluator.dimensions()), + requirements); + + size_t block_size = block_mapper.blockTotalSize(); + const size_t align = numext::maxi(EIGEN_MAX_ALIGN_BYTES, 1); + const size_t aligned_blocksize = + align * + divup(block_size * sizeof(typename Evaluator::Scalar), align); + + return {block_mapper, requirements.cost_per_coeff * block_size, + aligned_blocksize}; +} + +template +struct EvalRange { + static void run(Evaluator* evaluator_in, const StorageIndex firstIdx, + const StorageIndex lastIdx) { + Evaluator evaluator = *evaluator_in; + eigen_assert(lastIdx >= firstIdx); + for (StorageIndex i = firstIdx; i < lastIdx; ++i) { + evaluator.evalScalar(i); + } + } + + static StorageIndex alignBlockSize(StorageIndex size) { return size; } +}; + +template +struct EvalRange { + static constexpr int PacketSize = + unpacket_traits::size; + + static void run(Evaluator* evaluator_in, const StorageIndex firstIdx, + const StorageIndex lastIdx) { + Evaluator evaluator = *evaluator_in; + eigen_assert(lastIdx >= firstIdx); + StorageIndex i = firstIdx; + if (lastIdx - firstIdx >= PacketSize) { + eigen_assert(firstIdx % PacketSize == 0); + StorageIndex last_chunk_offset = lastIdx - 4 * PacketSize; + // Give compiler a strong possibility to unroll the loop. But don't insist + // on unrolling, because if the function is expensive compiler should not + // unroll the loop at the expense of inlining. + for (; i <= last_chunk_offset; i += 4 * PacketSize) { + for (StorageIndex j = 0; j < 4; j++) { + evaluator.evalPacket(i + j * PacketSize); + } + } + last_chunk_offset = lastIdx - PacketSize; + for (; i <= last_chunk_offset; i += PacketSize) { + evaluator.evalPacket(i); + } + } + for (; i < lastIdx; ++i) { + evaluator.evalScalar(i); + } + } + + static StorageIndex alignBlockSize(StorageIndex size) { + // Align block size to packet size and account for unrolling in run above. + if (size >= 16 * PacketSize) { + return (size + 4 * PacketSize - 1) & ~(4 * PacketSize - 1); + } + // Aligning to 4 * PacketSize would increase block size by more than 25%. + return (size + PacketSize - 1) & ~(PacketSize - 1); + } +}; + +template +class TensorExecutor { + public: + typedef typename Expression::Index StorageIndex; + + static EIGEN_STRONG_INLINE void run(const Expression& expr, + const ThreadPoolDevice& device) { + typedef TensorEvaluator Evaluator; + typedef EvalRange EvalRange; + + Evaluator evaluator(expr, device); + const bool needs_assign = evaluator.evalSubExprsIfNeeded(nullptr); + if (needs_assign) { + const StorageIndex size = array_prod(evaluator.dimensions()); + device.parallelFor(size, evaluator.costPerCoeff(Vectorizable), + EvalRange::alignBlockSize, + [&evaluator](StorageIndex firstIdx, StorageIndex lastIdx) { + EvalRange::run(&evaluator, firstIdx, lastIdx); + }); + } + evaluator.cleanup(); + } +}; + +template +class TensorExecutor { + public: + typedef typename traits::Index IndexType; + typedef typename traits::Scalar Scalar; + typedef std::remove_const_t ScalarNoConst; + + static constexpr int NumDims = traits::NumDimensions; + + typedef TensorEvaluator Evaluator; + typedef TensorBlockMapper BlockMapper; + typedef TensorExecutorTilingContext TilingContext; + + typedef internal::TensorBlockDescriptor + TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator + TensorBlockScratch; + + static EIGEN_STRONG_INLINE void run(const Expression& expr, + const ThreadPoolDevice& device) { + Evaluator evaluator(expr, device); + + const bool needs_assign = evaluator.evalSubExprsIfNeeded(nullptr); + if (needs_assign) { + const TilingContext tiling = + internal::GetTensorExecutorTilingContext(evaluator); + + auto eval_block = [&device, &evaluator, &tiling](IndexType firstBlockIdx, + IndexType lastBlockIdx) { + TensorBlockScratch scratch(device); + + for (IndexType block_idx = firstBlockIdx; block_idx < lastBlockIdx; + ++block_idx) { + TensorBlockDesc desc = tiling.block_mapper.blockDescriptor(block_idx); + evaluator.evalBlock(desc, scratch); + scratch.reset(); + } + }; + + // Evaluate small expressions directly as a single block. + if (tiling.block_mapper.blockCount() == 1) { + TensorBlockScratch scratch(device); + TensorBlockDesc desc(0, tiling.block_mapper.blockDimensions()); + evaluator.evalBlock(desc, scratch); + } else { + device.parallelFor(tiling.block_mapper.blockCount(), tiling.cost, + eval_block); + } + } + evaluator.cleanup(); + } +}; + +template +class TensorAsyncExecutor { + public: + typedef typename Expression::Index StorageIndex; + typedef TensorEvaluator Evaluator; + + static EIGEN_STRONG_INLINE void runAsync(const Expression& expr, + const ThreadPoolDevice& device, + DoneCallback done) { + TensorAsyncExecutorContext* const ctx = + new TensorAsyncExecutorContext(expr, device, std::move(done)); + + const auto on_eval_subexprs = [ctx, &device](bool need_assign) -> void { + if (!need_assign) { + delete ctx; + return; + } + + typedef EvalRange EvalRange; + const StorageIndex size = array_prod(ctx->evaluator.dimensions()); + device.parallelForAsync( + size, ctx->evaluator.costPerCoeff(Vectorizable), + EvalRange::alignBlockSize, + [ctx](StorageIndex firstIdx, StorageIndex lastIdx) { + EvalRange::run(&ctx->evaluator, firstIdx, lastIdx); + }, + [ctx]() { delete ctx; }); + }; + + ctx->evaluator.evalSubExprsIfNeededAsync(nullptr, on_eval_subexprs); + } + + private: + struct TensorAsyncExecutorContext { + TensorAsyncExecutorContext(const Expression& expr, + const ThreadPoolDevice& thread_pool, + DoneCallback done) + : evaluator(expr, thread_pool), on_done(std::move(done)) {} + + ~TensorAsyncExecutorContext() { + evaluator.cleanup(); + on_done(); + } + + Evaluator evaluator; + + private: + DoneCallback on_done; + }; +}; + +template +class TensorAsyncExecutor { + public: + typedef typename traits::Index IndexType; + typedef typename traits::Scalar Scalar; + typedef std::remove_const_t ScalarNoConst; + + static constexpr int NumDims = traits::NumDimensions; + + typedef TensorEvaluator Evaluator; + typedef TensorBlockMapper BlockMapper; + typedef TensorExecutorTilingContext TilingContext; + + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator + TensorBlockScratch; + + static EIGEN_STRONG_INLINE void runAsync(const Expression& expr, + const ThreadPoolDevice& device, + DoneCallback done) { + + TensorAsyncExecutorContext* const ctx = + new TensorAsyncExecutorContext(expr, device, std::move(done)); + + const auto on_eval_subexprs = [ctx](bool need_assign) -> void { + if (!need_assign) { + delete ctx; + return; + } + + ctx->tiling = internal::GetTensorExecutorTilingContext< + Evaluator, BlockMapper, Vectorizable>(ctx->evaluator); + + auto eval_block = [ctx](IndexType firstBlockIdx, IndexType lastBlockIdx) { + TensorBlockScratch scratch(ctx->device); + + for (IndexType block_idx = firstBlockIdx; block_idx < lastBlockIdx; + ++block_idx) { + TensorBlockDesc desc = + ctx->tiling.block_mapper.blockDescriptor(block_idx); + ctx->evaluator.evalBlock(desc, scratch); + scratch.reset(); + } + }; + + // Evaluate small expressions directly as a single block. + if (ctx->tiling.block_mapper.blockCount() == 1) { + TensorBlockScratch scratch(ctx->device); + TensorBlockDesc desc(0, ctx->tiling.block_mapper.blockDimensions()); + ctx->evaluator.evalBlock(desc, scratch); + delete ctx; + } else { + ctx->device.parallelForAsync(ctx->tiling.block_mapper.blockCount(), + ctx->tiling.cost, eval_block, + [ctx]() { delete ctx; }); + } + }; + + ctx->evaluator.evalSubExprsIfNeededAsync(nullptr, on_eval_subexprs); + } + + private: + struct TensorAsyncExecutorContext { + TensorAsyncExecutorContext(const Expression& expr, + const ThreadPoolDevice& thread_pool, + DoneCallback done) + : device(thread_pool), + evaluator(expr, thread_pool), + on_done(std::move(done)) {} + + ~TensorAsyncExecutorContext() { + evaluator.cleanup(); + on_done(); + } + + const ThreadPoolDevice& device; + Evaluator evaluator; + TilingContext tiling; + + private: + DoneCallback on_done; + }; +}; + +#endif // EIGEN_USE_THREADS + +// GPU: the evaluation of the expression is offloaded to a GPU. +#if defined(EIGEN_USE_GPU) + +template +class TensorExecutor { + public: + typedef typename Expression::Index StorageIndex; + static void run(const Expression& expr, const GpuDevice& device); +}; + +#if defined(EIGEN_GPUCC) +// Returns 1 if lhs + rhs would overflow, -1 if it would underflow, otherwise 0. +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE int sum_will_overflow(Index lhs, + Index rhs) { + const Index highest = NumTraits::highest(); + const Index lowest = NumTraits::lowest(); + if (lhs > 0 && rhs > 0) { + return lhs > highest - rhs ? 1 : 0; + } else if (lhs < 0 && rhs < 0) { + return lhs < lowest - rhs ? -1 : 0; + } else { + return 0; + } +} + +// Returns lhs + rhs, saturating to the highest/lowest representable value on +// overflow/underflow respectively. +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index saturate_add(Index lhs, Index rhs) { + const Index highest = NumTraits::highest(); + const Index lowest = NumTraits::lowest(); + int overflow = sum_will_overflow(lhs, rhs); + return overflow == 1 ? highest : overflow == -1 ? lowest : lhs + rhs; +} + +// A functor that adds step_size to a given index, saturating to avoid +// overflow/underflow. If overflow/underflow is not possible, regular addition +// is used (for efficiency). +template +struct SafeStep { + // lastIdx is one past the end of the possible indexes. + // step_size is the value that will be added to the given index when the + // functor is called. + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE SafeStep(Index lastIdx, Index step_size) + : can_overflow_(sum_will_overflow(lastIdx, step_size)), + step_size_(step_size) {} + + // Adds step_size to index, saturating on overflow (if overflow is possible). + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index operator()(Index index) const { + return can_overflow_ ? saturate_add(index, step_size_) : index + step_size_; + } + + private: + const bool can_overflow_; + const Index step_size_; +}; + +template +struct EigenMetaKernelEval { + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + void run(Evaluator& eval, StorageIndex firstIdx, StorageIndex lastIdx, StorageIndex step_size) { + SafeStep safe_step(lastIdx, step_size); + for (StorageIndex i = firstIdx; i < lastIdx; i = safe_step(i)) { + eval.evalScalar(i); + } + } +}; + +template +struct EigenMetaKernelEval { + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + void run(Evaluator& eval, StorageIndex firstIdx, StorageIndex lastIdx, StorageIndex step_size) { + const StorageIndex PacketSize = unpacket_traits::size; + const StorageIndex vectorized_size = (lastIdx / PacketSize) * PacketSize; + const StorageIndex vectorized_step_size = step_size * PacketSize; + + SafeStep safe_vectorized_step(vectorized_size, + vectorized_step_size); + // Use the vector path + for (StorageIndex i = firstIdx * PacketSize; i < vectorized_size; + i = safe_vectorized_step(i)) { + eval.evalPacket(i); + } + SafeStep safe_step(lastIdx, step_size); + for (StorageIndex i = saturate_add(vectorized_size, firstIdx); i < lastIdx; + i = safe_step(i)) { + eval.evalScalar(i); + } + } +}; + +template +__global__ void +__launch_bounds__(1024) +EigenMetaKernel(Evaluator eval, StorageIndex size) { + + const StorageIndex first_index = blockIdx.x * blockDim.x + threadIdx.x; + const StorageIndex step_size = blockDim.x * gridDim.x; + + const bool vectorizable = Evaluator::PacketAccess & Evaluator::IsAligned; + EigenMetaKernelEval::run(eval, first_index, size, step_size); +} + +/*static*/ +template +EIGEN_STRONG_INLINE void TensorExecutor::run( + const Expression& expr, const GpuDevice& device) { + TensorEvaluator evaluator(expr, device); + const bool needs_assign = evaluator.evalSubExprsIfNeeded(nullptr); + if (needs_assign) { + + const int block_size = device.maxGpuThreadsPerBlock(); + const int max_blocks = + numext::mini(device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor(), + NumTraits::highest()) / + block_size; + const StorageIndex size = array_prod(evaluator.dimensions()); + // Create a least one block to ensure we won't crash when tensorflow calls with tensors of size 0. + const int num_blocks = numext::maxi(numext::mini(max_blocks, divup(size, block_size)), 1); + + LAUNCH_GPU_KERNEL( + (EigenMetaKernel, StorageIndex>), + num_blocks, block_size, 0, device, evaluator, size); + } + evaluator.cleanup(); +} + +#endif // EIGEN_GPUCC +#endif // EIGEN_USE_GPU + +// SYCL Executor policy +#ifdef EIGEN_USE_SYCL + +template +struct ExecExprFunctorKernel { + typedef typename Evaluator::Index Index; + Evaluator evaluator; + const Index range; + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE ExecExprFunctorKernel( + const Scratch, Evaluator evaluator_, const Index range_) + : evaluator(evaluator_), range(range_) {} + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void operator()( + cl::sycl::nd_item<1> itemID) const { + compute(itemID); + } + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE std::enable_if_t + compute(const cl::sycl::nd_item<1>& itemID) const { + Index gId = static_cast(itemID.get_global_linear_id()); + Index total_threads = itemID.get_global_range(0); + + for (Index i = gId; i < range; i += total_threads) { + evaluator.evalScalar(i); + } + } + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE std::enable_if_t + compute(const cl::sycl::nd_item<1>& itemID) const { + const Index vectorizedRange = + (range / Evaluator::PacketSize) * Evaluator::PacketSize; + Index gId = static_cast(itemID.get_global_linear_id()); + const Index step = Evaluator::PacketSize * itemID.get_global_range(0); + const Index start = Evaluator::PacketSize * gId; + for (Index i = start; i < vectorizedRange; i += step) { + evaluator.evalPacket(i); + } + gId += vectorizedRange; + for (Index i = gId; i < range; i += itemID.get_global_range(0)) { + evaluator.evalScalar(i); + } + } +}; + +template +class TensorExecutor { + public: + typedef typename Expression::Index Index; + static EIGEN_STRONG_INLINE void run(const Expression& expr, + const Eigen::SyclDevice& dev) { + typedef Eigen::TensorEvaluator Evaluator; + Evaluator evaluator(expr, dev); + const bool needs_assign = evaluator.evalSubExprsIfNeeded(NULL); + if (needs_assign) { + Index range, GRange, tileSize; + Index total_size = ::Eigen::internal::array_prod(evaluator.dimensions()); + total_size = (total_size == 0) ? 1 : total_size; + const int PacketSize = + Eigen::PacketType::size; + Index vectorizable_threads = static_cast(total_size / PacketSize); + dev.parallel_for_setup(vectorizable_threads, tileSize, range, GRange); + range = total_size; + + dev.template nullary_kernel_launcher< + typename Evaluator::CoeffReturnType, + ExecExprFunctorKernel >( + evaluator, + cl::sycl::nd_range<1>(cl::sycl::range<1>(GRange), + cl::sycl::range<1>(tileSize)), + Index(1), range).wait(); + } + evaluator.cleanup(); + } +}; + +#endif + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_EXECUTOR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExpr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExpr.h new file mode 100644 index 0000000000000000000000000000000000000000..9bed2a162855f9126383a3044c10ca251072ebb9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorExpr.h @@ -0,0 +1,390 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_EXPR_H +#define EIGEN_CXX11_TENSOR_TENSOR_EXPR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorExpr + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor expression classes. + * + * The TensorCwiseNullaryOp class applies a nullary operators to an expression. + * This is typically used to generate constants. + * + * The TensorCwiseUnaryOp class represents an expression where a unary operator + * (e.g. cwiseSqrt) is applied to an expression. + * + * The TensorCwiseBinaryOp class represents an expression where a binary + * operator (e.g. addition) is applied to a lhs and a rhs expression. + * + */ +namespace internal { +template +struct traits > + : traits +{ + typedef traits XprTraits; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::Nested XprTypeNested; + typedef std::remove_reference_t XprTypeNested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; + enum { + Flags = 0 + }; +}; + +} // end namespace internal + + + +template +class TensorCwiseNullaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef TensorCwiseNullaryOp Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCwiseNullaryOp(const XprType& xpr, const NullaryOp& func = NullaryOp()) + : m_xpr(xpr), m_functor(func) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + nestedExpression() const { return m_xpr; } + + EIGEN_DEVICE_FUNC + const NullaryOp& functor() const { return m_functor; } + + protected: + typename XprType::Nested m_xpr; + const NullaryOp m_functor; +}; + + + +namespace internal { +template +struct traits > + : traits +{ + // TODO(phli): Add InputScalar, InputPacket. Check references to + // current Scalar/Packet to see if the intent is Input or Output. + typedef typename result_of::type Scalar; + typedef traits XprTraits; + typedef typename XprType::Nested XprTypeNested; + typedef std::remove_reference_t XprTypeNested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename TypeConversion::type + PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorCwiseUnaryOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorCwiseUnaryOp type; +}; + +} // end namespace internal + + + +template +class TensorCwiseUnaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + // TODO(phli): Add InputScalar, InputPacket. Check references to + // current Scalar/Packet to see if the intent is Input or Output. + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef Scalar CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCwiseUnaryOp(const XprType& xpr, const UnaryOp& func = UnaryOp()) + : m_xpr(xpr), m_functor(func) {} + + EIGEN_DEVICE_FUNC + const UnaryOp& functor() const { return m_functor; } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + nestedExpression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const UnaryOp m_functor; +}; + + +namespace internal { +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs + // are different. + // TODO(phli): Add Lhs/RhsScalar, Lhs/RhsPacket. Check references to + // current Scalar/Packet to see if the intent is Inputs or Output. + typedef typename result_of< + BinaryOp(typename LhsXprType::Scalar, + typename RhsXprType::Scalar)>::type Scalar; + typedef traits XprTraits; + typedef typename promote_storage_type< + typename traits::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type< + typename traits::Index, + typename traits::Index>::type Index; + typedef typename LhsXprType::Nested LhsNested; + typedef typename RhsXprType::Nested RhsNested; + typedef std::remove_reference_t LhsNested_; + typedef std::remove_reference_t RhsNested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename TypeConversion::val, + typename traits::PointerType, + typename traits::PointerType> + >::type + PointerType; + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorCwiseBinaryOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorCwiseBinaryOp type; +}; + +} // end namespace internal + + + +template +class TensorCwiseBinaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + // TODO(phli): Add Lhs/RhsScalar, Lhs/RhsPacket. Check references to + // current Scalar/Packet to see if the intent is Inputs or Output. + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef Scalar CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCwiseBinaryOp(const LhsXprType& lhs, const RhsXprType& rhs, const BinaryOp& func = BinaryOp()) + : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_functor(func) {} + + EIGEN_DEVICE_FUNC + const BinaryOp& functor() const { return m_functor; } + + /** \returns the nested expressions */ + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + lhsExpression() const { return m_lhs_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + rhsExpression() const { return m_rhs_xpr; } + + protected: + typename LhsXprType::Nested m_lhs_xpr; + typename RhsXprType::Nested m_rhs_xpr; + const BinaryOp m_functor; +}; + + +namespace internal { +template +struct traits > +{ + // Type promotion to handle the case where the types of the args are different. + typedef typename result_of< + TernaryOp(typename Arg1XprType::Scalar, + typename Arg2XprType::Scalar, + typename Arg3XprType::Scalar)>::type Scalar; + typedef traits XprTraits; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::Index Index; + typedef typename Arg1XprType::Nested Arg1Nested; + typedef typename Arg2XprType::Nested Arg2Nested; + typedef typename Arg3XprType::Nested Arg3Nested; + typedef std::remove_reference_t Arg1Nested_; + typedef std::remove_reference_t Arg2Nested_; + typedef std::remove_reference_t Arg3Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename TypeConversion::val, + typename traits::PointerType, + typename traits::PointerType> + >::type + PointerType; + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorCwiseTernaryOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorCwiseTernaryOp type; +}; + +} // end namespace internal + + + +template +class TensorCwiseTernaryOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef Scalar CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorCwiseTernaryOp(const Arg1XprType& arg1, const Arg2XprType& arg2, const Arg3XprType& arg3, const TernaryOp& func = TernaryOp()) + : m_arg1_xpr(arg1), m_arg2_xpr(arg2), m_arg3_xpr(arg3), m_functor(func) {} + + EIGEN_DEVICE_FUNC + const TernaryOp& functor() const { return m_functor; } + + /** \returns the nested expressions */ + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + arg1Expression() const { return m_arg1_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + arg2Expression() const { return m_arg2_xpr; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + arg3Expression() const { return m_arg3_xpr; } + + protected: + typename Arg1XprType::Nested m_arg1_xpr; + typename Arg2XprType::Nested m_arg2_xpr; + typename Arg3XprType::Nested m_arg3_xpr; + const TernaryOp m_functor; +}; + + +namespace internal { +template +struct traits > + : traits +{ + typedef typename traits::Scalar Scalar; + typedef traits XprTraits; + typedef typename promote_storage_type::StorageKind, + typename traits::StorageKind>::ret StorageKind; + typedef typename promote_index_type::Index, + typename traits::Index>::type Index; + typedef typename IfXprType::Nested IfNested; + typedef typename ThenXprType::Nested ThenNested; + typedef typename ElseXprType::Nested ElseNested; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef std::conditional_t::val, + typename traits::PointerType, + typename traits::PointerType> PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorSelectOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorSelectOp type; +}; + +} // end namespace internal + + +template +class TensorSelectOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename internal::promote_storage_type::ret CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC + TensorSelectOp(const IfXprType& a_condition, + const ThenXprType& a_then, + const ElseXprType& a_else) + : m_condition(a_condition), m_then(a_then), m_else(a_else) + { } + + EIGEN_DEVICE_FUNC + const IfXprType& ifExpression() const { return m_condition; } + + EIGEN_DEVICE_FUNC + const ThenXprType& thenExpression() const { return m_then; } + + EIGEN_DEVICE_FUNC + const ElseXprType& elseExpression() const { return m_else; } + + protected: + typename IfXprType::Nested m_condition; + typename ThenXprType::Nested m_then; + typename ElseXprType::Nested m_else; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_EXPR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFFT.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFFT.h new file mode 100644 index 0000000000000000000000000000000000000000..4eaa60b70bced0a0e8d1c38e0ab4c32ea820e177 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFFT.h @@ -0,0 +1,665 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Jianwei Cui +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_FFT_H +#define EIGEN_CXX11_TENSOR_TENSOR_FFT_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorFFT + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor FFT class. + * + * TODO: + * Vectorize the Cooley Tukey and the Bluestein algorithm + * Add support for multithreaded evaluation + * Improve the performance on GPU + */ + +template struct MakeComplex { + template + EIGEN_DEVICE_FUNC + T operator() (const T& val) const { return val; } +}; + +template <> struct MakeComplex { + template + EIGEN_DEVICE_FUNC + std::complex operator() (const T& val) const { return std::complex(val, 0); } +}; + +template <> struct MakeComplex { + template + EIGEN_DEVICE_FUNC + std::complex operator() (const std::complex& val) const { return val; } +}; + +template struct PartOf { + template T operator() (const T& val) const { return val; } +}; + +template <> struct PartOf { + template T operator() (const std::complex& val) const { return val.real(); } +}; + +template <> struct PartOf { + template T operator() (const std::complex& val) const { return val.imag(); } +}; + +namespace internal { +template +struct traits > : public traits { + typedef traits XprTraits; + typedef typename NumTraits::Real RealScalar; + typedef typename std::complex ComplexScalar; + typedef typename XprTraits::Scalar InputScalar; + typedef std::conditional_t OutputScalar; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename traits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> { + typedef const TensorFFTOp& type; +}; + +template +struct nested, 1, typename eval >::type> { + typedef TensorFFTOp type; +}; + +} // end namespace internal + +template +class TensorFFTOp : public TensorBase, ReadOnlyAccessors> { + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename std::complex ComplexScalar; + typedef std::conditional_t OutputScalar; + typedef OutputScalar CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorFFTOp(const XprType& expr, const FFT& fft) + : m_xpr(expr), m_fft(fft) {} + + EIGEN_DEVICE_FUNC + const FFT& fft() const { return m_fft; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& expression() const { + return m_xpr; + } + + protected: + typename XprType::Nested m_xpr; + const FFT m_fft; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> { + typedef TensorFFTOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename std::complex ComplexScalar; + typedef typename TensorEvaluator::Dimensions InputDimensions; + typedef internal::traits XprTraits; + typedef typename XprTraits::Scalar InputScalar; + typedef std::conditional_t OutputScalar; + typedef OutputScalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = internal::unpacket_traits::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = true, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : m_fft(op.fft()), m_impl(op.expression(), device), m_data(NULL), m_device(device) { + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + for (int i = 0; i < NumDims; ++i) { + eigen_assert(input_dims[i] > 0); + m_dimensions[i] = input_dims[i]; + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_strides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1]; + } + } else { + m_strides[NumDims - 1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1]; + } + } + m_size = m_dimensions.TotalSize(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { + return m_dimensions; + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + m_impl.evalSubExprsIfNeeded(NULL); + if (data) { + evalToBuf(data); + return false; + } else { + m_data = (EvaluatorPointerType)m_device.get((CoeffReturnType*)(m_device.allocate_temp(sizeof(CoeffReturnType) * m_size))); + evalToBuf(m_data); + return true; + } + } + + EIGEN_STRONG_INLINE void cleanup() { + if (m_data) { + m_device.deallocate(m_data); + m_data = NULL; + } + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffReturnType coeff(Index index) const { + return m_data[index]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketReturnType + packet(Index index) const { + return internal::ploadt(m_data + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_data; } + + private: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalToBuf(EvaluatorPointerType data) { + const bool write_to_out = internal::is_same::value; + ComplexScalar* buf = write_to_out ? (ComplexScalar*)data : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * m_size); + + for (Index i = 0; i < m_size; ++i) { + buf[i] = MakeComplex::value>()(m_impl.coeff(i)); + } + + for (size_t i = 0; i < m_fft.size(); ++i) { + Index dim = m_fft[i]; + eigen_assert(dim >= 0 && dim < NumDims); + Index line_len = m_dimensions[dim]; + eigen_assert(line_len >= 1); + ComplexScalar* line_buf = (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * line_len); + const bool is_power_of_two = isPowerOfTwo(line_len); + const Index good_composite = is_power_of_two ? 0 : findGoodComposite(line_len); + const Index log_len = is_power_of_two ? getLog2(line_len) : getLog2(good_composite); + + ComplexScalar* a = is_power_of_two ? NULL : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * good_composite); + ComplexScalar* b = is_power_of_two ? NULL : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * good_composite); + ComplexScalar* pos_j_base_powered = is_power_of_two ? NULL : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * (line_len + 1)); + if (!is_power_of_two) { + // Compute twiddle factors + // t_n = exp(sqrt(-1) * pi * n^2 / line_len) + // for n = 0, 1,..., line_len-1. + // For n > 2 we use the recurrence t_n = t_{n-1}^2 / t_{n-2} * t_1^2 + + // The recurrence is correct in exact arithmetic, but causes + // numerical issues for large transforms, especially in + // single-precision floating point. + // + // pos_j_base_powered[0] = ComplexScalar(1, 0); + // if (line_len > 1) { + // const ComplexScalar pos_j_base = ComplexScalar( + // numext::cos(M_PI / line_len), numext::sin(M_PI / line_len)); + // pos_j_base_powered[1] = pos_j_base; + // if (line_len > 2) { + // const ComplexScalar pos_j_base_sq = pos_j_base * pos_j_base; + // for (int i = 2; i < line_len + 1; ++i) { + // pos_j_base_powered[i] = pos_j_base_powered[i - 1] * + // pos_j_base_powered[i - 1] / + // pos_j_base_powered[i - 2] * + // pos_j_base_sq; + // } + // } + // } + // TODO(rmlarsen): Find a way to use Eigen's vectorized sin + // and cosine functions here. + for (int j = 0; j < line_len + 1; ++j) { + double arg = ((EIGEN_PI * j) * j) / line_len; + std::complex tmp(numext::cos(arg), numext::sin(arg)); + pos_j_base_powered[j] = static_cast(tmp); + } + } + + for (Index partial_index = 0; partial_index < m_size / line_len; ++partial_index) { + const Index base_offset = getBaseOffsetFromIndex(partial_index, dim); + + // get data into line_buf + const Index stride = m_strides[dim]; + if (stride == 1) { + m_device.memcpy(line_buf, &buf[base_offset], line_len*sizeof(ComplexScalar)); + } else { + Index offset = base_offset; + for (int j = 0; j < line_len; ++j, offset += stride) { + line_buf[j] = buf[offset]; + } + } + + // process the line + if (is_power_of_two) { + processDataLineCooleyTukey(line_buf, line_len, log_len); + } + else { + processDataLineBluestein(line_buf, line_len, good_composite, log_len, a, b, pos_j_base_powered); + } + + // write back + if (FFTDir == FFT_FORWARD && stride == 1) { + m_device.memcpy(&buf[base_offset], line_buf, line_len*sizeof(ComplexScalar)); + } else { + Index offset = base_offset; + const ComplexScalar div_factor = ComplexScalar(1.0 / line_len, 0); + for (int j = 0; j < line_len; ++j, offset += stride) { + buf[offset] = (FFTDir == FFT_FORWARD) ? line_buf[j] : line_buf[j] * div_factor; + } + } + } + m_device.deallocate(line_buf); + if (!is_power_of_two) { + m_device.deallocate(a); + m_device.deallocate(b); + m_device.deallocate(pos_j_base_powered); + } + } + + if(!write_to_out) { + for (Index i = 0; i < m_size; ++i) { + data[i] = PartOf()(buf[i]); + } + m_device.deallocate(buf); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static bool isPowerOfTwo(Index x) { + eigen_assert(x > 0); + return !(x & (x - 1)); + } + + // The composite number for padding, used in Bluestein's FFT algorithm + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static Index findGoodComposite(Index n) { + Index i = 2; + while (i < 2 * n - 1) i *= 2; + return i; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static Index getLog2(Index m) { + Index log2m = 0; + while (m >>= 1) log2m++; + return log2m; + } + + // Call Cooley Tukey algorithm directly, data length must be power of 2 + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void processDataLineCooleyTukey(ComplexScalar* line_buf, Index line_len, Index log_len) { + eigen_assert(isPowerOfTwo(line_len)); + scramble_FFT(line_buf, line_len); + compute_1D_Butterfly(line_buf, line_len, log_len); + } + + // Call Bluestein's FFT algorithm, m is a good composite number greater than (2 * n - 1), used as the padding length + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void processDataLineBluestein(ComplexScalar* line_buf, Index line_len, Index good_composite, Index log_len, ComplexScalar* a, ComplexScalar* b, const ComplexScalar* pos_j_base_powered) { + Index n = line_len; + Index m = good_composite; + ComplexScalar* data = line_buf; + + for (Index i = 0; i < n; ++i) { + if(FFTDir == FFT_FORWARD) { + a[i] = data[i] * numext::conj(pos_j_base_powered[i]); + } + else { + a[i] = data[i] * pos_j_base_powered[i]; + } + } + for (Index i = n; i < m; ++i) { + a[i] = ComplexScalar(0, 0); + } + + for (Index i = 0; i < n; ++i) { + if(FFTDir == FFT_FORWARD) { + b[i] = pos_j_base_powered[i]; + } + else { + b[i] = numext::conj(pos_j_base_powered[i]); + } + } + for (Index i = n; i < m - n; ++i) { + b[i] = ComplexScalar(0, 0); + } + for (Index i = m - n; i < m; ++i) { + if(FFTDir == FFT_FORWARD) { + b[i] = pos_j_base_powered[m-i]; + } + else { + b[i] = numext::conj(pos_j_base_powered[m-i]); + } + } + + scramble_FFT(a, m); + compute_1D_Butterfly(a, m, log_len); + + scramble_FFT(b, m); + compute_1D_Butterfly(b, m, log_len); + + for (Index i = 0; i < m; ++i) { + a[i] *= b[i]; + } + + scramble_FFT(a, m); + compute_1D_Butterfly(a, m, log_len); + + //Do the scaling after ifft + for (Index i = 0; i < m; ++i) { + a[i] /= m; + } + + for (Index i = 0; i < n; ++i) { + if(FFTDir == FFT_FORWARD) { + data[i] = a[i] * numext::conj(pos_j_base_powered[i]); + } + else { + data[i] = a[i] * pos_j_base_powered[i]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static void scramble_FFT(ComplexScalar* data, Index n) { + eigen_assert(isPowerOfTwo(n)); + Index j = 1; + for (Index i = 1; i < n; ++i){ + if (j > i) { + std::swap(data[j-1], data[i-1]); + } + Index m = n >> 1; + while (m >= 2 && j > m) { + j -= m; + m >>= 1; + } + j += m; + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_2(ComplexScalar* data) { + ComplexScalar tmp = data[1]; + data[1] = data[0] - data[1]; + data[0] += tmp; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_4(ComplexScalar* data) { + ComplexScalar tmp[4]; + tmp[0] = data[0] + data[1]; + tmp[1] = data[0] - data[1]; + tmp[2] = data[2] + data[3]; + if (Dir == FFT_FORWARD) { + tmp[3] = ComplexScalar(0.0, -1.0) * (data[2] - data[3]); + } else { + tmp[3] = ComplexScalar(0.0, 1.0) * (data[2] - data[3]); + } + data[0] = tmp[0] + tmp[2]; + data[1] = tmp[1] + tmp[3]; + data[2] = tmp[0] - tmp[2]; + data[3] = tmp[1] - tmp[3]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_8(ComplexScalar* data) { + ComplexScalar tmp_1[8]; + ComplexScalar tmp_2[8]; + + tmp_1[0] = data[0] + data[1]; + tmp_1[1] = data[0] - data[1]; + tmp_1[2] = data[2] + data[3]; + if (Dir == FFT_FORWARD) { + tmp_1[3] = (data[2] - data[3]) * ComplexScalar(0, -1); + } else { + tmp_1[3] = (data[2] - data[3]) * ComplexScalar(0, 1); + } + tmp_1[4] = data[4] + data[5]; + tmp_1[5] = data[4] - data[5]; + tmp_1[6] = data[6] + data[7]; + if (Dir == FFT_FORWARD) { + tmp_1[7] = (data[6] - data[7]) * ComplexScalar(0, -1); + } else { + tmp_1[7] = (data[6] - data[7]) * ComplexScalar(0, 1); + } + tmp_2[0] = tmp_1[0] + tmp_1[2]; + tmp_2[1] = tmp_1[1] + tmp_1[3]; + tmp_2[2] = tmp_1[0] - tmp_1[2]; + tmp_2[3] = tmp_1[1] - tmp_1[3]; + tmp_2[4] = tmp_1[4] + tmp_1[6]; +// SQRT2DIV2 = sqrt(2)/2 +#define SQRT2DIV2 0.7071067811865476 + if (Dir == FFT_FORWARD) { + tmp_2[5] = (tmp_1[5] + tmp_1[7]) * ComplexScalar(SQRT2DIV2, -SQRT2DIV2); + tmp_2[6] = (tmp_1[4] - tmp_1[6]) * ComplexScalar(0, -1); + tmp_2[7] = (tmp_1[5] - tmp_1[7]) * ComplexScalar(-SQRT2DIV2, -SQRT2DIV2); + } else { + tmp_2[5] = (tmp_1[5] + tmp_1[7]) * ComplexScalar(SQRT2DIV2, SQRT2DIV2); + tmp_2[6] = (tmp_1[4] - tmp_1[6]) * ComplexScalar(0, 1); + tmp_2[7] = (tmp_1[5] - tmp_1[7]) * ComplexScalar(-SQRT2DIV2, SQRT2DIV2); + } + data[0] = tmp_2[0] + tmp_2[4]; + data[1] = tmp_2[1] + tmp_2[5]; + data[2] = tmp_2[2] + tmp_2[6]; + data[3] = tmp_2[3] + tmp_2[7]; + data[4] = tmp_2[0] - tmp_2[4]; + data[5] = tmp_2[1] - tmp_2[5]; + data[6] = tmp_2[2] - tmp_2[6]; + data[7] = tmp_2[3] - tmp_2[7]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_1D_merge( + ComplexScalar* data, Index n, Index n_power_of_2) { + // Original code: + // RealScalar wtemp = std::sin(M_PI/n); + // RealScalar wpi = -std::sin(2 * M_PI/n); + const RealScalar wtemp = m_sin_PI_div_n_LUT[n_power_of_2]; + const RealScalar wpi = (Dir == FFT_FORWARD) + ? m_minus_sin_2_PI_div_n_LUT[n_power_of_2] + : -m_minus_sin_2_PI_div_n_LUT[n_power_of_2]; + + const ComplexScalar wp(wtemp, wpi); + const ComplexScalar wp_one = wp + ComplexScalar(1, 0); + const ComplexScalar wp_one_2 = wp_one * wp_one; + const ComplexScalar wp_one_3 = wp_one_2 * wp_one; + const ComplexScalar wp_one_4 = wp_one_3 * wp_one; + const Index n2 = n / 2; + ComplexScalar w(1.0, 0.0); + for (Index i = 0; i < n2; i += 4) { + ComplexScalar temp0(data[i + n2] * w); + ComplexScalar temp1(data[i + 1 + n2] * w * wp_one); + ComplexScalar temp2(data[i + 2 + n2] * w * wp_one_2); + ComplexScalar temp3(data[i + 3 + n2] * w * wp_one_3); + w = w * wp_one_4; + + data[i + n2] = data[i] - temp0; + data[i] += temp0; + + data[i + 1 + n2] = data[i + 1] - temp1; + data[i + 1] += temp1; + + data[i + 2 + n2] = data[i + 2] - temp2; + data[i + 2] += temp2; + + data[i + 3 + n2] = data[i + 3] - temp3; + data[i + 3] += temp3; + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_1D_Butterfly( + ComplexScalar* data, Index n, Index n_power_of_2) { + eigen_assert(isPowerOfTwo(n)); + if (n > 8) { + compute_1D_Butterfly(data, n / 2, n_power_of_2 - 1); + compute_1D_Butterfly(data + n / 2, n / 2, n_power_of_2 - 1); + butterfly_1D_merge(data, n, n_power_of_2); + } else if (n == 8) { + butterfly_8(data); + } else if (n == 4) { + butterfly_4(data); + } else if (n == 2) { + butterfly_2(data); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index getBaseOffsetFromIndex(Index index, Index omitted_dim) const { + Index result = 0; + + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > omitted_dim; --i) { + const Index partial_m_stride = m_strides[i] / m_dimensions[omitted_dim]; + const Index idx = index / partial_m_stride; + index -= idx * partial_m_stride; + result += idx * m_strides[i]; + } + result += index; + } + else { + for (Index i = 0; i < omitted_dim; ++i) { + const Index partial_m_stride = m_strides[i] / m_dimensions[omitted_dim]; + const Index idx = index / partial_m_stride; + index -= idx * partial_m_stride; + result += idx * m_strides[i]; + } + result += index; + } + // Value of index_coords[omitted_dim] is not determined to this step + return result; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index getIndexFromOffset(Index base, Index omitted_dim, Index offset) const { + Index result = base + offset * m_strides[omitted_dim] ; + return result; + } + + protected: + Index m_size; + const FFT EIGEN_DEVICE_REF m_fft; + Dimensions m_dimensions; + array m_strides; + TensorEvaluator m_impl; + EvaluatorPointerType m_data; + const Device EIGEN_DEVICE_REF m_device; + + // This will support a maximum FFT size of 2^32 for each dimension + // m_sin_PI_div_n_LUT[i] = (-2) * std::sin(M_PI / std::pow(2,i)) ^ 2; + const RealScalar m_sin_PI_div_n_LUT[32] = { + RealScalar(0.0), + RealScalar(-2), + RealScalar(-0.999999999999999), + RealScalar(-0.292893218813453), + RealScalar(-0.0761204674887130), + RealScalar(-0.0192147195967696), + RealScalar(-0.00481527332780311), + RealScalar(-0.00120454379482761), + RealScalar(-3.01181303795779e-04), + RealScalar(-7.52981608554592e-05), + RealScalar(-1.88247173988574e-05), + RealScalar(-4.70619042382852e-06), + RealScalar(-1.17654829809007e-06), + RealScalar(-2.94137117780840e-07), + RealScalar(-7.35342821488550e-08), + RealScalar(-1.83835707061916e-08), + RealScalar(-4.59589268710903e-09), + RealScalar(-1.14897317243732e-09), + RealScalar(-2.87243293150586e-10), + RealScalar( -7.18108232902250e-11), + RealScalar(-1.79527058227174e-11), + RealScalar(-4.48817645568941e-12), + RealScalar(-1.12204411392298e-12), + RealScalar(-2.80511028480785e-13), + RealScalar(-7.01277571201985e-14), + RealScalar(-1.75319392800498e-14), + RealScalar(-4.38298482001247e-15), + RealScalar(-1.09574620500312e-15), + RealScalar(-2.73936551250781e-16), + RealScalar(-6.84841378126949e-17), + RealScalar(-1.71210344531737e-17), + RealScalar(-4.28025861329343e-18) + }; + + // m_minus_sin_2_PI_div_n_LUT[i] = -std::sin(2 * M_PI / std::pow(2,i)); + const RealScalar m_minus_sin_2_PI_div_n_LUT[32] = { + RealScalar(0.0), + RealScalar(0.0), + RealScalar(-1.00000000000000e+00), + RealScalar(-7.07106781186547e-01), + RealScalar(-3.82683432365090e-01), + RealScalar(-1.95090322016128e-01), + RealScalar(-9.80171403295606e-02), + RealScalar(-4.90676743274180e-02), + RealScalar(-2.45412285229123e-02), + RealScalar(-1.22715382857199e-02), + RealScalar(-6.13588464915448e-03), + RealScalar(-3.06795676296598e-03), + RealScalar(-1.53398018628477e-03), + RealScalar(-7.66990318742704e-04), + RealScalar(-3.83495187571396e-04), + RealScalar(-1.91747597310703e-04), + RealScalar(-9.58737990959773e-05), + RealScalar(-4.79368996030669e-05), + RealScalar(-2.39684498084182e-05), + RealScalar(-1.19842249050697e-05), + RealScalar(-5.99211245264243e-06), + RealScalar(-2.99605622633466e-06), + RealScalar(-1.49802811316901e-06), + RealScalar(-7.49014056584716e-07), + RealScalar(-3.74507028292384e-07), + RealScalar(-1.87253514146195e-07), + RealScalar(-9.36267570730981e-08), + RealScalar(-4.68133785365491e-08), + RealScalar(-2.34066892682746e-08), + RealScalar(-1.17033446341373e-08), + RealScalar(-5.85167231706864e-09), + RealScalar(-2.92583615853432e-09) + }; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_FFT_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h new file mode 100644 index 0000000000000000000000000000000000000000..08b182ac8a9a51d47b553a831dc6e276f053bebc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h @@ -0,0 +1,280 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_FIXED_SIZE_H +#define EIGEN_CXX11_TENSOR_TENSOR_FIXED_SIZE_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorFixedSize + * \ingroup CXX11_Tensor_Module + * + * \brief The fixed sized version of the tensor class. + * + * The fixed sized equivalent of + * Eigen::Tensor t(3, 5, 7); + * is + * Eigen::TensorFixedSize> t; + */ + +template +class TensorFixedSize : public TensorBase > +{ + public: + typedef TensorFixedSize Self; + typedef TensorBase > Base; + typedef typename Eigen::internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + typedef typename Base::CoeffReturnType CoeffReturnType; + + static constexpr int Options = Options_; + static constexpr int Layout = Options_ & RowMajor ? RowMajor : ColMajor; + + enum { + IsAligned = bool(EIGEN_MAX_ALIGN_BYTES>0), + PacketAccess = (internal::packet_traits::size > 1), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = true, + RawAccess = true + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + typedef Dimensions_ Dimensions; + static constexpr std::size_t NumIndices = Dimensions::count; + + protected: + TensorStorage m_storage; + + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rank() const { return NumIndices; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index dimension(std::size_t n) const { return m_storage.dimensions()[n]; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions dimensions() const { return m_storage.dimensions(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_storage.size(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar *data() { return m_storage.data(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar *data() const { return m_storage.data(); } + + // This makes EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + // work, because that uses base().coeffRef() - and we don't yet + // implement a similar class hierarchy + inline Self& base() { return *this; } + inline const Self& base() const { return *this; } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& coeff(Index firstIndex, IndexTypes... otherIndices) const + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeff(array{{firstIndex, otherIndices...}}); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeff(const array& indices) const + { + eigen_internal_assert(checkIndexRange(indices)); + return m_storage.data()[linearizedIndex(indices)]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeff(Index index) const + { + eigen_internal_assert(index >= 0 && index < size()); + return m_storage.data()[index]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeff() const + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return m_storage.data()[0]; + } + + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index firstIndex, IndexTypes... otherIndices) + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeffRef(array{{firstIndex, otherIndices...}}); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(const array& indices) + { + eigen_internal_assert(checkIndexRange(indices)); + return m_storage.data()[linearizedIndex(indices)]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) + { + eigen_internal_assert(index >= 0 && index < size()); + return m_storage.data()[index]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return m_storage.data()[0]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar& operator()(Index firstIndex, IndexTypes... otherIndices) const + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return this->operator()(array{{firstIndex, otherIndices...}}); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& operator()(const array& indices) const + { + eigen_assert(checkIndexRange(indices)); + return coeff(indices); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& operator()(Index index) const + { + eigen_internal_assert(index >= 0 && index < size()); + return coeff(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& operator()() const + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeff(); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& operator[](Index index) const + { + // The bracket operator is only for vectors, use the parenthesis operator instead. + EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeff(index); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& operator()(Index firstIndex, IndexTypes... otherIndices) + { + // The number of indices used to access a tensor coefficient must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 1 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + return operator()(array{{firstIndex, otherIndices...}}); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& operator()(const array& indices) + { + eigen_assert(checkIndexRange(indices)); + return coeffRef(indices); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& operator()(Index index) + { + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& operator()() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE); + return coeffRef(); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& operator[](Index index) + { + // The bracket operator is only for vectors, use the parenthesis operator instead + EIGEN_STATIC_ASSERT(NumIndices == 1, YOU_MADE_A_PROGRAMMING_MISTAKE) + return coeffRef(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorFixedSize() + : m_storage() + { + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorFixedSize(const Self& other) + : Base(other), m_storage(other.m_storage) + { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorFixedSize(Self&& other) + : m_storage(other.m_storage) + { + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorFixedSize(const TensorBase& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other.derived()); + internal::TensorExecutor::run(assign, DefaultDevice()); + } + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorFixedSize(const TensorBase& other) + { + typedef TensorAssignOp Assign; + Assign assign(*this, other.derived()); + internal::TensorExecutor::run(assign, DefaultDevice()); + } + + // FIXME: check that the dimensions of other match the dimensions of *this. + // Unfortunately this isn't possible yet when the rhs is an expression. + EIGEN_TENSOR_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(TensorFixedSize) + + + protected: + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE bool checkIndexRange(const array& /*indices*/) const + { + using internal::array_apply_and_reduce; + using internal::array_zip_and_reduce; + using internal::greater_equal_zero_op; + using internal::logical_and_op; + using internal::lesser_op; + + return true; + // check whether the indices are all >= 0 + /* array_apply_and_reduce(indices) && + // check whether the indices fit in the dimensions + array_zip_and_reduce(indices, m_storage.dimensions());*/ + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index linearizedIndex(const array& indices) const + { + if (Options&RowMajor) { + return m_storage.dimensions().IndexOfRowMajor(indices); + } else { + return m_storage.dimensions().IndexOfColMajor(indices); + } + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_FIXED_SIZE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForcedEval.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForcedEval.h new file mode 100644 index 0000000000000000000000000000000000000000..facf7d1c89e1b50d5c6c485a51c8ef1289e5bda6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForcedEval.h @@ -0,0 +1,232 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H +#define EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorForcedEval + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor reshaping class. + * + * + */ +namespace internal { +template +struct traits > +{ + // Type promotion to handle the case where the types of the lhs and the rhs are different. + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; + + enum { + Flags = 0 + }; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorForcedEvalOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorForcedEvalOp type; +}; + +} // end namespace internal + + + +template +class TensorForcedEvalOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorForcedEvalOp(const XprType& expr) + : m_xpr(expr) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; +}; + +namespace internal { +template +struct non_integral_type_placement_new{ + template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(Index numValues, StorageType m_buffer) { + // Initialize non-trivially constructible types. + if (!internal::is_arithmetic::value) { + for (Index i = 0; i < numValues; ++i) new (m_buffer + i) CoeffReturnType(); + } +} +}; + +// SYCL does not support non-integral types +// having new (m_buffer + i) CoeffReturnType() causes the following compiler error for SYCL Devices +// no matching function for call to 'operator new' +template +struct non_integral_type_placement_new { + template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(Index, StorageType) { +} +}; +} // end namespace internal + +template +struct TensorEvaluator, Device> +{ + typedef const internal::remove_all_t ArgType; + typedef TensorForcedEvalOp XprType; + typedef typename ArgType::Scalar Scalar; + typedef typename TensorEvaluator::Dimensions Dimensions; + typedef typename XprType::Index Index; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef typename Eigen::internal::traits::PointerType TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + enum { + IsAligned = true, + PacketAccess = (PacketType::size > 1), + BlockAccess = internal::is_arithmetic::value, + PreferBlockAccess = false, + RawAccess = true + }; + + static constexpr int Layout = TensorEvaluator::Layout; + static constexpr int NumDims = internal::traits::NumDimensions; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_op(op.expression()), + m_device(device), m_buffer(NULL) + { } + + EIGEN_DEVICE_FUNC const Dimensions& dimensions() const { return m_impl.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + const Index numValues = internal::array_prod(m_impl.dimensions()); + m_buffer = m_device.get((CoeffReturnType*)m_device.allocate_temp(numValues * sizeof(CoeffReturnType))); + + internal::non_integral_type_placement_new()(numValues, m_buffer); + + typedef TensorEvalToOp< const std::remove_const_t > EvalTo; + EvalTo evalToTmp(m_device.get(m_buffer), m_op); + + internal::TensorExecutor< + const EvalTo, std::remove_const_t, + /*Vectorizable=*/internal::IsVectorizable::value, + /*Tiling=*/internal::IsTileable::value>:: + run(evalToTmp, m_device); + + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + const Index numValues = internal::array_prod(m_impl.dimensions()); + m_buffer = m_device.get((CoeffReturnType*)m_device.allocate_temp( + numValues * sizeof(CoeffReturnType))); + typedef TensorEvalToOp> + EvalTo; + EvalTo evalToTmp(m_device.get(m_buffer), m_op); + + auto on_done = std::bind([](EvalSubExprsCallback done_) { done_(true); }, + std::move(done)); + internal::TensorAsyncExecutor< + const EvalTo, std::remove_const_t, + decltype(on_done), + /*Vectorizable=*/internal::IsVectorizable::value, + /*Tiling=*/internal::IsTileable::value>:: + runAsync(evalToTmp, m_device, std::move(on_done)); + } +#endif + + EIGEN_STRONG_INLINE void cleanup() { + m_device.deallocate_temp(m_buffer); + m_buffer = NULL; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_buffer[index]; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return internal::ploadt(m_buffer + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return internal::TensorBlockResourceRequirements::any(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + eigen_assert(m_buffer != NULL); + return TensorBlock::materialize(m_buffer, m_impl.dimensions(), desc, scratch); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + EvaluatorPointerType data() const { return m_buffer; } + + private: + TensorEvaluator m_impl; + const ArgType m_op; + const Device EIGEN_DEVICE_REF m_device; + EvaluatorPointerType m_buffer; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_FORCED_EVAL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h new file mode 100644 index 0000000000000000000000000000000000000000..4069b7de08cfd1d9bfeb5d2bf1fc8af17e897f77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h @@ -0,0 +1,177 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H +#define EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +// MakePointer class is used as a container of the address space of the pointer +// on the host and on the device. From the host side it generates the T* pointer +// and when EIGEN_USE_SYCL is used it construct a buffer with a map_allocator to +// T* m_data on the host. It is always called on the device. +// Specialisation of MakePointer class for creating the sycl buffer with +// map_allocator. +template struct MakePointer { + typedef T* Type; + typedef const T* ConstType; +}; + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T* constCast(const T* data) { + return const_cast(data); +} + +// The StorageMemory class is a container of the device specific pointer +// used for referring to a Pointer on TensorEvaluator class. While the TensorExpression +// is a device-agnostic type and need MakePointer class for type conversion, +// the TensorEvaluator class can be specialized for a device, hence it is possible +// to construct different types of temproray storage memory in TensorEvaluator +// for different devices by specializing the following StorageMemory class. +template struct StorageMemory: MakePointer {}; + +namespace internal{ +template struct Pointer_type_promotion { + static const bool val=false; +}; +template struct Pointer_type_promotion { + static const bool val = true; +}; +template struct TypeConversion { + typedef A* type; +}; +} + + +template class MakePointer_ = MakePointer> class TensorMap; +template class Tensor; +template class TensorFixedSize; +template class TensorRef; +template class TensorBase; + +template class TensorCwiseNullaryOp; +template class TensorCwiseUnaryOp; +template class TensorCwiseBinaryOp; +template class TensorCwiseTernaryOp; +template class TensorSelectOp; +template class MakePointer_ = MakePointer > class TensorReductionOp; +template class TensorIndexPairOp; +template class TensorPairReducerOp; +template class TensorConcatenationOp; +template class TensorContractionOp; +template class TensorConversionOp; +template class TensorConvolutionOp; +template class TensorFFTOp; +template class TensorPatchOp; +template class TensorImagePatchOp; +template class TensorVolumePatchOp; +template class TensorBroadcastingOp; +template class TensorChippingOp; +template class TensorReshapingOp; +template class TensorLayoutSwapOp; +template class TensorSlicingOp; +template class TensorReverseOp; +template class TensorPaddingOp; +template class TensorShufflingOp; +template class TensorStridingOp; +template class TensorStridingSlicingOp; +template class TensorInflationOp; +template class TensorGeneratorOp; +template class TensorAssignOp; +template class TensorScanOp; +template class TensorTraceOp; + +template class TensorCustomUnaryOp; +template class TensorCustomBinaryOp; + +template class MakePointer_ = MakePointer> class TensorEvalToOp; +template class TensorForcedEvalOp; + +template class TensorDevice; +template class TensorAsyncDevice; +template struct TensorEvaluator; + +struct NoOpOutputKernel; + +struct DefaultDevice; +struct ThreadPoolDevice; +struct GpuDevice; +struct SyclDevice; + +#ifdef EIGEN_USE_SYCL +namespace TensorSycl { +namespace internal{ +template class GenericNondeterministicReducer; +} +} +#endif + + +enum FFTResultType { + RealPart = 0, + ImagPart = 1, + BothParts = 2 +}; + +enum FFTDirection { + FFT_FORWARD = 0, + FFT_REVERSE = 1 +}; + + +namespace internal { + +template +struct IsVectorizable { + static const bool value = TensorEvaluator::PacketAccess; +}; + +template +struct IsVectorizable { + static const bool value = TensorEvaluator::PacketAccess && + TensorEvaluator::IsAligned; +}; + +// Tiled evaluation strategy. +enum TiledEvaluation { + Off = 0, // tiled evaluation is not supported + On = 1, // still work in progress (see TensorBlock.h) +}; + +template +struct IsTileable { + // Check that block evaluation is supported and it's a preferred option (at + // least one sub-expression has much faster block evaluation, e.g. + // broadcasting). + static constexpr bool BlockAccess = + TensorEvaluator::BlockAccess && + TensorEvaluator::PreferBlockAccess; + + static const TiledEvaluation value = + BlockAccess ? TiledEvaluation::On : TiledEvaluation::Off; +}; + +template ::value, + TiledEvaluation Tiling = IsTileable::value> +class TensorExecutor; + +template ::value, + TiledEvaluation Tiling = IsTileable::value> +class TensorAsyncExecutor; + + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_FORWARD_DECLARATIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFunctors.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFunctors.h new file mode 100644 index 0000000000000000000000000000000000000000..137fe5878d3e5619cd3bef0cb8dc3b528e6c2943 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorFunctors.h @@ -0,0 +1,488 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_FUNCTORS_H +#define EIGEN_CXX11_TENSOR_TENSOR_FUNCTORS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + + +/** \internal + * \brief Template functor to compute the modulo between an array and a scalar. + */ +template +struct scalar_mod_op { + EIGEN_DEVICE_FUNC scalar_mod_op(const Scalar& divisor) : m_divisor(divisor) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator() (const Scalar& a) const { return a % m_divisor; } + const Scalar m_divisor; +}; +template +struct functor_traits > +{ enum { Cost = scalar_div_cost::value, PacketAccess = false }; }; + + +/** \internal + * \brief Template functor to compute the modulo between 2 arrays. + */ +template +struct scalar_mod2_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator() (const Scalar& a, const Scalar& b) const { return a % b; } +}; +template +struct functor_traits > +{ enum { Cost = scalar_div_cost::value, PacketAccess = false }; }; + +template +struct scalar_fmod_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar + operator()(const Scalar& a, const Scalar& b) const { + return numext::fmod(a, b); + } +}; +template +struct functor_traits > { + enum { Cost = 13, // Reciprocal throughput of FPREM on Haswell. + PacketAccess = false }; +}; + +template +struct reducer_traits { + enum { + Cost = 1, + PacketAccess = false, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + +// Standard reduction functors +template struct SumReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) const { + internal::scalar_sum_op sum_op; + *accum = sum_op(*accum, t); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reducePacket(const Packet& p, Packet* accum) const { + (*accum) = padd(*accum, p); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + internal::scalar_cast_op conv; + return conv(0); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet initializePacket() const { + return pset1(initialize()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T accum) const { + return accum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet finalizePacket(const Packet& vaccum) const { + return vaccum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalizeBoth(const T saccum, const Packet& vaccum) const { + internal::scalar_sum_op sum_op; + return sum_op(saccum, predux(vaccum)); + } +}; + +template +struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = PacketType::HasAdd, + IsStateful = false, + IsExactlyAssociative = NumTraits::IsInteger + }; +}; + +template struct MeanReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + MeanReducer() : scalarCount_(0), packetCount_(0) { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) { + internal::scalar_sum_op sum_op; + *accum = sum_op(*accum, t); + scalarCount_++; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reducePacket(const Packet& p, Packet* accum) { + (*accum) = padd(*accum, p); + packetCount_++; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + internal::scalar_cast_op conv; + return conv(0); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet initializePacket() const { + return pset1(initialize()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T accum) const { + internal::scalar_quotient_op quotient_op; + return quotient_op(accum, T(scalarCount_)); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet finalizePacket(const Packet& vaccum) const { + return pdiv(vaccum, pset1(T(packetCount_))); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalizeBoth(const T saccum, const Packet& vaccum) const { + internal::scalar_sum_op sum_op; + internal::scalar_quotient_op quotient_op; + return quotient_op( + sum_op(saccum, predux(vaccum)), + T(scalarCount_ + packetCount_ * unpacket_traits::size)); + } + + protected: + DenseIndex scalarCount_; + DenseIndex packetCount_; +}; + +template +struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = PacketType::HasAdd && + PacketType::HasDiv && !NumTraits::IsInteger, + IsStateful = true, + IsExactlyAssociative = NumTraits::IsInteger + }; +}; + + +template +struct MinMaxBottomValue { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T bottom_value() { + return Eigen::NumTraits::lowest(); + } +}; +template +struct MinMaxBottomValue { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T bottom_value() { + return -Eigen::NumTraits::infinity(); + } +}; +template +struct MinMaxBottomValue { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T bottom_value() { + return Eigen::NumTraits::highest(); + } +}; +template +struct MinMaxBottomValue { + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T bottom_value() { + return Eigen::NumTraits::infinity(); + } +}; + + +template struct MaxReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) const { + scalar_max_op op; + *accum = op(t, *accum); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reducePacket(const Packet& p, Packet* accum) const { + scalar_max_op op; + (*accum) = op.packetOp(*accum, p); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + return MinMaxBottomValue::IsInteger>::bottom_value(); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet initializePacket() const { + return pset1(initialize()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T accum) const { + return accum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet finalizePacket(const Packet& vaccum) const { + return vaccum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalizeBoth(const T saccum, const Packet& vaccum) const { + scalar_max_op op; + return op(saccum, op.predux(vaccum)); + } +}; + +template + struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = PacketType::HasMax, + IsStateful = false, + IsExactlyAssociative = (NaNPropagation!=PropagateFast) + }; +}; + +template struct MinReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) const { + scalar_min_op op; + *accum = op(t, *accum); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reducePacket(const Packet& p, Packet* accum) const { + scalar_min_op op; + (*accum) = op.packetOp(*accum, p); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + return MinMaxBottomValue::IsInteger>::bottom_value(); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet initializePacket() const { + return pset1(initialize()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T accum) const { + return accum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet finalizePacket(const Packet& vaccum) const { + return vaccum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalizeBoth(const T saccum, const Packet& vaccum) const { + scalar_min_op op; + return op(saccum, op.predux(vaccum)); + } +}; + +template + struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = PacketType::HasMin, + IsStateful = false, + IsExactlyAssociative = (NaNPropagation!=PropagateFast) + }; +}; + +template struct ProdReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) const { + internal::scalar_product_op prod_op; + (*accum) = prod_op(*accum, t); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reducePacket(const Packet& p, Packet* accum) const { + (*accum) = pmul(*accum, p); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + internal::scalar_cast_op conv; + return conv(1); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet initializePacket() const { + return pset1(initialize()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T accum) const { + return accum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet finalizePacket(const Packet& vaccum) const { + return vaccum; + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalizeBoth(const T saccum, const Packet& vaccum) const { + internal::scalar_product_op prod_op; + return prod_op(saccum, predux_mul(vaccum)); + } +}; + +template +struct reducer_traits, Device> { + enum { + Cost = NumTraits::MulCost, + PacketAccess = PacketType::HasMul, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + + +struct AndReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(bool t, bool* accum) const { + *accum = *accum && t; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool initialize() const { + return true; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool finalize(bool accum) const { + return accum; + } +}; + +template +struct reducer_traits { + enum { + Cost = 1, + PacketAccess = false, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + + +struct OrReducer { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(bool t, bool* accum) const { + *accum = *accum || t; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool initialize() const { + return false; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool finalize(bool accum) const { + return accum; + } +}; + +template +struct reducer_traits { + enum { + Cost = 1, + PacketAccess = false, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + +// Argmin/Argmax reducers. Returns the first occurrence if multiple locations +// contain the same min/max value. +template struct ArgMaxPairReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T t, T* accum) const { + if (t.second < accum->second) { + return; + } else if (t.second > accum->second || accum->first > t.first ) { + *accum = t; + } + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + return T(0, NumTraits::lowest()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T& accum) const { + return accum; + } +}; + +template +struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = false, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + + +template struct ArgMinPairReducer +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const T& t, T* accum) const { + if (t.second > accum->second) { + return; + } else if (t.second < accum->second || accum->first > t.first) { + *accum = t; + } + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T initialize() const { + return T(0, NumTraits::highest()); + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T finalize(const T& accum) const { + return accum; + } +}; + +template +struct reducer_traits, Device> { + enum { + Cost = NumTraits::AddCost, + PacketAccess = false, + IsStateful = false, + IsExactlyAssociative = true + }; +}; + + +template +class GaussianGenerator { + public: + static constexpr bool PacketAccess = false; + + EIGEN_DEVICE_FUNC GaussianGenerator(const array& means, + const array& std_devs) + : m_means(means) + { + EIGEN_UNROLL_LOOP + for (size_t i = 0; i < NumDims; ++i) { + m_two_sigmas[i] = std_devs[i] * std_devs[i] * 2; + } + } + + EIGEN_DEVICE_FUNC T operator()(const array& coordinates) const { + T tmp = T(0); + EIGEN_UNROLL_LOOP + for (size_t i = 0; i < NumDims; ++i) { + T offset = coordinates[i] - m_means[i]; + tmp += offset * offset / m_two_sigmas[i]; + } + return numext::exp(-tmp); + } + + private: + array m_means; + array m_two_sigmas; +}; + +template +struct functor_traits > { + enum { + Cost = NumDims * (2 * NumTraits::AddCost + NumTraits::MulCost + + functor_traits >::Cost) + + functor_traits >::Cost, + PacketAccess = GaussianGenerator::PacketAccess + }; +}; + +template +struct scalar_clamp_op { + EIGEN_DEVICE_FUNC inline scalar_clamp_op(const Scalar& _min, const Scalar& _max) : m_min(_min), m_max(_max) {} + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar + operator()(const Scalar& x) const { + return numext::mini(numext::maxi(x, m_min), m_max); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet + packetOp(const Packet& x) const { + return internal::pmin(internal::pmax(x, pset1(m_min)), pset1(m_max)); + } + const Scalar m_min; + const Scalar m_max; +}; +template +struct functor_traits > +{ enum { Cost = 2 * NumTraits::AddCost, PacketAccess = (packet_traits::HasMin && packet_traits::HasMax)}; }; + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_FUNCTORS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGenerator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGenerator.h new file mode 100644 index 0000000000000000000000000000000000000000..83f20eb18becba89f38fb8e2ce8836c7a30e4fe5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGenerator.h @@ -0,0 +1,298 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_GENERATOR_H +#define EIGEN_CXX11_TENSOR_TENSOR_GENERATOR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorGeneratorOp + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor generator class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorGeneratorOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorGeneratorOp type; +}; + +} // end namespace internal + + + +template +class TensorGeneratorOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorGeneratorOp(const XprType& expr, const Generator& generator) + : m_xpr(expr), m_generator(generator) {} + + EIGEN_DEVICE_FUNC + const Generator& generator() const { return m_generator; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const Generator m_generator; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorGeneratorOp XprType; + typedef typename XprType::Index Index; + typedef typename TensorEvaluator::Dimensions Dimensions; + static constexpr int NumDims = internal::array_size::value; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = true, + PreferBlockAccess = true, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + typedef internal::TensorIntDivisor IndexDivisor; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_device(device), m_generator(op.generator()) + { + TensorEvaluator argImpl(op.expression(), device); + m_dimensions = argImpl.dimensions(); + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_strides[0] = 1; + EIGEN_UNROLL_LOOP + for (int i = 1; i < NumDims; ++i) { + m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1]; + if (m_strides[i] != 0) m_fast_strides[i] = IndexDivisor(m_strides[i]); + } + } else { + m_strides[NumDims - 1] = 1; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 2; i >= 0; --i) { + m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1]; + if (m_strides[i] != 0) m_fast_strides[i] = IndexDivisor(m_strides[i]); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + array coords; + extract_coordinates(index, coords); + return m_generator(coords); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + const int packetSize = PacketType::size; + eigen_assert(index+packetSize-1 < dimensions().TotalSize()); + + EIGEN_ALIGN_MAX std::remove_const_t values[packetSize]; + for (int i = 0; i < packetSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + const size_t target_size = m_device.firstLevelCacheSize(); + // TODO(ezhulenev): Generator should have a cost. + return internal::TensorBlockResourceRequirements::skewed( + target_size); + } + + struct BlockIteratorState { + Index stride; + Index span; + Index size; + Index count; + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + static const bool is_col_major = + static_cast(Layout) == static_cast(ColMajor); + + // Compute spatial coordinates for the first block element. + array coords; + extract_coordinates(desc.offset(), coords); + array initial_coords = coords; + + // Offset in the output block buffer. + Index offset = 0; + + // Initialize output block iterator state. Dimension in this array are + // always in inner_most -> outer_most order (col major layout). + array it; + for (int i = 0; i < NumDims; ++i) { + const int dim = is_col_major ? i : NumDims - 1 - i; + it[i].size = desc.dimension(dim); + it[i].stride = i == 0 ? 1 : (it[i - 1].size * it[i - 1].stride); + it[i].span = it[i].stride * (it[i].size - 1); + it[i].count = 0; + } + eigen_assert(it[0].stride == 1); + + // Prepare storage for the materialized generator result. + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage(desc, scratch); + + CoeffReturnType* block_buffer = block_storage.data(); + + static const int packet_size = PacketType::size; + + static const int inner_dim = is_col_major ? 0 : NumDims - 1; + const Index inner_dim_size = it[0].size; + const Index inner_dim_vectorized = inner_dim_size - packet_size; + + while (it[NumDims - 1].count < it[NumDims - 1].size) { + Index i = 0; + // Generate data for the vectorized part of the inner-most dimension. + for (; i <= inner_dim_vectorized; i += packet_size) { + for (Index j = 0; j < packet_size; ++j) { + array j_coords = coords; // Break loop dependence. + j_coords[inner_dim] += j; + *(block_buffer + offset + i + j) = m_generator(j_coords); + } + coords[inner_dim] += packet_size; + } + // Finalize non-vectorized part of the inner-most dimension. + for (; i < inner_dim_size; ++i) { + *(block_buffer + offset + i) = m_generator(coords); + coords[inner_dim]++; + } + coords[inner_dim] = initial_coords[inner_dim]; + + // For the 1d tensor we need to generate only one inner-most dimension. + if (NumDims == 1) break; + + // Update offset. + for (i = 1; i < NumDims; ++i) { + if (++it[i].count < it[i].size) { + offset += it[i].stride; + coords[is_col_major ? i : NumDims - 1 - i]++; + break; + } + if (i != NumDims - 1) it[i].count = 0; + coords[is_col_major ? i : NumDims - 1 - i] = + initial_coords[is_col_major ? i : NumDims - 1 - i]; + offset -= it[i].span; + } + } + + return block_storage.AsTensorMaterializedBlock(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool) const { + // TODO(rmlarsen): This is just a placeholder. Define interface to make + // generators return their cost. + return TensorOpCost(0, 0, TensorOpCost::AddCost() + + TensorOpCost::MulCost()); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void extract_coordinates(Index index, array& coords) const { + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_fast_strides[i]; + index -= idx * m_strides[i]; + coords[i] = idx; + } + coords[0] = index; + } else { + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_fast_strides[i]; + index -= idx * m_strides[i]; + coords[i] = idx; + } + coords[NumDims-1] = index; + } + } + + const Device EIGEN_DEVICE_REF m_device; + Dimensions m_dimensions; + array m_strides; + array m_fast_strides; + Generator m_generator; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_GENERATOR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGlobalFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGlobalFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..65052a21822189447a339ec7267041e5a25655e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGlobalFunctions.h @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Eugene Brevdo +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_GLOBAL_FUNCTIONS_H +#define EIGEN_CXX11_TENSOR_TENSOR_GLOBAL_FUNCTIONS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \cpp11 \returns an expression of the coefficient-wise betainc(\a x, \a a, \a b) to the given tensors. + * + * This function computes the regularized incomplete beta function (integral). + * + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const + TensorCwiseTernaryOp, + const ADerived, const BDerived, const XDerived> + betainc(const ADerived& a, const BDerived& b, const XDerived& x) { + return TensorCwiseTernaryOp< + internal::scalar_betainc_op, const ADerived, + const BDerived, const XDerived>( + a, b, x, internal::scalar_betainc_op()); +} + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_GLOBAL_FUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaDefines.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaDefines.h new file mode 100644 index 0000000000000000000000000000000000000000..ae79a1d25db387b0ef48bfc5ad6f03ce64b9000b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaDefines.h @@ -0,0 +1,101 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// Copyright (C) 2018 Deven Desai +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if defined(EIGEN_USE_GPU) && !defined(EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H) +#define EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H + +// Note that we are using EIGEN_USE_HIP here instead of EIGEN_HIPCC...this is by design +// There is code in the Tensorflow codebase that will define EIGEN_USE_GPU, but +// for some reason gets sent to the gcc/host compiler instead of the gpu/nvcc/hipcc compiler +// When compiling such files, gcc will end up trying to pick up the CUDA headers by +// default (see the code within "unsupported/Eigen/CXX11/Tensor" that is guarded by EIGEN_USE_GPU) +// This will obviously not work when trying to compile tensorflow on a system with no CUDA +// To work around this issue for HIP systems (and leave the default behaviour intact), the +// HIP tensorflow build defines EIGEN_USE_HIP when compiling all source files, and +// "unsupported/Eigen/CXX11/Tensor" has been updated to use HIP header when EIGEN_USE_HIP is +// defined. In continuation of that requirement, the guard here needs to be EIGEN_USE_HIP as well + +#if defined(EIGEN_USE_HIP) + +#define gpuStream_t hipStream_t +#define gpuDeviceProp_t hipDeviceProp_t +#define gpuError_t hipError_t +#define gpuSuccess hipSuccess +#define gpuErrorNotReady hipErrorNotReady +#define gpuGetDeviceCount hipGetDeviceCount +#define gpuGetLastError hipGetLastError +#define gpuPeekAtLastError hipPeekAtLastError +#define gpuGetErrorName hipGetErrorName +#define gpuGetErrorString hipGetErrorString +#define gpuGetDeviceProperties hipGetDeviceProperties +#define gpuStreamDefault hipStreamDefault +#define gpuGetDevice hipGetDevice +#define gpuSetDevice hipSetDevice +#define gpuMalloc hipMalloc +#define gpuFree hipFree +#define gpuMemsetAsync hipMemsetAsync +#define gpuMemset2DAsync hipMemset2DAsync +#define gpuMemcpyAsync hipMemcpyAsync +#define gpuMemcpyDeviceToDevice hipMemcpyDeviceToDevice +#define gpuMemcpyDeviceToHost hipMemcpyDeviceToHost +#define gpuMemcpyHostToDevice hipMemcpyHostToDevice +#define gpuStreamQuery hipStreamQuery +#define gpuSharedMemConfig hipSharedMemConfig +#define gpuDeviceSetSharedMemConfig hipDeviceSetSharedMemConfig +#define gpuStreamSynchronize hipStreamSynchronize +#define gpuDeviceSynchronize hipDeviceSynchronize +#define gpuMemcpy hipMemcpy + +#else + +#define gpuStream_t cudaStream_t +#define gpuDeviceProp_t cudaDeviceProp +#define gpuError_t cudaError_t +#define gpuSuccess cudaSuccess +#define gpuErrorNotReady cudaErrorNotReady +#define gpuGetDeviceCount cudaGetDeviceCount +#define gpuGetLastError cudaGetLastError +#define gpuPeekAtLastError cudaPeekAtLastError +#define gpuGetErrorName cudaGetErrorName +#define gpuGetErrorString cudaGetErrorString +#define gpuGetDeviceProperties cudaGetDeviceProperties +#define gpuStreamDefault cudaStreamDefault +#define gpuGetDevice cudaGetDevice +#define gpuSetDevice cudaSetDevice +#define gpuMalloc cudaMalloc +#define gpuFree cudaFree +#define gpuMemsetAsync cudaMemsetAsync +#define gpuMemset2DAsync cudaMemset2DAsync +#define gpuMemcpyAsync cudaMemcpyAsync +#define gpuMemcpyDeviceToDevice cudaMemcpyDeviceToDevice +#define gpuMemcpyDeviceToHost cudaMemcpyDeviceToHost +#define gpuMemcpyHostToDevice cudaMemcpyHostToDevice +#define gpuStreamQuery cudaStreamQuery +#define gpuSharedMemConfig cudaSharedMemConfig +#define gpuDeviceSetSharedMemConfig cudaDeviceSetSharedMemConfig +#define gpuStreamSynchronize cudaStreamSynchronize +#define gpuDeviceSynchronize cudaDeviceSynchronize +#define gpuMemcpy cudaMemcpy + +#endif + +// gpu_assert can be overridden +#ifndef gpu_assert + +#if defined(EIGEN_HIP_DEVICE_COMPILE) +// HIPCC do not support the use of assert on the GPU side. +#define gpu_assert(COND) +#else +#define gpu_assert(COND) eigen_assert(COND) +#endif + +#endif // gpu_assert + +#endif // EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaUndefines.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaUndefines.h new file mode 100644 index 0000000000000000000000000000000000000000..e4d4bd5e769da04cf8c4d9ef52cb0f68f1a51856 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaUndefines.h @@ -0,0 +1,45 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// Copyright (C) 2018 Deven Desai +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#if defined(EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H) + +#ifndef EIGEN_PERMANENTLY_ENABLE_GPU_HIP_CUDA_DEFINES + +#undef gpuStream_t +#undef gpuDeviceProp_t +#undef gpuError_t +#undef gpuSuccess +#undef gpuErrorNotReady +#undef gpuGetDeviceCount +#undef gpuGetErrorString +#undef gpuGetDeviceProperties +#undef gpuStreamDefault +#undef gpuGetDevice +#undef gpuSetDevice +#undef gpuMalloc +#undef gpuFree +#undef gpuMemsetAsync +#undef gpuMemset2DAsync +#undef gpuMemcpyAsync +#undef gpuMemcpyDeviceToDevice +#undef gpuMemcpyDeviceToHost +#undef gpuMemcpyHostToDevice +#undef gpuStreamQuery +#undef gpuSharedMemConfig +#undef gpuDeviceSetSharedMemConfig +#undef gpuStreamSynchronize +#undef gpuDeviceSynchronize +#undef gpuMemcpy + +#endif // EIGEN_PERMANENTLY_ENABLE_GPU_HIP_CUDA_DEFINES + +#undef EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H + +#endif // EIGEN_CXX11_TENSOR_GPU_HIP_CUDA_DEFINES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h new file mode 100644 index 0000000000000000000000000000000000000000..efda741319a9ce9429dc963d31d44a445d3b4106 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIO.h @@ -0,0 +1,374 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_IO_H +#define EIGEN_CXX11_TENSOR_TENSOR_IO_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +struct TensorIOFormat; + +namespace internal { +template +struct TensorPrinter; +} + +struct TensorIOFormat { + TensorIOFormat(const std::vector& _separator, const std::vector& _prefix, + const std::vector& _suffix, int _precision = StreamPrecision, int _flags = 0, + const std::string& _tenPrefix = "", const std::string& _tenSuffix = "", const char _fill = ' ') + : tenPrefix(_tenPrefix), + tenSuffix(_tenSuffix), + prefix(_prefix), + suffix(_suffix), + separator(_separator), + fill(_fill), + precision(_precision), + flags(_flags) { + init_spacer(); + } + + TensorIOFormat(int _precision = StreamPrecision, int _flags = 0, const std::string& _tenPrefix = "", + const std::string& _tenSuffix = "", const char _fill = ' ') + : tenPrefix(_tenPrefix), tenSuffix(_tenSuffix), fill(_fill), precision(_precision), flags(_flags) { + // default values of prefix, suffix and separator + prefix = {"", "["}; + suffix = {"", "]"}; + separator = {", ", "\n"}; + + init_spacer(); + } + + void init_spacer() { + if ((flags & DontAlignCols)) return; + spacer.resize(prefix.size()); + spacer[0] = ""; + int i = int(tenPrefix.length()) - 1; + while (i >= 0 && tenPrefix[i] != '\n') { + spacer[0] += ' '; + i--; + } + + for (std::size_t k = 1; k < prefix.size(); k++) { + int j = int(prefix[k].length()) - 1; + while (j >= 0 && prefix[k][j] != '\n') { + spacer[k] += ' '; + j--; + } + } + } + + static inline const TensorIOFormat Numpy() { + std::vector prefix = {"", "["}; + std::vector suffix = {"", "]"}; + std::vector separator = {" ", "\n"}; + return TensorIOFormat(separator, prefix, suffix, StreamPrecision, 0, "[", "]"); + } + + static inline const TensorIOFormat Plain() { + std::vector separator = {" ", "\n", "\n", ""}; + std::vector prefix = {""}; + std::vector suffix = {""}; + return TensorIOFormat(separator, prefix, suffix, StreamPrecision, 0, "", "", ' '); + } + + static inline const TensorIOFormat Native() { + std::vector separator = {", ", ",\n", "\n"}; + std::vector prefix = {"", "{"}; + std::vector suffix = {"", "}"}; + return TensorIOFormat(separator, prefix, suffix, StreamPrecision, 0, "{", "}", ' '); + } + + static inline const TensorIOFormat Legacy() { + TensorIOFormat LegacyFormat(StreamPrecision, 0, "", "", ' '); + LegacyFormat.legacy_bit = true; + return LegacyFormat; + } + + std::string tenPrefix; + std::string tenSuffix; + std::vector prefix; + std::vector suffix; + std::vector separator; + char fill; + int precision; + int flags; + std::vector spacer{}; + bool legacy_bit = false; +}; + +template +class TensorWithFormat; +// specialize for Layout=ColMajor, Layout=RowMajor and rank=0. +template +class TensorWithFormat { + public: + TensorWithFormat(const T& tensor, const TensorIOFormat& format) : t_tensor(tensor), t_format(format) {} + + friend std::ostream& operator<<(std::ostream& os, const TensorWithFormat& wf) { + // Evaluate the expression if needed + typedef TensorEvaluator, DefaultDevice> Evaluator; + TensorForcedEvalOp eval = wf.t_tensor.eval(); + Evaluator tensor(eval, DefaultDevice()); + tensor.evalSubExprsIfNeeded(NULL); + internal::TensorPrinter::run(os, tensor, wf.t_format); + // Cleanup. + tensor.cleanup(); + return os; + } + + protected: + T t_tensor; + TensorIOFormat t_format; +}; + +template +class TensorWithFormat { + public: + TensorWithFormat(const T& tensor, const TensorIOFormat& format) : t_tensor(tensor), t_format(format) {} + + friend std::ostream& operator<<(std::ostream& os, const TensorWithFormat& wf) { + // Switch to RowMajor storage and print afterwards + typedef typename T::Index IndexType; + std::array shuffle; + std::array id; + std::iota(id.begin(), id.end(), IndexType(0)); + std::copy(id.begin(), id.end(), shuffle.rbegin()); + auto tensor_row_major = wf.t_tensor.swap_layout().shuffle(shuffle); + + // Evaluate the expression if needed + typedef TensorEvaluator, DefaultDevice> Evaluator; + TensorForcedEvalOp eval = tensor_row_major.eval(); + Evaluator tensor(eval, DefaultDevice()); + tensor.evalSubExprsIfNeeded(NULL); + internal::TensorPrinter::run(os, tensor, wf.t_format); + // Cleanup. + tensor.cleanup(); + return os; + } + + protected: + T t_tensor; + TensorIOFormat t_format; +}; + +template +class TensorWithFormat { + public: + TensorWithFormat(const T& tensor, const TensorIOFormat& format) : t_tensor(tensor), t_format(format) {} + + friend std::ostream& operator<<(std::ostream& os, const TensorWithFormat& wf) { + // Evaluate the expression if needed + typedef TensorEvaluator, DefaultDevice> Evaluator; + TensorForcedEvalOp eval = wf.t_tensor.eval(); + Evaluator tensor(eval, DefaultDevice()); + tensor.evalSubExprsIfNeeded(NULL); + internal::TensorPrinter::run(os, tensor, wf.t_format); + // Cleanup. + tensor.cleanup(); + return os; + } + + protected: + T t_tensor; + TensorIOFormat t_format; +}; + +namespace internal { +template +struct TensorPrinter { + static void run(std::ostream& s, const Tensor& _t, const TensorIOFormat& fmt) { + typedef std::remove_const_t Scalar; + typedef typename Tensor::Index IndexType; + static const int layout = Tensor::Layout; + // backwards compatibility case: print tensor after reshaping to matrix of size dim(0) x + // (dim(1)*dim(2)*...*dim(rank-1)). + if (fmt.legacy_bit) { + const IndexType total_size = internal::array_prod(_t.dimensions()); + if (total_size > 0) { + const IndexType first_dim = Eigen::internal::array_get<0>(_t.dimensions()); + Map > matrix(_t.data(), first_dim, + total_size / first_dim); + s << matrix; + return; + } + } + + eigen_assert(layout == RowMajor); + typedef std::conditional_t::value || is_same::value || + is_same::value || is_same::value, + int, + std::conditional_t >::value || + is_same >::value || + is_same >::value || + is_same >::value, + std::complex, const Scalar&>> PrintType; + + const IndexType total_size = array_prod(_t.dimensions()); + + std::streamsize explicit_precision; + if (fmt.precision == StreamPrecision) { + explicit_precision = 0; + } else if (fmt.precision == FullPrecision) { + if (NumTraits::IsInteger) { + explicit_precision = 0; + } else { + explicit_precision = significant_decimals_impl::run(); + } + } else { + explicit_precision = fmt.precision; + } + + std::streamsize old_precision = 0; + if (explicit_precision) old_precision = s.precision(explicit_precision); + + IndexType width = 0; + + bool align_cols = !(fmt.flags & DontAlignCols); + if (align_cols) { + // compute the largest width + for (IndexType i = 0; i < total_size; i++) { + std::stringstream sstr; + sstr.copyfmt(s); + sstr << static_cast(_t.data()[i]); + width = std::max(width, IndexType(sstr.str().length())); + } + } + std::streamsize old_width = s.width(); + char old_fill_character = s.fill(); + + s << fmt.tenPrefix; + for (IndexType i = 0; i < total_size; i++) { + std::array is_at_end{}; + std::array is_at_begin{}; + + // is the ith element the end of an coeff (always true), of a row, of a matrix, ...? + for (std::size_t k = 0; k < rank; k++) { + if ((i + 1) % (std::accumulate(_t.dimensions().rbegin(), _t.dimensions().rbegin() + k, 1, + std::multiplies())) == + 0) { + is_at_end[k] = true; + } + } + + // is the ith element the begin of an coeff (always true), of a row, of a matrix, ...? + for (std::size_t k = 0; k < rank; k++) { + if (i % (std::accumulate(_t.dimensions().rbegin(), _t.dimensions().rbegin() + k, 1, + std::multiplies())) == + 0) { + is_at_begin[k] = true; + } + } + + // do we have a line break? + bool is_at_begin_after_newline = false; + for (std::size_t k = 0; k < rank; k++) { + if (is_at_begin[k]) { + std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1; + if (fmt.separator[separator_index].find('\n') != std::string::npos) { + is_at_begin_after_newline = true; + } + } + } + + bool is_at_end_before_newline = false; + for (std::size_t k = 0; k < rank; k++) { + if (is_at_end[k]) { + std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1; + if (fmt.separator[separator_index].find('\n') != std::string::npos) { + is_at_end_before_newline = true; + } + } + } + + std::stringstream suffix, prefix, separator; + for (std::size_t k = 0; k < rank; k++) { + std::size_t suffix_index = (k < fmt.suffix.size()) ? k : fmt.suffix.size() - 1; + if (is_at_end[k]) { + suffix << fmt.suffix[suffix_index]; + } + } + for (std::size_t k = 0; k < rank; k++) { + std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1; + if (is_at_end[k] && + (!is_at_end_before_newline || fmt.separator[separator_index].find('\n') != std::string::npos)) { + separator << fmt.separator[separator_index]; + } + } + for (std::size_t k = 0; k < rank; k++) { + std::size_t spacer_index = (k < fmt.spacer.size()) ? k : fmt.spacer.size() - 1; + if (i != 0 && is_at_begin_after_newline && (!is_at_begin[k] || k == 0)) { + prefix << fmt.spacer[spacer_index]; + } + } + for (int k = rank - 1; k >= 0; k--) { + std::size_t prefix_index = (static_cast(k) < fmt.prefix.size()) ? k : fmt.prefix.size() - 1; + if (is_at_begin[k]) { + prefix << fmt.prefix[prefix_index]; + } + } + + s << prefix.str(); + if (width) { + s.fill(fmt.fill); + s.width(width); + s << std::right; + } + s << _t.data()[i]; + s << suffix.str(); + if (i < total_size - 1) { + s << separator.str(); + } + } + s << fmt.tenSuffix; + if (explicit_precision) s.precision(old_precision); + if (width) { + s.fill(old_fill_character); + s.width(old_width); + } + } +}; + +template +struct TensorPrinter { + static void run(std::ostream& s, const Tensor& _t, const TensorIOFormat& fmt) { + typedef typename Tensor::Scalar Scalar; + + std::streamsize explicit_precision; + if (fmt.precision == StreamPrecision) { + explicit_precision = 0; + } else if (fmt.precision == FullPrecision) { + if (NumTraits::IsInteger) { + explicit_precision = 0; + } else { + explicit_precision = significant_decimals_impl::run(); + } + } else { + explicit_precision = fmt.precision; + } + + std::streamsize old_precision = 0; + if (explicit_precision) old_precision = s.precision(explicit_precision); + + s << fmt.tenPrefix << _t.coeff(0) << fmt.tenSuffix; + if (explicit_precision) s.precision(old_precision); + } +}; + +} // end namespace internal +template +std::ostream& operator<<(std::ostream& s, const TensorBase& t) { + s << t.format(TensorIOFormat::Plain()); + return s; +} +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_IO_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorImagePatch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorImagePatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3ce021c1a87b8c6b713ca91bc3796b6aa0b65eef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorImagePatch.h @@ -0,0 +1,596 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_IMAGE_PATCH_H +#define EIGEN_CXX11_TENSOR_TENSOR_IMAGE_PATCH_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorImagePatch + * \ingroup CXX11_Tensor_Module + * + * \brief Patch extraction specialized for image processing. + * This assumes that the input has a least 3 dimensions ordered as follow: + * 1st dimension: channels (of size d) + * 2nd dimension: rows (of size r) + * 3rd dimension: columns (of size c) + * There can be additional dimensions such as time (for video) or batch (for + * bulk processing after the first 3. + * Calling the image patch code with patch_rows and patch_cols is equivalent + * to calling the regular patch extraction code with parameters d, patch_rows, + * patch_cols, and 1 for all the additional dimensions. + */ +namespace internal { + +template +struct traits > : public traits +{ + typedef std::remove_const_t Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions + 1; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorImagePatchOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorImagePatchOp type; +}; + +template +struct ImagePatchCopyOp { + typedef typename Self::Index Index; + typedef typename Self::Scalar Scalar; + typedef typename Self::Impl Impl; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run( + const Self& self, const Index num_coeff_to_copy, const Index dst_index, + Scalar* dst_data, const Index src_index) { + const Impl& impl = self.impl(); + for (Index i = 0; i < num_coeff_to_copy; ++i) { + dst_data[dst_index + i] = impl.coeff(src_index + i); + } + } +}; + +template +struct ImagePatchCopyOp { + typedef typename Self::Index Index; + typedef typename Self::Scalar Scalar; + typedef typename Self::Impl Impl; + typedef typename packet_traits::type Packet; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run( + const Self& self, const Index num_coeff_to_copy, const Index dst_index, + Scalar* dst_data, const Index src_index) { + const Impl& impl = self.impl(); + const Index packet_size = internal::unpacket_traits::size; + const Index vectorized_size = + (num_coeff_to_copy / packet_size) * packet_size; + for (Index i = 0; i < vectorized_size; i += packet_size) { + Packet p = impl.template packet(src_index + i); + internal::pstoret(dst_data + dst_index + i, p); + } + for (Index i = vectorized_size; i < num_coeff_to_copy; ++i) { + dst_data[dst_index + i] = impl.coeff(src_index + i); + } + } +}; + +template +struct ImagePatchPaddingOp { + typedef typename Self::Index Index; + typedef typename Self::Scalar Scalar; + typedef typename packet_traits::type Packet; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void Run( + const Index num_coeff_to_pad, const Scalar padding_value, + const Index dst_index, Scalar* dst_data) { + const Index packet_size = internal::unpacket_traits::size; + const Packet padded_packet = internal::pset1(padding_value); + const Index vectorized_size = + (num_coeff_to_pad / packet_size) * packet_size; + for (Index i = 0; i < vectorized_size; i += packet_size) { + internal::pstoret(dst_data + dst_index + i, + padded_packet); + } + for (Index i = vectorized_size; i < num_coeff_to_pad; ++i) { + dst_data[dst_index + i] = padding_value; + } + } +}; + +} // end namespace internal + +template +class TensorImagePatchOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorImagePatchOp(const XprType& expr, DenseIndex patch_rows, DenseIndex patch_cols, + DenseIndex row_strides, DenseIndex col_strides, + DenseIndex in_row_strides, DenseIndex in_col_strides, + DenseIndex row_inflate_strides, DenseIndex col_inflate_strides, + PaddingType padding_type, Scalar padding_value) + : m_xpr(expr), m_patch_rows(patch_rows), m_patch_cols(patch_cols), + m_row_strides(row_strides), m_col_strides(col_strides), + m_in_row_strides(in_row_strides), m_in_col_strides(in_col_strides), + m_row_inflate_strides(row_inflate_strides), m_col_inflate_strides(col_inflate_strides), + m_padding_explicit(false), m_padding_top(0), m_padding_bottom(0), m_padding_left(0), m_padding_right(0), + m_padding_type(padding_type), m_padding_value(padding_value) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorImagePatchOp(const XprType& expr, DenseIndex patch_rows, DenseIndex patch_cols, + DenseIndex row_strides, DenseIndex col_strides, + DenseIndex in_row_strides, DenseIndex in_col_strides, + DenseIndex row_inflate_strides, DenseIndex col_inflate_strides, + DenseIndex padding_top, DenseIndex padding_bottom, + DenseIndex padding_left, DenseIndex padding_right, + Scalar padding_value) + : m_xpr(expr), m_patch_rows(patch_rows), m_patch_cols(patch_cols), + m_row_strides(row_strides), m_col_strides(col_strides), + m_in_row_strides(in_row_strides), m_in_col_strides(in_col_strides), + m_row_inflate_strides(row_inflate_strides), m_col_inflate_strides(col_inflate_strides), + m_padding_explicit(true), m_padding_top(padding_top), m_padding_bottom(padding_bottom), + m_padding_left(padding_left), m_padding_right(padding_right), + m_padding_type(PADDING_VALID), m_padding_value(padding_value) {} + + + EIGEN_DEVICE_FUNC + DenseIndex patch_rows() const { return m_patch_rows; } + EIGEN_DEVICE_FUNC + DenseIndex patch_cols() const { return m_patch_cols; } + EIGEN_DEVICE_FUNC + DenseIndex row_strides() const { return m_row_strides; } + EIGEN_DEVICE_FUNC + DenseIndex col_strides() const { return m_col_strides; } + EIGEN_DEVICE_FUNC + DenseIndex in_row_strides() const { return m_in_row_strides; } + EIGEN_DEVICE_FUNC + DenseIndex in_col_strides() const { return m_in_col_strides; } + EIGEN_DEVICE_FUNC + DenseIndex row_inflate_strides() const { return m_row_inflate_strides; } + EIGEN_DEVICE_FUNC + DenseIndex col_inflate_strides() const { return m_col_inflate_strides; } + EIGEN_DEVICE_FUNC + bool padding_explicit() const { return m_padding_explicit; } + EIGEN_DEVICE_FUNC + DenseIndex padding_top() const { return m_padding_top; } + EIGEN_DEVICE_FUNC + DenseIndex padding_bottom() const { return m_padding_bottom; } + EIGEN_DEVICE_FUNC + DenseIndex padding_left() const { return m_padding_left; } + EIGEN_DEVICE_FUNC + DenseIndex padding_right() const { return m_padding_right; } + EIGEN_DEVICE_FUNC + PaddingType padding_type() const { return m_padding_type; } + EIGEN_DEVICE_FUNC + Scalar padding_value() const { return m_padding_value; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const DenseIndex m_patch_rows; + const DenseIndex m_patch_cols; + const DenseIndex m_row_strides; + const DenseIndex m_col_strides; + const DenseIndex m_in_row_strides; + const DenseIndex m_in_col_strides; + const DenseIndex m_row_inflate_strides; + const DenseIndex m_col_inflate_strides; + const bool m_padding_explicit; + const DenseIndex m_padding_top; + const DenseIndex m_padding_bottom; + const DenseIndex m_padding_left; + const DenseIndex m_padding_right; + const PaddingType m_padding_type; + const Scalar m_padding_value; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorImagePatchOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + static constexpr int NumDims = NumInputDims + 1; + typedef DSizes Dimensions; + typedef std::remove_const_t Scalar; + typedef TensorEvaluator, + Device> Self; + typedef TensorEvaluator Impl; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = true, + CoordAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator( const XprType& op, const Device& device) + : m_device(device), m_impl(op.expression(), device) + { + EIGEN_STATIC_ASSERT((NumDims >= 4), YOU_MADE_A_PROGRAMMING_MISTAKE); + + m_paddingValue = op.padding_value(); + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + + // Caches a few variables. + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputDepth = input_dims[0]; + m_inputRows = input_dims[1]; + m_inputCols = input_dims[2]; + } else { + m_inputDepth = input_dims[NumInputDims-1]; + m_inputRows = input_dims[NumInputDims-2]; + m_inputCols = input_dims[NumInputDims-3]; + } + + m_row_strides = op.row_strides(); + m_col_strides = op.col_strides(); + + // Input strides and effective input/patch size + m_in_row_strides = op.in_row_strides(); + m_in_col_strides = op.in_col_strides(); + m_row_inflate_strides = op.row_inflate_strides(); + m_col_inflate_strides = op.col_inflate_strides(); + // The "effective" input rows and input cols are the input rows and cols + // after inflating them with zeros. + // For examples, a 2x3 matrix with row_inflate_strides and + // col_inflate_strides of 2 comes from: + // A B C + // D E F + // + // to a matrix is 3 x 5: + // + // A . B . C + // . . . . . + // D . E . F + + m_input_rows_eff = (m_inputRows - 1) * m_row_inflate_strides + 1; + m_input_cols_eff = (m_inputCols - 1) * m_col_inflate_strides + 1; + m_patch_rows_eff = op.patch_rows() + (op.patch_rows() - 1) * (m_in_row_strides - 1); + m_patch_cols_eff = op.patch_cols() + (op.patch_cols() - 1) * (m_in_col_strides - 1); + + if (op.padding_explicit()) { + m_outputRows = numext::ceil((m_input_rows_eff + op.padding_top() + op.padding_bottom() - m_patch_rows_eff + 1.f) / static_cast(m_row_strides)); + m_outputCols = numext::ceil((m_input_cols_eff + op.padding_left() + op.padding_right() - m_patch_cols_eff + 1.f) / static_cast(m_col_strides)); + m_rowPaddingTop = op.padding_top(); + m_colPaddingLeft = op.padding_left(); + } else { + // Computing padding from the type + switch (op.padding_type()) { + case PADDING_VALID: + m_outputRows = numext::ceil((m_input_rows_eff - m_patch_rows_eff + 1.f) / static_cast(m_row_strides)); + m_outputCols = numext::ceil((m_input_cols_eff - m_patch_cols_eff + 1.f) / static_cast(m_col_strides)); + // Calculate the padding + m_rowPaddingTop = numext::maxi(0, ((m_outputRows - 1) * m_row_strides + m_patch_rows_eff - m_input_rows_eff) / 2); + m_colPaddingLeft = numext::maxi(0, ((m_outputCols - 1) * m_col_strides + m_patch_cols_eff - m_input_cols_eff) / 2); + break; + case PADDING_SAME: + m_outputRows = numext::ceil(m_input_rows_eff / static_cast(m_row_strides)); + m_outputCols = numext::ceil(m_input_cols_eff / static_cast(m_col_strides)); + // Calculate the padding + m_rowPaddingTop = ((m_outputRows - 1) * m_row_strides + m_patch_rows_eff - m_input_rows_eff) / 2; + m_colPaddingLeft = ((m_outputCols - 1) * m_col_strides + m_patch_cols_eff - m_input_cols_eff) / 2; + // The padding size calculation for PADDING_SAME has been updated to + // be consistent with how TensorFlow extracts its paddings. + m_rowPaddingTop = numext::maxi(0, m_rowPaddingTop); + m_colPaddingLeft = numext::maxi(0, m_colPaddingLeft); + break; + default: + eigen_assert(false && "unexpected padding"); + m_outputCols=0; // silence the uninitialised warning; + m_outputRows=0; //// silence the uninitialised warning; + } + } + eigen_assert(m_outputRows > 0); + eigen_assert(m_outputCols > 0); + + // Dimensions for result of extraction. + if (static_cast(Layout) == static_cast(ColMajor)) { + // ColMajor + // 0: depth + // 1: patch_rows + // 2: patch_cols + // 3: number of patches + // 4 and beyond: anything else (such as batch). + m_dimensions[0] = input_dims[0]; + m_dimensions[1] = op.patch_rows(); + m_dimensions[2] = op.patch_cols(); + m_dimensions[3] = m_outputRows * m_outputCols; + for (int i = 4; i < NumDims; ++i) { + m_dimensions[i] = input_dims[i-1]; + } + } else { + // RowMajor + // NumDims-1: depth + // NumDims-2: patch_rows + // NumDims-3: patch_cols + // NumDims-4: number of patches + // NumDims-5 and beyond: anything else (such as batch). + m_dimensions[NumDims-1] = input_dims[NumInputDims-1]; + m_dimensions[NumDims-2] = op.patch_rows(); + m_dimensions[NumDims-3] = op.patch_cols(); + m_dimensions[NumDims-4] = m_outputRows * m_outputCols; + for (int i = NumDims-5; i >= 0; --i) { + m_dimensions[i] = input_dims[i]; + } + } + + // Strides for moving the patch in various dimensions. + if (static_cast(Layout) == static_cast(ColMajor)) { + m_colStride = m_dimensions[1]; + m_patchStride = m_colStride * m_dimensions[2] * m_dimensions[0]; + m_otherStride = m_patchStride * m_dimensions[3]; + } else { + m_colStride = m_dimensions[NumDims-2]; + m_patchStride = m_colStride * m_dimensions[NumDims-3] * m_dimensions[NumDims-1]; + m_otherStride = m_patchStride * m_dimensions[NumDims-4]; + } + + // Strides for navigating through the input tensor. + m_rowInputStride = m_inputDepth; + m_colInputStride = m_inputDepth * m_inputRows; + m_patchInputStride = m_inputDepth * m_inputRows * m_inputCols; + + // Fast representations of different variables. + m_fastOtherStride = internal::TensorIntDivisor(m_otherStride); + m_fastPatchStride = internal::TensorIntDivisor(m_patchStride); + m_fastColStride = internal::TensorIntDivisor(m_colStride); + m_fastInflateRowStride = internal::TensorIntDivisor(m_row_inflate_strides); + m_fastInflateColStride = internal::TensorIntDivisor(m_col_inflate_strides); + m_fastInputColsEff = internal::TensorIntDivisor(m_input_cols_eff); + + // Number of patches in the width dimension. + m_fastOutputRows = internal::TensorIntDivisor(m_outputRows); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_fastOutputDepth = internal::TensorIntDivisor(m_dimensions[0]); + } else { + m_fastOutputDepth = internal::TensorIntDivisor(m_dimensions[NumDims-1]); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + // Patch index corresponding to the passed in index. + const Index patchIndex = index / m_fastPatchStride; + // Find the offset of the element wrt the location of the first element. + const Index patchOffset = (index - patchIndex * m_patchStride) / m_fastOutputDepth; + + // Other ways to index this element. + const Index otherIndex = (NumDims == 4) ? 0 : index / m_fastOtherStride; + const Index patch2DIndex = (NumDims == 4) ? patchIndex : (index - otherIndex * m_otherStride) / m_fastPatchStride; + + // Calculate col index in the input original tensor. + const Index colIndex = patch2DIndex / m_fastOutputRows; + const Index colOffset = patchOffset / m_fastColStride; + const Index inputCol = colIndex * m_col_strides + colOffset * m_in_col_strides - m_colPaddingLeft; + const Index origInputCol = (m_col_inflate_strides == 1) ? inputCol : ((inputCol >= 0) ? (inputCol / m_fastInflateColStride) : 0); + if (inputCol < 0 || inputCol >= m_input_cols_eff || + ((m_col_inflate_strides != 1) && (inputCol != origInputCol * m_col_inflate_strides))) { + return Scalar(m_paddingValue); + } + + // Calculate row index in the original input tensor. + const Index rowIndex = patch2DIndex - colIndex * m_outputRows; + const Index rowOffset = patchOffset - colOffset * m_colStride; + const Index inputRow = rowIndex * m_row_strides + rowOffset * m_in_row_strides - m_rowPaddingTop; + const Index origInputRow = (m_row_inflate_strides == 1) ? inputRow : ((inputRow >= 0) ? (inputRow / m_fastInflateRowStride) : 0); + if (inputRow < 0 || inputRow >= m_input_rows_eff || + ((m_row_inflate_strides != 1) && (inputRow != origInputRow * m_row_inflate_strides))) { + return Scalar(m_paddingValue); + } + + const int depth_index = static_cast(Layout) == static_cast(ColMajor) ? 0 : NumDims - 1; + const Index depth = index - (index / m_fastOutputDepth) * m_dimensions[depth_index]; + + const Index inputIndex = depth + origInputRow * m_rowInputStride + origInputCol * m_colInputStride + otherIndex * m_patchInputStride; + return m_impl.coeff(inputIndex); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + if (m_in_row_strides != 1 || m_in_col_strides != 1 || m_row_inflate_strides != 1 || m_col_inflate_strides != 1) { + return packetWithPossibleZero(index); + } + + const Index indices[2] = {index, index + PacketSize - 1}; + const Index patchIndex = indices[0] / m_fastPatchStride; + if (patchIndex != indices[1] / m_fastPatchStride) { + return packetWithPossibleZero(index); + } + const Index otherIndex = (NumDims == 4) ? 0 : indices[0] / m_fastOtherStride; + eigen_assert(otherIndex == indices[1] / m_fastOtherStride); + + // Find the offset of the element wrt the location of the first element. + const Index patchOffsets[2] = {(indices[0] - patchIndex * m_patchStride) / m_fastOutputDepth, + (indices[1] - patchIndex * m_patchStride) / m_fastOutputDepth}; + + const Index patch2DIndex = (NumDims == 4) ? patchIndex : (indices[0] - otherIndex * m_otherStride) / m_fastPatchStride; + eigen_assert(patch2DIndex == (indices[1] - otherIndex * m_otherStride) / m_fastPatchStride); + + const Index colIndex = patch2DIndex / m_fastOutputRows; + const Index colOffsets[2] = {patchOffsets[0] / m_fastColStride, patchOffsets[1] / m_fastColStride}; + + // Calculate col indices in the original input tensor. + const Index inputCols[2] = {colIndex * m_col_strides + colOffsets[0] - + m_colPaddingLeft, colIndex * m_col_strides + colOffsets[1] - m_colPaddingLeft}; + if (inputCols[1] < 0 || inputCols[0] >= m_inputCols) { + return internal::pset1(Scalar(m_paddingValue)); + } + + if (inputCols[0] == inputCols[1]) { + const Index rowIndex = patch2DIndex - colIndex * m_outputRows; + const Index rowOffsets[2] = {patchOffsets[0] - colOffsets[0]*m_colStride, patchOffsets[1] - colOffsets[1]*m_colStride}; + eigen_assert(rowOffsets[0] <= rowOffsets[1]); + // Calculate col indices in the original input tensor. + const Index inputRows[2] = {rowIndex * m_row_strides + rowOffsets[0] - + m_rowPaddingTop, rowIndex * m_row_strides + rowOffsets[1] - m_rowPaddingTop}; + + if (inputRows[1] < 0 || inputRows[0] >= m_inputRows) { + return internal::pset1(Scalar(m_paddingValue)); + } + + if (inputRows[0] >= 0 && inputRows[1] < m_inputRows) { + // no padding + const int depth_index = static_cast(Layout) == static_cast(ColMajor) ? 0 : NumDims - 1; + const Index depth = index - (index / m_fastOutputDepth) * m_dimensions[depth_index]; + const Index inputIndex = depth + inputRows[0] * m_rowInputStride + inputCols[0] * m_colInputStride + otherIndex * m_patchInputStride; + return m_impl.template packet(inputIndex); + } + } + + return packetWithPossibleZero(index); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const TensorEvaluator& impl() const { return m_impl; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowPaddingTop() const { return m_rowPaddingTop; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colPaddingLeft() const { return m_colPaddingLeft; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outputRows() const { return m_outputRows; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outputCols() const { return m_outputCols; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userRowStride() const { return m_row_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userColStride() const { return m_col_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userInRowStride() const { return m_in_row_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userInColStride() const { return m_in_col_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowInflateStride() const { return m_row_inflate_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colInflateStride() const { return m_col_inflate_strides; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + // We conservatively estimate the cost for the code path where the computed + // index is inside the original image and + // TensorEvaluator::CoordAccess is false. + const double compute_cost = 3 * TensorOpCost::DivCost() + + 6 * TensorOpCost::MulCost() + + 8 * TensorOpCost::MulCost(); + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetWithPossibleZero(Index index) const + { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + Dimensions m_dimensions; + + Index m_otherStride; + Index m_patchStride; + Index m_colStride; + Index m_row_strides; + Index m_col_strides; + + Index m_in_row_strides; + Index m_in_col_strides; + Index m_row_inflate_strides; + Index m_col_inflate_strides; + + Index m_input_rows_eff; + Index m_input_cols_eff; + Index m_patch_rows_eff; + Index m_patch_cols_eff; + + internal::TensorIntDivisor m_fastOtherStride; + internal::TensorIntDivisor m_fastPatchStride; + internal::TensorIntDivisor m_fastColStride; + internal::TensorIntDivisor m_fastInflateRowStride; + internal::TensorIntDivisor m_fastInflateColStride; + internal::TensorIntDivisor m_fastInputColsEff; + + Index m_rowInputStride; + Index m_colInputStride; + Index m_patchInputStride; + + Index m_inputDepth; + Index m_inputRows; + Index m_inputCols; + + Index m_outputRows; + Index m_outputCols; + + Index m_rowPaddingTop; + Index m_colPaddingLeft; + + internal::TensorIntDivisor m_fastOutputRows; + internal::TensorIntDivisor m_fastOutputDepth; + + Scalar m_paddingValue; + + const Device EIGEN_DEVICE_REF m_device; + TensorEvaluator m_impl; +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_IMAGE_PATCH_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIndexList.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIndexList.h new file mode 100644 index 0000000000000000000000000000000000000000..dc97d213ff0f97cd8a6998ee62ad3f52ebda9f00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIndexList.h @@ -0,0 +1,665 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_INDEX_LIST_H +#define EIGEN_CXX11_TENSOR_TENSOR_INDEX_LIST_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \internal + * + * \class TensorIndexList + * \ingroup CXX11_Tensor_Module + * + * \brief Set of classes used to encode a set of Tensor dimensions/indices. + * + * The indices in the list can be known at compile time or at runtime. A mix + * of static and dynamic indices can also be provided if needed. The tensor + * code will attempt to take advantage of the indices that are known at + * compile time to optimize the code it generates. + * + * This functionality requires a c++11 compliant compiler. If your compiler + * is older you need to use arrays of indices instead. + * + * Several examples are provided in the cxx11_tensor_index_list.cpp file. + * + * \sa Tensor + */ + +template +struct type2index { + static const Index value = n; + EIGEN_DEVICE_FUNC constexpr operator Index() const { return n; } + EIGEN_DEVICE_FUNC void set(Index val) { + eigen_assert(val == n); + } +}; + +// This can be used with IndexPairList to get compile-time constant pairs, +// such as IndexPairList, type2indexpair<3,4>>(). +template +struct type2indexpair { + static const Index first = f; + static const Index second = s; + + constexpr EIGEN_DEVICE_FUNC operator IndexPair() const { + return IndexPair(f, s); + } + + EIGEN_DEVICE_FUNC void set(const IndexPair& val) { + eigen_assert(val.first == f); + eigen_assert(val.second == s); + } +}; + + +template struct NumTraits > +{ + typedef Index Real; + enum { + IsComplex = 0, + RequireInitialization = false, + ReadCost = 1, + AddCost = 1, + MulCost = 1 + }; + + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR EIGEN_STRONG_INLINE Real epsilon() { return 0; } + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR EIGEN_STRONG_INLINE Real dummy_precision() { return 0; } + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR EIGEN_STRONG_INLINE Real highest() { return n; } + EIGEN_DEVICE_FUNC static EIGEN_CONSTEXPR EIGEN_STRONG_INLINE Real lowest() { return n; } +}; + +namespace internal { +template +EIGEN_DEVICE_FUNC void update_value(T& val, Index new_val) { + val = internal::convert_index(new_val); +} +template +EIGEN_DEVICE_FUNC void update_value(type2index& val, Index new_val) { + val.set(new_val); +} + +template +EIGEN_DEVICE_FUNC void update_value(T& val, IndexPair new_val) { + val = new_val; +} +template +EIGEN_DEVICE_FUNC void update_value(type2indexpair& val, IndexPair new_val) { + val.set(new_val); +} + + +template +struct is_compile_time_constant { + static constexpr bool value = false; +}; + +template +struct is_compile_time_constant > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant& > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant& > { + static constexpr bool value = true; +}; + +template +struct is_compile_time_constant > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant& > { + static constexpr bool value = true; +}; +template +struct is_compile_time_constant& > { + static constexpr bool value = true; +}; + + +template +struct IndexTuple; + +template +struct IndexTuple { + EIGEN_DEVICE_FUNC constexpr IndexTuple() : head(), others() { } + EIGEN_DEVICE_FUNC constexpr IndexTuple(const T& v, const O... o) : head(v), others(o...) { } + + constexpr static int count = 1 + sizeof...(O); + T head; + IndexTuple others; + typedef T Head; + typedef IndexTuple Other; +}; + +template + struct IndexTuple { + EIGEN_DEVICE_FUNC constexpr IndexTuple() : head() { } + EIGEN_DEVICE_FUNC constexpr IndexTuple(const T& v) : head(v) { } + + constexpr static int count = 1; + T head; + typedef T Head; +}; + + +template +struct IndexTupleExtractor; + +template +struct IndexTupleExtractor { + + typedef typename IndexTupleExtractor::ValType ValType; + + EIGEN_DEVICE_FUNC static constexpr ValType& get_val(IndexTuple& val) { + return IndexTupleExtractor::get_val(val.others); + } + + EIGEN_DEVICE_FUNC static constexpr const ValType& get_val(const IndexTuple& val) { + return IndexTupleExtractor::get_val(val.others); + } + template + EIGEN_DEVICE_FUNC static void set_val(IndexTuple& val, V& new_val) { + IndexTupleExtractor::set_val(val.others, new_val); + } + +}; + +template + struct IndexTupleExtractor<0, T, O...> { + + typedef T ValType; + + EIGEN_DEVICE_FUNC static constexpr ValType& get_val(IndexTuple& val) { + return val.head; + } + EIGEN_DEVICE_FUNC static constexpr const ValType& get_val(const IndexTuple& val) { + return val.head; + } + template + EIGEN_DEVICE_FUNC static void set_val(IndexTuple& val, V& new_val) { + val.head = new_val; + } +}; + + + +template +EIGEN_DEVICE_FUNC constexpr typename IndexTupleExtractor::ValType& array_get(IndexTuple& tuple) { + return IndexTupleExtractor::get_val(tuple); +} +template +EIGEN_DEVICE_FUNC constexpr const typename IndexTupleExtractor::ValType& array_get(const IndexTuple& tuple) { + return IndexTupleExtractor::get_val(tuple); +} +template + struct array_size > { + static const size_t value = IndexTuple::count; +}; +template + struct array_size > { + static const size_t value = IndexTuple::count; +}; + + + + +template +struct tuple_coeff { + template + EIGEN_DEVICE_FUNC static constexpr ValueT get(const Index i, const IndexTuple& t) { + // return array_get(t) * (i == Idx) + tuple_coeff::get(i, t) * (i != Idx); + return (i == Idx ? array_get(t) : tuple_coeff::get(i, t)); + } + template + EIGEN_DEVICE_FUNC static void set(const Index i, IndexTuple& t, const ValueT& value) { + if (i == Idx) { + update_value(array_get(t), value); + } else { + tuple_coeff::set(i, t, value); + } + } + + template + EIGEN_DEVICE_FUNC static constexpr bool value_known_statically(const Index i, const IndexTuple& t) { + return ((i == Idx) && is_compile_time_constant::ValType>::value) || + tuple_coeff::value_known_statically(i, t); + } + + template + EIGEN_DEVICE_FUNC static constexpr bool values_up_to_known_statically(const IndexTuple& t) { + return is_compile_time_constant::ValType>::value && + tuple_coeff::values_up_to_known_statically(t); + } + + template + EIGEN_DEVICE_FUNC static constexpr bool values_up_to_statically_known_to_increase(const IndexTuple& t) { + return is_compile_time_constant::ValType>::value && + is_compile_time_constant::ValType>::value && + array_get(t) > array_get(t) && + tuple_coeff::values_up_to_statically_known_to_increase(t); + } +}; + +template +struct tuple_coeff<0, ValueT> { + template + EIGEN_DEVICE_FUNC static constexpr ValueT get(const Index /*i*/, const IndexTuple& t) { + // eigen_assert (i == 0); // gcc fails to compile assertions in constexpr + return array_get<0>(t)/* * (i == 0)*/; + } + template + EIGEN_DEVICE_FUNC static void set(const Index i, IndexTuple& t, const ValueT value) { + eigen_assert (i == 0); + update_value(array_get<0>(t), value); + } + template + EIGEN_DEVICE_FUNC static constexpr bool value_known_statically(const Index i, const IndexTuple&) { + return is_compile_time_constant::ValType>::value && (i == 0); + } + + template + EIGEN_DEVICE_FUNC static constexpr bool values_up_to_known_statically(const IndexTuple&) { + return is_compile_time_constant::ValType>::value; + } + + template + EIGEN_DEVICE_FUNC static constexpr bool values_up_to_statically_known_to_increase(const IndexTuple&) { + return true; + } +}; +} // namespace internal + + + +template +struct IndexList : internal::IndexTuple { + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC constexpr Index operator[] (const Index i) const { + return internal::tuple_coeff >::value-1, Index>::get(i, *this); + } + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC constexpr Index get(const Index i) const { + return internal::tuple_coeff >::value-1, Index>::get(i, *this); + } + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void set(const Index i, const Index value) { + return internal::tuple_coeff >::value-1, Index>::set(i, *this, value); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC constexpr std::size_t size() const { + return 1 + sizeof...(OtherTypes); + }; + + + EIGEN_DEVICE_FUNC constexpr IndexList(const internal::IndexTuple& other) : internal::IndexTuple(other) { } + EIGEN_DEVICE_FUNC constexpr IndexList(FirstType& first, OtherTypes... other) : internal::IndexTuple(first, other...) { } + EIGEN_DEVICE_FUNC constexpr IndexList() : internal::IndexTuple() { } + + EIGEN_DEVICE_FUNC constexpr bool value_known_statically(const Index i) const { + return internal::tuple_coeff >::value-1, Index>::value_known_statically(i, *this); + } + EIGEN_DEVICE_FUNC constexpr bool all_values_known_statically() const { + return internal::tuple_coeff >::value-1, Index>::values_up_to_known_statically(*this); + } + + EIGEN_DEVICE_FUNC constexpr bool values_statically_known_to_increase() const { + return internal::tuple_coeff >::value-1, Index>::values_up_to_statically_known_to_increase(*this); + } +}; + +template +std::ostream& operator<<(std::ostream& os, + const IndexList& dims) { + os << "["; + for (size_t i = 0; i < 1 + sizeof...(OtherTypes); ++i) { + if (i > 0) os << ", "; + os << dims[i]; + } + os << "]"; + return os; +} + +template +constexpr IndexList make_index_list(FirstType val1, OtherTypes... other_vals) { + return IndexList(val1, other_vals...); +} + + +template +struct IndexPairList : internal::IndexTuple { + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC constexpr IndexPair operator[] (const Index i) const { + return internal::tuple_coeff >::value-1, IndexPair>::get(i, *this); + } + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC void set(const Index i, const IndexPair value) { + return internal::tuple_coeff>::value-1, IndexPair >::set(i, *this, value); + } + + EIGEN_DEVICE_FUNC constexpr IndexPairList(const internal::IndexTuple& other) : internal::IndexTuple(other) { } + EIGEN_DEVICE_FUNC constexpr IndexPairList() : internal::IndexTuple() { } + + EIGEN_DEVICE_FUNC constexpr bool value_known_statically(const Index i) const { + return internal::tuple_coeff >::value-1, Index>::value_known_statically(i, *this); + } +}; + +namespace internal { + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index array_prod(const IndexList& sizes) { + Index result = 1; + EIGEN_UNROLL_LOOP + for (size_t i = 0; i < array_size >::value; ++i) { + result *= sizes[i]; + } + return result; +} + +template struct array_size > { + static const size_t value = array_size >::value; +}; +template struct array_size > { + static const size_t value = array_size >::value; +}; + +template struct array_size > { + static const size_t value = 1 + sizeof...(OtherTypes); +}; +template struct array_size > { + static const size_t value = 1 + sizeof...(OtherTypes); +}; + +template EIGEN_DEVICE_FUNC constexpr Index array_get(IndexList& a) { + return IndexTupleExtractor::get_val(a); +} +template EIGEN_DEVICE_FUNC constexpr Index array_get(const IndexList& a) { + return IndexTupleExtractor::get_val(a); +} + +template +struct index_known_statically_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index) { + return false; + } +}; + +template +struct index_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i) { + return IndexList().value_known_statically(i); + } +}; + +template +struct index_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i) { + return IndexList().value_known_statically(i); + } +}; + + +template +struct all_indices_known_statically_impl { + static constexpr bool run() { + return false; + } +}; + +template +struct all_indices_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return IndexList().all_values_known_statically(); + } +}; + +template +struct all_indices_known_statically_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return IndexList().all_values_known_statically(); + } +}; + + +template +struct indices_statically_known_to_increase_impl { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return false; + } +}; + +template + struct indices_statically_known_to_increase_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return Eigen::IndexList().values_statically_known_to_increase(); + } +}; + +template + struct indices_statically_known_to_increase_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run() { + return Eigen::IndexList().values_statically_known_to_increase(); + } +}; + + +template +struct index_statically_eq_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) == value); + } +}; + +template +struct index_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) == value); + } +}; + + +template +struct index_statically_ne_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_statically_ne_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) != value); + } +}; + +template +struct index_statically_ne_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) != value); + } +}; + + +template +struct index_statically_gt_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_statically_gt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) > value); + } +}; + +template +struct index_statically_gt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) > value); + } +}; + + + +template +struct index_statically_lt_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_statically_lt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) < value); + } +}; + +template +struct index_statically_lt_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexList().value_known_statically(i) && + (IndexList().get(i) < value); + } +}; + + + +template +struct index_pair_first_statically_eq_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_pair_first_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexPairList().value_known_statically(i) && + (IndexPairList().operator[](i).first == value); + } +}; + +template +struct index_pair_first_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexPairList().value_known_statically(i) && + (IndexPairList().operator[](i).first == value); + } +}; + + + +template +struct index_pair_second_statically_eq_impl { + EIGEN_DEVICE_FUNC static constexpr bool run(Index, Index) { + return false; + } +}; + +template +struct index_pair_second_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexPairList().value_known_statically(i) && + (IndexPairList().operator[](i).second == value); + } +}; + +template +struct index_pair_second_statically_eq_impl > { + EIGEN_DEVICE_FUNC static constexpr bool run(const Index i, const Index value) { + return IndexPairList().value_known_statically(i) && + (IndexPairList().operator[](i).second == value); + } +}; + + +} // end namespace internal +} // end namespace Eigen + + +namespace Eigen { +namespace internal { +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_known_statically(Index i) { + return index_known_statically_impl::run(i); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool all_indices_known_statically() { + return all_indices_known_statically_impl::run(); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool indices_statically_known_to_increase() { + return indices_statically_known_to_increase_impl::run(); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_statically_eq(Index i, Index value) { + return index_statically_eq_impl::run(i, value); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_statically_ne(Index i, Index value) { + return index_statically_ne_impl::run(i, value); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_statically_gt(Index i, Index value) { + return index_statically_gt_impl::run(i, value); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_statically_lt(Index i, Index value) { + return index_statically_lt_impl::run(i, value); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_pair_first_statically_eq(Index i, Index value) { + return index_pair_first_statically_eq_impl::run(i, value); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR bool index_pair_second_statically_eq(Index i, Index value) { + return index_pair_second_statically_eq_impl::run(i, value); +} + +} // end namespace internal +} // end namespace Eigen + + +#endif // EIGEN_CXX11_TENSOR_TENSOR_INDEX_LIST_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInflation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInflation.h new file mode 100644 index 0000000000000000000000000000000000000000..7266305ec8067687a8280fd49454ee0c23348b49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInflation.h @@ -0,0 +1,242 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Ke Yang +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_INFLATION_H +#define EIGEN_CXX11_TENSOR_TENSOR_INFLATION_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorInflation + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor inflation class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorInflationOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorInflationOp type; +}; + +} // end namespace internal + +template +class TensorInflationOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorInflationOp(const XprType& expr, const Strides& strides) + : m_xpr(expr), m_strides(strides) {} + + EIGEN_DEVICE_FUNC + const Strides& strides() const { return m_strides; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const Strides m_strides; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorInflationOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = /*TensorEvaluator::IsAligned*/ false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_strides(op.strides()) + { + m_dimensions = m_impl.dimensions(); + // Expand each dimension to the inflated dimension. + for (int i = 0; i < NumDims; ++i) { + m_dimensions[i] = (m_dimensions[i] - 1) * op.strides()[i] + 1; + } + + // Remember the strides for fast division. + for (int i = 0; i < NumDims; ++i) { + m_fastStrides[i] = internal::TensorIntDivisor(m_strides[i]); + } + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_outputStrides[0] = 1; + m_inputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1]; + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + } + } else { // RowMajor + m_outputStrides[NumDims-1] = 1; + m_inputStrides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i+1] * m_dimensions[i+1]; + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + // Computes the input index given the output index. Returns true if the output + // index doesn't fall into a hole. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool getInputIndex(Index index, Index* inputIndex) const + { + eigen_assert(index < dimensions().TotalSize()); + *inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + if (idx != idx / m_fastStrides[i] * m_strides[i]) { + return false; + } + *inputIndex += idx / m_strides[i] * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + if (index != index / m_fastStrides[0] * m_strides[0]) { + return false; + } + *inputIndex += index / m_strides[0]; + return true; + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStrides[i]; + if (idx != idx / m_fastStrides[i] * m_strides[i]) { + return false; + } + *inputIndex += idx / m_strides[i] * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + if (index != index / m_fastStrides[NumDims-1] * m_strides[NumDims-1]) { + return false; + } + *inputIndex += index / m_strides[NumDims - 1]; + } + return true; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + Index inputIndex = 0; + if (getInputIndex(index, &inputIndex)) { + return m_impl.coeff(inputIndex); + } else { + return Scalar(0); + } + } + + // TODO(yangke): optimize this function so that we can detect and produce + // all-zero packets + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + EIGEN_STATIC_ASSERT((PacketSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + const double compute_cost = NumDims * (3 * TensorOpCost::DivCost() + + 3 * TensorOpCost::MulCost() + + 2 * TensorOpCost::AddCost()); + const double input_size = m_impl.dimensions().TotalSize(); + const double output_size = m_dimensions.TotalSize(); + if (output_size == 0) + return TensorOpCost(); + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(sizeof(CoeffReturnType) * input_size / output_size, 0, + compute_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + protected: + Dimensions m_dimensions; + array m_outputStrides; + array m_inputStrides; + TensorEvaluator m_impl; + const Strides m_strides; + array, NumDims> m_fastStrides; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_INFLATION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInitializer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInitializer.h new file mode 100644 index 0000000000000000000000000000000000000000..d8d977c9b4ce009665b2eaa744ab46739d002a30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorInitializer.h @@ -0,0 +1,80 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_INITIALIZER_H +#define EIGEN_CXX11_TENSOR_TENSOR_INITIALIZER_H + +#include + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorInitializer + * \ingroup CXX11_Tensor_Module + * + * \brief Helper template to initialize Tensors from std::initializer_lists. + */ +namespace internal { + +template +struct Initializer { + typedef std::initializer_list< + typename Initializer::InitList> InitList; + + static void run(TensorEvaluator& tensor, + Eigen::array::Index, traits::NumDimensions>* indices, + const InitList& vals) { + int i = 0; + for (const auto& v : vals) { + (*indices)[traits::NumDimensions - N] = i++; + Initializer::run(tensor, indices, v); + } + } +}; + +template +struct Initializer { + typedef std::initializer_list::Scalar> InitList; + + static void run(TensorEvaluator& tensor, + Eigen::array::Index, traits::NumDimensions>* indices, + const InitList& vals) { + int i = 0; + // There is likely a faster way to do that than iterating. + for (const auto& v : vals) { + (*indices)[traits::NumDimensions - 1] = i++; + tensor.coeffRef(*indices) = v; + } + } +}; + +template +struct Initializer { + typedef typename traits::Scalar InitList; + + static void run(TensorEvaluator& tensor, + Eigen::array::Index, traits::NumDimensions>*, + const InitList& v) { + tensor.coeffRef(0) = v; + } +}; + + +template +void initialize_tensor(TensorEvaluator& tensor, + const typename Initializer::NumDimensions>::InitList& vals) { + Eigen::array::Index, traits::NumDimensions> indices; + Initializer::NumDimensions>::run(tensor, &indices, vals); +} + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_INITIALIZER_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIntDiv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIntDiv.h new file mode 100644 index 0000000000000000000000000000000000000000..a921fea140bd9a070062cc8c68f25f2d00423ad8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorIntDiv.h @@ -0,0 +1,261 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_INTDIV_H +#define EIGEN_CXX11_TENSOR_TENSOR_INTDIV_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \internal + * + * \class TensorIntDiv + * \ingroup CXX11_Tensor_Module + * + * \brief Fast integer division by a constant. + * + * See the paper from Granlund and Montgomery for explanation. + * (at https://doi.org/10.1145/773473.178249) + * + * \sa Tensor + */ + +namespace internal { + + // Note: result is undefined if val == 0 + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + std::enable_if_t count_leading_zeros(const T val) + { +#ifdef EIGEN_GPU_COMPILE_PHASE + return __clz(val); +#elif defined(SYCL_DEVICE_ONLY) + return cl::sycl::clz(val); +#elif EIGEN_COMP_MSVC + unsigned long index; + _BitScanReverse(&index, val); + return 31 - index; +#else + EIGEN_STATIC_ASSERT(sizeof(unsigned long long) == 8, YOU_MADE_A_PROGRAMMING_MISTAKE); + return __builtin_clz(static_cast(val)); +#endif + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + std::enable_if_t count_leading_zeros(const T val) + { +#ifdef EIGEN_GPU_COMPILE_PHASE + return __clzll(val); +#elif defined(SYCL_DEVICE_ONLY) + return static_cast(cl::sycl::clz(val)); +#elif EIGEN_COMP_MSVC && EIGEN_ARCH_x86_64 + unsigned long index; + _BitScanReverse64(&index, val); + return 63 - index; +#elif EIGEN_COMP_MSVC + // MSVC's _BitScanReverse64 is not available for 32bits builds. + unsigned int lo = (unsigned int)(val&0xffffffff); + unsigned int hi = (unsigned int)((val>>32)&0xffffffff); + int n; + if(hi==0) + n = 32 + count_leading_zeros(lo); + else + n = count_leading_zeros(hi); + return n; +#else + EIGEN_STATIC_ASSERT(sizeof(unsigned long long) == 8, YOU_MADE_A_PROGRAMMING_MISTAKE); + return __builtin_clzll(static_cast(val)); +#endif + } + + template + struct UnsignedTraits { + typedef std::conditional_t type; + }; + + template + struct DividerTraits { + typedef typename UnsignedTraits::type type; + static constexpr int N = sizeof(T) * 8; + }; + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE uint32_t muluh(const uint32_t a, const T b) { +#if defined(EIGEN_GPU_COMPILE_PHASE) + return __umulhi(a, b); +#elif defined(SYCL_DEVICE_ONLY) + return cl::sycl::mul_hi(a, static_cast(b)); +#else + return (static_cast(a) * b) >> 32; +#endif + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE uint64_t muluh(const uint64_t a, const T b) { +#if defined(EIGEN_GPU_COMPILE_PHASE) + return __umul64hi(a, b); +#elif defined(SYCL_DEVICE_ONLY) + return cl::sycl::mul_hi(a, static_cast(b)); +#elif EIGEN_HAS_BUILTIN_INT128 + __uint128_t v = static_cast<__uint128_t>(a) * static_cast<__uint128_t>(b); + return static_cast(v >> 64); +#else + return (TensorUInt128, uint64_t>(a) * TensorUInt128, uint64_t>(b)).upper(); +#endif + } + + template + struct DividerHelper { + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE uint32_t computeMultiplier(const int log_div, const T divider) { + EIGEN_STATIC_ASSERT(N == 32, YOU_MADE_A_PROGRAMMING_MISTAKE); + return static_cast((static_cast(1) << (N+log_div)) / divider - (static_cast(1) << N) + 1); + } + }; + + template + struct DividerHelper<64, T> { + static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE uint64_t computeMultiplier(const int log_div, const T divider) { +#if EIGEN_HAS_BUILTIN_INT128 && !defined(EIGEN_GPU_COMPILE_PHASE) && !defined(SYCL_DEVICE_ONLY) + return static_cast((static_cast<__uint128_t>(1) << (64+log_div)) / static_cast<__uint128_t>(divider) - (static_cast<__uint128_t>(1) << 64) + 1); +#else + const uint64_t shift = 1ULL << log_div; + TensorUInt128 result = TensorUInt128 >(shift, 0) / TensorUInt128, uint64_t>(divider) + - TensorUInt128, static_val<0> >(1, 0) + + TensorUInt128, static_val<1> >(1); + return static_cast(result); +#endif + } + }; + +template +struct TensorIntDivisor { + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorIntDivisor() { + multiplier = 0; + shift1 = 0; + shift2 = 0; + } + + // Must have 0 < divider < 2^31. This is relaxed to + // 0 < divider < 2^63 when using 64-bit indices on platforms that support + // the __uint128_t type. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorIntDivisor(const T divider) { + const int N = DividerTraits::N; + eigen_assert(static_cast::type>(divider) < NumTraits::highest()/2); + eigen_assert(divider > 0); + + // fast ln2 + const int leading_zeros = count_leading_zeros(static_cast(divider)); + int log_div = N - leading_zeros; + // if divider is a power of two then log_div is 1 more than it should be. + if ((static_cast::type>(1) << (log_div-1)) == static_cast::type>(divider)) + log_div--; + + multiplier = DividerHelper::computeMultiplier(log_div, divider); + shift1 = log_div > 1 ? 1 : log_div; + shift2 = log_div > 1 ? log_div-1 : 0; + } + + // Must have 0 <= numerator. On platforms that don't support the __uint128_t + // type numerator should also be less than 2^32-1. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T divide(const T numerator) const { + eigen_assert(static_cast::type>(numerator) < NumTraits::highest()/2); + //eigen_assert(numerator >= 0); // this is implicitly asserted by the line above + + UnsignedType t1 = muluh(multiplier, numerator); + UnsignedType t = (static_cast(numerator) - t1) >> shift1; + return (t1 + t) >> shift2; + } + + private: + typedef typename DividerTraits::type UnsignedType; + UnsignedType multiplier; + int32_t shift1; + int32_t shift2; +}; + + +// Optimized version for signed 32 bit integers. +// Derived from Hacker's Delight. +// Only works for divisors strictly greater than one +template <> +class TensorIntDivisor { + public: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorIntDivisor() { + magic = 0; + shift = 0; + } + // Must have 2 <= divider + EIGEN_DEVICE_FUNC TensorIntDivisor(int32_t divider) { + eigen_assert(divider >= 2); + calcMagic(divider); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE int divide(const int32_t n) const { +#ifdef EIGEN_GPU_COMPILE_PHASE + return (__umulhi(magic, n) >> shift); +#elif defined(SYCL_DEVICE_ONLY) + return (cl::sycl::mul_hi(magic, static_cast(n)) >> shift); +#else + uint64_t v = static_cast(magic) * static_cast(n); + return (static_cast(v >> 32) >> shift); +#endif + } + +private: + // Compute the magic numbers. See Hacker's Delight section 10 for an in + // depth explanation. + EIGEN_DEVICE_FUNC void calcMagic(int32_t d) { + const unsigned two31 = 0x80000000; // 2**31. + unsigned ad = d; + unsigned t = two31 + (ad >> 31); + unsigned anc = t - 1 - t%ad; // Absolute value of nc. + int p = 31; // Init. p. + unsigned q1 = two31/anc; // Init. q1 = 2**p/|nc|. + unsigned r1 = two31 - q1*anc; // Init. r1 = rem(2**p, |nc|). + unsigned q2 = two31/ad; // Init. q2 = 2**p/|d|. + unsigned r2 = two31 - q2*ad; // Init. r2 = rem(2**p, |d|). + unsigned delta = 0; + do { + p = p + 1; + q1 = 2*q1; // Update q1 = 2**p/|nc|. + r1 = 2*r1; // Update r1 = rem(2**p, |nc|). + if (r1 >= anc) { // (Must be an unsigned + q1 = q1 + 1; // comparison here). + r1 = r1 - anc;} + q2 = 2*q2; // Update q2 = 2**p/|d|. + r2 = 2*r2; // Update r2 = rem(2**p, |d|). + if (r2 >= ad) { // (Must be an unsigned + q2 = q2 + 1; // comparison here). + r2 = r2 - ad;} + delta = ad - r2; + } while (q1 < delta || (q1 == delta && r1 == 0)); + + magic = (unsigned)(q2 + 1); + shift = p - 32; + } + + uint32_t magic; + int32_t shift; +}; + + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T operator / (const T& numerator, const TensorIntDivisor& divisor) { + return divisor.divide(numerator); +} + + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_INTDIV_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h new file mode 100644 index 0000000000000000000000000000000000000000..5a727bc82b69e509414356ee99ff78b38c78d55c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h @@ -0,0 +1,211 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H +#define EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorLayoutSwap + * \ingroup CXX11_Tensor_Module + * + * \brief Swap the layout from col-major to row-major, or row-major + * to col-major, and invert the order of the dimensions. + * + * Beware: the dimensions are reversed by this operation. If you want to + * preserve the ordering of the dimensions, you need to combine this + * operation with a shuffle. + * + * \example: + * Tensor input(2, 4); + * Tensor output = input.swap_layout(); + * eigen_assert(output.dimension(0) == 4); + * eigen_assert(output.dimension(1) == 2); + * + * array shuffle(1, 0); + * output = input.swap_layout().shuffle(shuffle); + * eigen_assert(output.dimension(0) == 2); + * eigen_assert(output.dimension(1) == 4); + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = traits::NumDimensions; + static constexpr int Layout = (traits::Layout == ColMajor) ? RowMajor : ColMajor; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorLayoutSwapOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorLayoutSwapOp type; +}; + +} // end namespace internal + + + +template +class TensorLayoutSwapOp : public TensorBase, WriteAccessors> +{ + public: + typedef TensorBase, WriteAccessors> Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorLayoutSwapOp(const XprType& expr) + : m_xpr(expr) {} + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorLayoutSwapOp) + protected: + typename XprType::Nested m_xpr; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorLayoutSwapOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + + static constexpr int Layout = (TensorEvaluator::Layout == static_cast(ColMajor)) ? RowMajor : ColMajor; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = TensorEvaluator::RawAccess + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device) + { + for(int i = 0; i < NumDims; ++i) { + m_dimensions[i] = m_impl.dimensions()[NumDims-1-i]; + } + } + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + return m_impl.evalSubExprsIfNeeded(data); + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_impl.coeff(index); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_impl.template packet(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return m_impl.costPerCoeff(vectorized); + } + + EIGEN_DEVICE_FUNC typename Storage::Type data() const { + return constCast(m_impl.data()); + } + + const TensorEvaluator& impl() const { return m_impl; } + + protected: + TensorEvaluator m_impl; + Dimensions m_dimensions; +}; + + +// Eval as lvalue +template + struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + typedef TensorLayoutSwapOp XprType; + + static constexpr int Layout = (TensorEvaluator::Layout == static_cast(ColMajor)) ? RowMajor : ColMajor; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false // to be implemented + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + return this->m_impl.coeffRef(index); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + this->m_impl.template writePacket(index, x); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_LAYOUT_SWAP_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMacros.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMacros.h new file mode 100644 index 0000000000000000000000000000000000000000..7d8814acf59f640a354f20b49dd7a429ffd0a871 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMacros.h @@ -0,0 +1,84 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_META_MACROS_H +#define EIGEN_CXX11_TENSOR_TENSOR_META_MACROS_H + + +/** use this macro in sfinae selection in templated functions + * + * template::value , int > = 0 + * > + * void foo(){} + * + * becomes => + * + * template::value ) + * > + * void foo(){} + */ + +#define EIGEN_SFINAE_ENABLE_IF( __condition__ ) \ + std::enable_if_t< ( __condition__ ) , int > = 0 + +// Define a macro to use a reference on the host but a value on the device +#if defined(SYCL_DEVICE_ONLY) + #define EIGEN_DEVICE_REF +#else + #define EIGEN_DEVICE_REF & +#endif + +// Define a macro for catching SYCL exceptions if exceptions are enabled +#define EIGEN_SYCL_TRY_CATCH(X) \ + do { \ + EIGEN_TRY {X;} \ + EIGEN_CATCH(const cl::sycl::exception& e) { \ + EIGEN_THROW_X(std::runtime_error("SYCL exception at " + \ + std::string(__FILE__) + ":" + \ + std::to_string(__LINE__) + "\n" + \ + e.what())); \ + } \ + } while (false) + +// Define a macro if local memory flags are unset or one of them is set +// Setting both flags is the same as unsetting them +#if (!defined(EIGEN_SYCL_LOCAL_MEM) && !defined(EIGEN_SYCL_NO_LOCAL_MEM)) || \ + (defined(EIGEN_SYCL_LOCAL_MEM) && defined(EIGEN_SYCL_NO_LOCAL_MEM)) + #define EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON 1 + #define EIGEN_SYCL_LOCAL_MEM_UNSET_OR_OFF 1 +#elif defined(EIGEN_SYCL_LOCAL_MEM) && !defined(EIGEN_SYCL_NO_LOCAL_MEM) + #define EIGEN_SYCL_LOCAL_MEM_UNSET_OR_ON 1 +#elif !defined(EIGEN_SYCL_LOCAL_MEM) && defined(EIGEN_SYCL_NO_LOCAL_MEM) + #define EIGEN_SYCL_LOCAL_MEM_UNSET_OR_OFF 1 +#endif + +#if EIGEN_COMP_CLANG // workaround clang bug (see http://forum.kde.org/viewtopic.php?f=74&t=102653) + #define EIGEN_TENSOR_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Derived) \ + using Base::operator =; \ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const Derived& other) { Base::operator=(other); return *this; } \ + template \ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& operator=(const OtherDerived& other) { Base::operator=(other); return *this; } +#else + #define EIGEN_TENSOR_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Derived) \ + EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Derived) +#endif + +/** \internal + * \brief Macro to manually inherit assignment operators. + * This is necessary, because the implicitly defined assignment operator gets deleted when a custom operator= is defined. + * This also inherits template operator=(const OtherDerived&) assignments. + * With C++11 or later this also default-implements the copy-constructor + */ +#define EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(Derived) \ + EIGEN_TENSOR_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Derived) \ + EIGEN_DEFAULT_COPY_CONSTRUCTOR(Derived) + +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMap.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMap.h new file mode 100644 index 0000000000000000000000000000000000000000..7a601ca1f270b73c514790fe8941ce305c82baa7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMap.h @@ -0,0 +1,211 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_MAP_H +#define EIGEN_CXX11_TENSOR_TENSOR_MAP_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +// FIXME use proper doxygen documentation (e.g. \tparam MakePointer_) + +/** \class TensorMap + * \ingroup CXX11_Tensor_Module + * + * \brief A tensor expression mapping an existing array of data. + * + */ +/// `template class MakePointer_` is added to convert the host pointer to the device pointer. +/// It is added due to the fact that for our device compiler `T*` is not allowed. +/// If we wanted to use the same Evaluator functions we have to convert that type to our pointer `T`. +/// This is done through our `MakePointer_` class. By default the Type in the `MakePointer_` is `T*` . +/// Therefore, by adding the default value, we managed to convert the type and it does not break any +/// existing code as its default value is `T*`. +template class MakePointer_> class TensorMap : public TensorBase > +{ + public: + typedef TensorMap Self; + typedef TensorBase > Base; + #ifdef EIGEN_USE_SYCL + typedef std::remove_reference_t::type> Nested; + #else + typedef typename Eigen::internal::nested::type Nested; + #endif + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef typename PlainObjectType::Base::CoeffReturnType CoeffReturnType; + + typedef typename MakePointer_::Type PointerType; + typedef typename MakePointer_::ConstType PointerConstType; + + // WARN: PointerType still can be a pointer to const (const Scalar*), for + // example in TensorMap> expression. This type of + // expression should be illegal, but adding this restriction is not possible + // in practice (see https://bitbucket.org/eigen/eigen/pull-requests/488). + typedef std::conditional_t< + bool(internal::is_lvalue::value), + PointerType, // use simple pointer in lvalue expressions + PointerConstType // use const pointer in rvalue expressions + > StoragePointerType; + + // If TensorMap was constructed over rvalue expression (e.g. const Tensor), + // we should return a reference to const from operator() (and others), even + // if TensorMap itself is not const. + typedef std::conditional_t< + bool(internal::is_lvalue::value), + Scalar&, + const Scalar& + > StorageRefType; + + static constexpr int Options = Options_; + + static constexpr Index NumIndices = PlainObjectType::NumIndices; + typedef typename PlainObjectType::Dimensions Dimensions; + + static constexpr int Layout = PlainObjectType::Layout; + enum { + IsAligned = ((int(Options_)&Aligned)==Aligned), + CoordAccess = true, + RawAccess = true + }; + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorMap(StoragePointerType dataPtr) : m_data(dataPtr), m_dimensions() { + // The number of dimensions used to construct a tensor must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT((0 == NumIndices || NumIndices == Dynamic), YOU_MADE_A_PROGRAMMING_MISTAKE) + } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorMap(StoragePointerType dataPtr, Index firstDimension, IndexTypes... otherDimensions) : m_data(dataPtr), m_dimensions(firstDimension, otherDimensions...) { + // The number of dimensions used to construct a tensor must be equal to the rank of the tensor. + EIGEN_STATIC_ASSERT((sizeof...(otherDimensions) + 1 == NumIndices || NumIndices == Dynamic), YOU_MADE_A_PROGRAMMING_MISTAKE) + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(StoragePointerType dataPtr, const array& dimensions) + : m_data(dataPtr), m_dimensions(dimensions) + { } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(StoragePointerType dataPtr, const Dimensions& dimensions) + : m_data(dataPtr), m_dimensions(dimensions) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorMap(PlainObjectType& tensor) + : m_data(tensor.data()), m_dimensions(tensor.dimensions()) + { } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rank() const { return m_dimensions.rank(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index dimension(Index n) const { return m_dimensions[n]; } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index size() const { return m_dimensions.TotalSize(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StoragePointerType data() { return m_data; } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StoragePointerType data() const { return m_data; } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(const array& indices) const + { + // eigen_assert(checkIndexRange(indices)); + if (PlainObjectType::Options&RowMajor) { + const Index index = m_dimensions.IndexOfRowMajor(indices); + return m_data[index]; + } else { + const Index index = m_dimensions.IndexOfColMajor(indices); + return m_data[index]; + } + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()() const + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE) + return m_data[0]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(Index index) const + { + eigen_internal_assert(index >= 0 && index < size()); + return m_data[index]; + } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) const + { + EIGEN_STATIC_ASSERT(sizeof...(otherIndices) + 2 == NumIndices, YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(internal::all((Eigen::NumTraits::highest() >= otherIndices)...)); + if (PlainObjectType::Options&RowMajor) { + const Index index = m_dimensions.IndexOfRowMajor(array{{firstIndex, secondIndex, otherIndices...}}); + return m_data[index]; + } else { + const Index index = m_dimensions.IndexOfColMajor(array{{firstIndex, secondIndex, otherIndices...}}); + return m_data[index]; + } + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(const array& indices) + { + // eigen_assert(checkIndexRange(indices)); + if (PlainObjectType::Options&RowMajor) { + const Index index = m_dimensions.IndexOfRowMajor(indices); + return m_data[index]; + } else { + const Index index = m_dimensions.IndexOfColMajor(indices); + return m_data[index]; + } + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()() + { + EIGEN_STATIC_ASSERT(NumIndices == 0, YOU_MADE_A_PROGRAMMING_MISTAKE) + return m_data[0]; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(Index index) + { + eigen_internal_assert(index >= 0 && index < size()); + return m_data[index]; + } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE StorageRefType operator()(Index firstIndex, Index secondIndex, IndexTypes... otherIndices) + { + static_assert(sizeof...(otherIndices) + 2 == NumIndices || NumIndices == Dynamic, "Number of indices used to access a tensor coefficient must be equal to the rank of the tensor."); + eigen_assert(internal::all((Eigen::NumTraits::highest() >= otherIndices)...)); + const std::size_t NumDims = sizeof...(otherIndices) + 2; + if (PlainObjectType::Options&RowMajor) { + const Index index = m_dimensions.IndexOfRowMajor(array{{firstIndex, secondIndex, otherIndices...}}); + return m_data[index]; + } else { + const Index index = m_dimensions.IndexOfColMajor(array{{firstIndex, secondIndex, otherIndices...}}); + return m_data[index]; + } + } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorMap) + + private: + StoragePointerType m_data; + Dimensions m_dimensions; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_MAP_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMeta.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMeta.h new file mode 100644 index 0000000000000000000000000000000000000000..5174d8ddf478f5b697e4d8c79a5c6c9438d20cf8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMeta.h @@ -0,0 +1,312 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_META_H +#define EIGEN_CXX11_TENSOR_TENSOR_META_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template struct Cond {}; + +template EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +const T1& choose(Cond, const T1& first, const T2&) { + return first; +} + +template EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +const T2& choose(Cond, const T1&, const T2& second) { + return second; +} + + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T divup(const X x, const Y y) { + // Note: This form is used because it cannot overflow. + return static_cast(x == 0 ? 0 : (x - 1) / y + 1); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T divup(const T x, const T y) { + // Note: This form is used because it cannot overflow. + return static_cast(x == 0 ? 0 : (x - 1) / y + 1); +} + +template struct max_n_1 { + static const size_t size = n; +}; +template <> struct max_n_1<0> { + static const size_t size = 1; +}; + + +// Default packet types +template +struct PacketType : internal::packet_traits { + typedef typename internal::packet_traits::type type; +}; + +// For CUDA packet types when using a GpuDevice +#if defined(EIGEN_USE_GPU) && defined(EIGEN_HAS_GPU_FP16) && defined(EIGEN_GPU_COMPILE_PHASE) + +typedef ulonglong2 Packet4h2; +template<> +struct PacketType { + typedef Packet4h2 type; + static const int size = 8; + enum { + HasAdd = 1, + HasSub = 1, + HasMul = 1, + HasNegate = 1, + HasAbs = 1, + HasArg = 0, + HasAbs2 = 0, + HasMin = 1, + HasMax = 1, + HasConj = 0, + HasSetLinear = 0, + HasBlend = 0, + + HasDiv = 1, + HasSqrt = 1, + HasRsqrt = 1, + HasExp = 1, + HasExpm1 = 0, + HasLog = 1, + HasLog1p = 0, + HasLog10 = 0, + HasPow = 1, + }; +}; +#endif + +#if defined(EIGEN_USE_SYCL) + +namespace TensorSycl { +namespace internal { + +template struct PlusOp { + static constexpr Index Value = A + B; +}; + +template struct DivOp { + static constexpr Index Value = A / B; +}; + +template class StepOp> +struct static_for { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void loop(UnaryOperator op) { + op(start); + static_for::Value, end, step, + StepOp>::loop(op); + } +}; +template class StepOp> +struct static_for { + template + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void loop(UnaryOperator) {} +}; + +template +struct Vectorise { + static constexpr int PacketSize = 1; + typedef OutScalar PacketReturnType; +}; + +template +struct Vectorise { + static constexpr int PacketSize = Eigen::PacketType::size; + typedef typename Eigen::PacketType::type PacketReturnType; +}; + +static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Index roundUp(Index x, Index y) { + return ((((x) + (y)-1) / (y)) * (y)); +} + +} // namespace internal +} // namespace TensorSycl + +template <> + struct PacketType { + typedef half type; + static const int size = 1; + enum { + HasAdd = 0, + HasSub = 0, + HasMul = 0, + HasNegate = 0, + HasAbs = 0, + HasArg = 0, + HasAbs2 = 0, + HasMin = 0, + HasMax = 0, + HasConj = 0, + HasSetLinear = 0, + HasBlend = 0 + }; +}; +template +struct PacketType : internal::default_packet_traits { + typedef Scalar type; + typedef Scalar half; + enum { + Vectorizable = 0, + size = 1, + AlignedOnScalar = 0, + }; + enum { + HasAdd = 0, + HasSub = 0, + HasMul = 0, + HasNegate = 0, + HasAbs = 0, + HasAbs2 = 0, + HasMin = 0, + HasMax = 0, + HasConj = 0, + HasSetLinear = 0 + }; + +}; + +template +struct PacketType : PacketType{}; + +#ifndef EIGEN_DONT_VECTORIZE_SYCL +#define PACKET_TYPE(CVQual, Type, val, lengths, DEV)\ +template<> struct PacketType : internal::sycl_packet_traits \ +{\ + typedef typename internal::packet_traits::type type;\ + typedef typename internal::packet_traits::half half;\ +}; + + +PACKET_TYPE(const, float, 1, 4, SyclDevice) +PACKET_TYPE(, float, 1, 4, SyclDevice) +PACKET_TYPE(const, float, 1, 4, const SyclDevice) +PACKET_TYPE(, float, 1, 4, const SyclDevice) + +PACKET_TYPE(const, double, 0, 2, SyclDevice) +PACKET_TYPE(, double, 0, 2, SyclDevice) +PACKET_TYPE(const, double, 0, 2, const SyclDevice) +PACKET_TYPE(, double, 0, 2, const SyclDevice) +#undef PACKET_TYPE + +template<> struct PacketType: PacketType{}; +template<> struct PacketType: PacketType{}; +#endif +#endif + +// Pair mimics std::pair but works on e.g. nvcc. +template struct Pair { + public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + U first; + V second; + + typedef U first_type; + typedef V second_type; + + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Pair() : first(), second() {} + + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Pair(const U& f, const V& s) : first(f), second(s) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void swap(Pair& rhs) { + using numext::swap; + swap(first, rhs.first); + swap(second, rhs.second); + } +}; + +template +EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +bool operator==(const Pair& x, const Pair& y) { + return (x.first == y.first && x.second == y.second); +} + +template +EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +bool operator!=(const Pair& x, const Pair& y) { + return !(x == y); +} + + +// Can't use std::pairs on cuda devices +template struct IndexPair { + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE IndexPair() : first(0), second(0) {} + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE IndexPair(Idx f, Idx s) : first(f), second(s) {} + + EIGEN_DEVICE_FUNC void set(IndexPair val) { + first = val.first; + second = val.second; + } + + Idx first; + Idx second; +}; + + +namespace internal { + + template + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + array customIndices2Array(IndexType& idx, numeric_list) { + return { static_cast(idx[First]), static_cast(idx[Is])... }; + } + template + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + array customIndices2Array(IndexType&, numeric_list) { + return array(); + } + + /** Make an array (for index/dimensions) out of a custom index */ + template + EIGEN_CONSTEXPR EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + array customIndices2Array(IndexType& idx) { + return customIndices2Array(idx, typename gen_numeric_list::type{}); + } + + + template + struct is_base_of + { + + typedef char (&yes)[1]; + typedef char (&no)[2]; + + template + struct Host + { + operator BB*() const; + operator DD*(); + }; + + template + static yes check(D*, T); + static no check(B*, int); + + static const bool value = sizeof(check(Host(), int())) == sizeof(yes); + }; + +} + +} // namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_META_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMorphing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMorphing.h new file mode 100644 index 0000000000000000000000000000000000000000..4445343e40dc7cb18002cbb2a2c9e9d0646d1211 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorMorphing.h @@ -0,0 +1,1084 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_MORPHING_H +#define EIGEN_CXX11_TENSOR_TENSOR_MORPHING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorReshaping + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor reshaping class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = array_size::value; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorReshapingOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorReshapingOp type; +}; + +} // end namespace internal + + + +template +class TensorReshapingOp : public TensorBase, WriteAccessors> +{ + public: + typedef TensorBase, WriteAccessors> Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReshapingOp(const XprType& expr, const NewDimensions& dims) + : m_xpr(expr), m_dims(dims) {} + + EIGEN_DEVICE_FUNC + const NewDimensions& dimensions() const { return m_dims; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorReshapingOp) + + protected: + typename XprType::Nested m_xpr; + const NewDimensions m_dims; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorReshapingOp XprType; + typedef NewDimensions Dimensions; + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + typedef StorageMemory, Device> ConstCastStorage; + + static constexpr int NumOutputDims = internal::array_size::value; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + + enum ReshapingKind { + // We do not use layout information to determine reshaping kind. + // Depending on the layout `N` can be inner or outer dimension. + OneByN = 0, // expr.reshape(1, N) + NByOne = 1, // expr.reshape(N, 1) + Runtime = 2 // Reshape dimensions are dynamic (specified at runtime). + }; + + // clang-format off + static const ReshapingKind kind = + (NumOutputDims == 2 && internal::index_statically_eq(/*index=*/0, /*value=*/1)) ? OneByN + : (NumOutputDims == 2 && internal::index_statically_eq(/*index=*/1, /*value=*/1)) ? NByOne + : Runtime; + // clang-format on + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + // For trivial reshapes with raw access to underlying data we will provide + // zero overhead block access. + // TODO(ezhulenev): Consider adding block access without raw access? + BlockAccess = TensorEvaluator::RawAccess && + NumInputDims > 0 && NumOutputDims > 0, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = TensorEvaluator::RawAccess + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef + typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_dimensions(op.dimensions()) + { + // The total size of the reshaped tensor must be equal to the total size + // of the input tensor. + eigen_assert(internal::array_prod(m_impl.dimensions()) == internal::array_prod(op.dimensions())); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType data, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(data, std::move(done)); + } +#endif + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + return m_impl.evalSubExprsIfNeeded(data); + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_impl.coeff(index); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + return m_impl.template packet(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return m_impl.costPerCoeff(vectorized); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + return internal::TensorBlockResourceRequirements::any(); + } + + // required in block(OutputTensorBlock* output_block) const + // For C++03 compatibility this must be defined outside the method + struct BlockIteratorState { + Index stride; + Index span; + Index size; + Index count; + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + eigen_assert(m_impl.data() != NULL); + eigen_assert((kind == Runtime) || + (kind == OneByN && desc.dimensions()[0] == 1) || + (kind == NByOne && desc.dimensions()[1] == 1)); + + if (kind == OneByN || kind == NByOne) { + // We can guarantee at compile time that block is just a contiguous slice + // of the underlying expression memory buffer. + return TensorBlock(internal::TensorBlockKind::kView, + m_impl.data() + desc.offset(), desc.dimensions()); + } else { + // This will do additional runtime checks, and in the end it might be also + // a view, or it might be a block materialized in the temporary buffer. + return TensorBlock::materialize(m_impl.data(), m_dimensions, desc, + scratch); + } + } + + EIGEN_DEVICE_FUNC typename Storage::Type data() const { + return constCast(m_impl.data()); + } + + EIGEN_DEVICE_FUNC const TensorEvaluator& impl() const { return m_impl; } + + protected: + TensorEvaluator m_impl; + NewDimensions m_dimensions; +}; + + +// Eval as lvalue +template + struct TensorEvaluator, Device> + : public TensorEvaluator, Device> + +{ + typedef TensorEvaluator, Device> Base; + typedef TensorReshapingOp XprType; + typedef NewDimensions Dimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = TensorEvaluator::IsAligned, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::RawAccess, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = TensorEvaluator::RawAccess + }; + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor + TensorBlockDesc; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + return this->m_impl.coeffRef(index); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + this->m_impl.template writePacket(index, x); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock( + const TensorBlockDesc& desc, const TensorBlock& block) { + eigen_assert(this->m_impl.data() != NULL); + + typedef typename TensorBlock::XprType TensorBlockExpr; + typedef internal::TensorBlockAssignment< + Scalar, TensorEvaluator::NumOutputDims, TensorBlockExpr, Index> + TensorBlockAssign; + + TensorBlockAssign::Run( + TensorBlockAssign::target(desc.dimensions(), + internal::strides(this->dimensions()), + this->m_impl.data(), desc.offset()), + block.expr()); + } +}; + + +/** \class TensorSlicing + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor slicing class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = array_size::value; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorSlicingOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorSlicingOp type; +}; + +} // end namespace internal + + + +template +class TensorSlicingOp : public TensorBase > +{ + public: + typedef TensorBase > Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorSlicingOp(const XprType& expr, const StartIndices& indices, const Sizes& sizes) + : m_xpr(expr), m_indices(indices), m_sizes(sizes) {} + + EIGEN_DEVICE_FUNC + const StartIndices& startIndices() const { return m_indices; } + EIGEN_DEVICE_FUNC + const Sizes& sizes() const { return m_sizes; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorSlicingOp) + + protected: + typename XprType::Nested m_xpr; + const StartIndices m_indices; + const Sizes m_sizes; +}; + + +namespace internal { + +// Fixme: figure out the exact threshold +template struct MemcpyTriggerForSlicing { + EIGEN_DEVICE_FUNC MemcpyTriggerForSlicing(const Device& device) : threshold_(2 * device.numThreads()) { } + EIGEN_DEVICE_FUNC bool operator ()(Index total, Index contiguous) const { + const bool prefer_block_evaluation = BlockAccess && total > 32*1024; + return !prefer_block_evaluation && contiguous > threshold_; + } + + private: + Index threshold_; +}; + +// It is very expensive to start the memcpy kernel on GPU: we therefore only +// use it for large copies. +#ifdef EIGEN_USE_GPU +template struct MemcpyTriggerForSlicing { + EIGEN_DEVICE_FUNC MemcpyTriggerForSlicing(const GpuDevice&) { } + EIGEN_DEVICE_FUNC bool operator ()(Index, Index contiguous) const { return contiguous > 4*1024*1024; } +}; +#endif + +// It is very expensive to start the memcpy kernel on GPU: we therefore only +// use it for large copies. +#ifdef EIGEN_USE_SYCL +template struct MemcpyTriggerForSlicing { + EIGEN_DEVICE_FUNC MemcpyTriggerForSlicing(const SyclDevice&) { } + EIGEN_DEVICE_FUNC bool operator ()(Index, Index contiguous) const { return contiguous > 4*1024*1024; } +}; +#endif + +} // namespace internal + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorSlicingOp XprType; + static constexpr int NumDims = internal::array_size::value; + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef Sizes Dimensions; + typedef StorageMemory Storage; + typedef StorageMemory, Device> ConstCastStorage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + // Alignment can't be guaranteed at compile time since it depends on the + // slice offsets and sizes. + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::BlockAccess && + // FIXME: Temporary workaround for bug in slicing of bool tensors. + !internal::is_same, bool>::value, + PreferBlockAccess = true, + CoordAccess = false, + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + // Tensor slicing does not change the block type. + typedef typename TensorEvaluator::TensorBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_device(device), m_dimensions(op.sizes()), m_offsets(op.startIndices()) + { + m_is_identity = true; + for (int i = 0; i < internal::array_size::value; ++i) { + eigen_assert(m_impl.dimensions()[i] >= + op.sizes()[i] + op.startIndices()[i]); + if (m_impl.dimensions()[i] != op.sizes()[i] || + op.startIndices()[i] != 0) { + m_is_identity = false; + } + } + + // No strides for scalars. + if (NumDims == 0) return; + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + const Sizes& output_dims = op.sizes(); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + } + + // Don't initialize m_fastOutputStrides[0] since it won't ever be accessed. + m_outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStrides[i] = m_outputStrides[i-1] * output_dims[i-1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1); + } + } else { + m_inputStrides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + } + + // Don't initialize m_fastOutputStrides[NumDims-1] since it won't ever be accessed. + m_outputStrides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i+1] * output_dims[i+1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + m_impl.evalSubExprsIfNeeded(NULL); + if (!NumTraits>::RequireInitialization + && data && m_impl.data()) { + Index contiguous_values = 1; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < NumDims; ++i) { + contiguous_values *= dimensions()[i]; + if (dimensions()[i] != m_impl.dimensions()[i]) { + break; + } + } + } else { + for (int i = NumDims-1; i >= 0; --i) { + contiguous_values *= dimensions()[i]; + if (dimensions()[i] != m_impl.dimensions()[i]) { + break; + } + } + } + // Use memcpy if it's going to be faster than using the regular evaluation. + const internal::MemcpyTriggerForSlicing trigger(m_device); + if (trigger(internal::array_prod(dimensions()), contiguous_values)) { + EvaluatorPointerType src = (EvaluatorPointerType)m_impl.data(); + for (Index i = 0; i < internal::array_prod(dimensions()); i += contiguous_values) { + Index offset = srcCoeff(i); + m_device.memcpy((void*)(m_device.get(data + i)), m_device.get(src+offset), contiguous_values * sizeof(Scalar)); + } + return false; + } + } + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType /*data*/, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + if (m_is_identity) { + return m_impl.coeff(index); + } else { + return m_impl.coeff(srcCoeff(index)); + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + const int packetSize = PacketType::size; + EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index+packetSize-1 < internal::array_prod(dimensions())); + + if (m_is_identity) { + return m_impl.template packet(index); + } + + Index inputIndices[] = {0, 0}; + Index indices[] = {index, index + packetSize - 1}; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx0 = indices[0] / m_fastOutputStrides[i]; + const Index idx1 = indices[1] / m_fastOutputStrides[i]; + inputIndices[0] += (idx0 + m_offsets[i]) * m_inputStrides[i]; + inputIndices[1] += (idx1 + m_offsets[i]) * m_inputStrides[i]; + indices[0] -= idx0 * m_outputStrides[i]; + indices[1] -= idx1 * m_outputStrides[i]; + } + inputIndices[0] += (indices[0] + m_offsets[0]); + inputIndices[1] += (indices[1] + m_offsets[0]); + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx0 = indices[0] / m_fastOutputStrides[i]; + const Index idx1 = indices[1] / m_fastOutputStrides[i]; + inputIndices[0] += (idx0 + m_offsets[i]) * m_inputStrides[i]; + inputIndices[1] += (idx1 + m_offsets[i]) * m_inputStrides[i]; + indices[0] -= idx0 * m_outputStrides[i]; + indices[1] -= idx1 * m_outputStrides[i]; + } + inputIndices[0] += (indices[0] + m_offsets[NumDims-1]); + inputIndices[1] += (indices[1] + m_offsets[NumDims-1]); + } + if (inputIndices[1] - inputIndices[0] == packetSize - 1) { + PacketReturnType rslt = m_impl.template packet(inputIndices[0]); + return rslt; + } + else { + EIGEN_ALIGN_MAX std::remove_const_t values[packetSize]; + values[0] = m_impl.coeff(inputIndices[0]); + values[packetSize-1] = m_impl.coeff(inputIndices[1]); + EIGEN_UNROLL_LOOP + for (int i = 1; i < packetSize-1; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, m_is_identity ? 1 : NumDims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + const size_t target_size = m_device.lastLevelCacheSize(); + return internal::TensorBlockResourceRequirements::merge( + internal::TensorBlockResourceRequirements::skewed(target_size), + m_impl.getResourceRequirements()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + TensorBlockDesc arg_desc = desc.WithOffset(srcCoeff(desc.offset())); + TensorBlock block = m_impl.block(arg_desc, scratch); + if (!arg_desc.HasDestinationBuffer()) desc.DropDestinationBuffer(); + return block; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const { + typename Storage::Type result = constCast(m_impl.data()); + if (result) { + Index offset = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < NumDims; ++i) { + if (m_dimensions[i] != m_impl.dimensions()[i]) { + offset += m_offsets[i] * m_inputStrides[i]; + for (int j = i+1; j < NumDims; ++j) { + if (m_dimensions[j] > 1) { + return NULL; + } + offset += m_offsets[j] * m_inputStrides[j]; + } + break; + } + } + } else { + for (int i = NumDims - 1; i >= 0; --i) { + if (m_dimensions[i] != m_impl.dimensions()[i]) { + offset += m_offsets[i] * m_inputStrides[i]; + for (int j = i-1; j >= 0; --j) { + if (m_dimensions[j] > 1) { + return NULL; + } + offset += m_offsets[j] * m_inputStrides[j]; + } + break; + } + } + } + return result + offset; + } + return NULL; + } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const + { + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += (idx + m_offsets[i]) * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + inputIndex += (index + m_offsets[0]); + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += (idx + m_offsets[i]) * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + inputIndex += (index + m_offsets[NumDims-1]); + } + return inputIndex; + } + + array m_outputStrides; + array, NumDims> m_fastOutputStrides; + array m_inputStrides; + TensorEvaluator m_impl; + const Device EIGEN_DEVICE_REF m_device; + Dimensions m_dimensions; + bool m_is_identity; + const StartIndices m_offsets; +}; + + +// Eval as lvalue +template +struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + typedef TensorSlicingOp XprType; + static constexpr int NumDims = internal::array_size::value; + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef Sizes Dimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::BlockAccess, + PreferBlockAccess = true, + CoordAccess = false, + RawAccess = (NumDims == 1) & TensorEvaluator::RawAccess + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + if (this->m_is_identity) { + return this->m_impl.coeffRef(index); + } else { + return this->m_impl.coeffRef(this->srcCoeff(index)); + } + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + if (this->m_is_identity) { + this->m_impl.template writePacket(index, x); + return; + } + + const int packetSize = PacketType::size; + Index inputIndices[] = {0, 0}; + Index indices[] = {index, index + packetSize - 1}; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx0 = indices[0] / this->m_fastOutputStrides[i]; + const Index idx1 = indices[1] / this->m_fastOutputStrides[i]; + inputIndices[0] += (idx0 + this->m_offsets[i]) * this->m_inputStrides[i]; + inputIndices[1] += (idx1 + this->m_offsets[i]) * this->m_inputStrides[i]; + indices[0] -= idx0 * this->m_outputStrides[i]; + indices[1] -= idx1 * this->m_outputStrides[i]; + } + inputIndices[0] += (indices[0] + this->m_offsets[0]); + inputIndices[1] += (indices[1] + this->m_offsets[0]); + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx0 = indices[0] / this->m_fastOutputStrides[i]; + const Index idx1 = indices[1] / this->m_fastOutputStrides[i]; + inputIndices[0] += (idx0 + this->m_offsets[i]) * this->m_inputStrides[i]; + inputIndices[1] += (idx1 + this->m_offsets[i]) * this->m_inputStrides[i]; + indices[0] -= idx0 * this->m_outputStrides[i]; + indices[1] -= idx1 * this->m_outputStrides[i]; + } + inputIndices[0] += (indices[0] + this->m_offsets[NumDims-1]); + inputIndices[1] += (indices[1] + this->m_offsets[NumDims-1]); + } + if (inputIndices[1] - inputIndices[0] == packetSize - 1) { + this->m_impl.template writePacket(inputIndices[0], x); + } + else { + EIGEN_ALIGN_MAX CoeffReturnType values[packetSize]; + internal::pstore(values, x); + this->m_impl.coeffRef(inputIndices[0]) = values[0]; + this->m_impl.coeffRef(inputIndices[1]) = values[packetSize-1]; + EIGEN_UNROLL_LOOP + for (int i = 1; i < packetSize-1; ++i) { + this->coeffRef(index+i) = values[i]; + } + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock( + const TensorBlockDesc& desc, const TensorBlock& block) { + TensorBlockDesc arg_desc = desc.WithOffset(this->srcCoeff(desc.offset())); + this->m_impl.writeBlock(arg_desc, block); + } +}; + +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = array_size::value; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorStridingSlicingOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorStridingSlicingOp type; +}; + +} // end namespace internal + + +template +class TensorStridingSlicingOp : public TensorBase > +{ + public: + typedef TensorBase > Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorStridingSlicingOp( + const XprType& expr, const StartIndices& startIndices, + const StopIndices& stopIndices, const Strides& strides) + : m_xpr(expr), m_startIndices(startIndices), m_stopIndices(stopIndices), + m_strides(strides) {} + + EIGEN_DEVICE_FUNC + const StartIndices& startIndices() const { return m_startIndices; } + EIGEN_DEVICE_FUNC + const StartIndices& stopIndices() const { return m_stopIndices; } + EIGEN_DEVICE_FUNC + const StartIndices& strides() const { return m_strides; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorStridingSlicingOp) + + protected: + typename XprType::Nested m_xpr; + const StartIndices m_startIndices; + const StopIndices m_stopIndices; + const Strides m_strides; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorStridingSlicingOp XprType; + static constexpr int NumDims = internal::array_size::value; + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + typedef Strides Dimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + // Alignment can't be guaranteed at compile time since it depends on the + // slice offsets and sizes. + IsAligned = false, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), + m_device(device), + m_strides(op.strides()) + { + // Handle degenerate intervals by gracefully clamping and allowing m_dimensions to be zero + DSizes startIndicesClamped, stopIndicesClamped; + for (ptrdiff_t i = 0; i < internal::array_size::value; ++i) { + eigen_assert(m_strides[i] != 0 && "0 stride is invalid"); + if (m_strides[i] > 0) { + startIndicesClamped[i] = + clamp(op.startIndices()[i], 0, m_impl.dimensions()[i]); + stopIndicesClamped[i] = + clamp(op.stopIndices()[i], 0, m_impl.dimensions()[i]); + } else { + /* implies m_strides[i] < 0 by assert */ + startIndicesClamped[i] = + clamp(op.startIndices()[i], -1, m_impl.dimensions()[i] - 1); + stopIndicesClamped[i] = + clamp(op.stopIndices()[i], -1, m_impl.dimensions()[i] - 1); + } + m_startIndices[i] = startIndicesClamped[i]; + } + + typedef typename TensorEvaluator::Dimensions InputDimensions; + const InputDimensions& input_dims = m_impl.dimensions(); + + // compute output tensor shape + m_is_identity = true; + for (int i = 0; i < NumDims; i++) { + Index interval = stopIndicesClamped[i] - startIndicesClamped[i]; + if (interval == 0 || ((interval < 0) != (m_strides[i] < 0))) { + m_dimensions[i] = 0; + } else { + m_dimensions[i] = + (interval / m_strides[i]) + (interval % m_strides[i] != 0 ? 1 : 0); + eigen_assert(m_dimensions[i] >= 0); + } + if (m_strides[i] != 1 || interval != m_impl.dimensions()[i]) { + m_is_identity = false; + } + } + + Strides output_dims = m_dimensions; + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputStrides[0] = m_strides[0]; + m_offsets[0] = startIndicesClamped[0]; + Index previousDimProduct = 1; + for (int i = 1; i < NumDims; ++i) { + previousDimProduct *= input_dims[i-1]; + m_inputStrides[i] = previousDimProduct * m_strides[i]; + m_offsets[i] = startIndicesClamped[i] * previousDimProduct; + } + + // Don't initialize m_fastOutputStrides[0] since it won't ever be accessed. + m_outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStrides[i] = m_outputStrides[i-1] * output_dims[i-1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1); + } + } else { + m_inputStrides[NumDims-1] = m_strides[NumDims-1]; + m_offsets[NumDims-1] = startIndicesClamped[NumDims-1]; + Index previousDimProduct = 1; + for (int i = NumDims - 2; i >= 0; --i) { + previousDimProduct *= input_dims[i+1]; + m_inputStrides[i] = previousDimProduct * m_strides[i]; + m_offsets[i] = startIndicesClamped[i] * previousDimProduct; + } + + m_outputStrides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i+1] * output_dims[i+1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + if (m_is_identity) { + return m_impl.coeff(index); + } else { + return m_impl.coeff(srcCoeff(index)); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, m_is_identity ? 1 : NumDims); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const { + return NULL; + } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const + { + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i >= 0; --i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += idx * m_inputStrides[i] + m_offsets[i]; + index -= idx * m_outputStrides[i]; + } + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims; ++i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += idx * m_inputStrides[i] + m_offsets[i]; + index -= idx * m_outputStrides[i]; + } + } + return inputIndex; + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index clamp(Index value, Index min, Index max) { +#ifndef SYCL_DEVICE_ONLY + return numext::maxi(min, numext::mini(max,value)); +#else + return cl::sycl::clamp(value, min, max); +#endif + } + + array m_outputStrides; + array, NumDims> m_fastOutputStrides; + array m_inputStrides; + bool m_is_identity; + TensorEvaluator m_impl; + const Device EIGEN_DEVICE_REF m_device; + DSizes m_startIndices; // clamped startIndices + DSizes m_dimensions; + DSizes m_offsets; // offset in a flattened shape + const Strides m_strides; +}; + +// Eval as lvalue +template +struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + typedef TensorStridingSlicingOp XprType; + static constexpr int NumDims = internal::array_size::value; + static constexpr int Layout = TensorEvaluator::Layout; + + enum { + IsAligned = false, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = TensorEvaluator::CoordAccess, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef Strides Dimensions; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + if (this->m_is_identity) { + return this->m_impl.coeffRef(index); + } else { + return this->m_impl.coeffRef(this->srcCoeff(index)); + } + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_MORPHING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPadding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPadding.h new file mode 100644 index 0000000000000000000000000000000000000000..60dc7ab3998ca4ad7ca0f8a70354f185862e0fad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPadding.h @@ -0,0 +1,686 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_PADDING_H +#define EIGEN_CXX11_TENSOR_TENSOR_PADDING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorPadding + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor padding class. + * At the moment only padding with a constant value is supported. + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorPaddingOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorPaddingOp type; +}; + +} // end namespace internal + + + +template +class TensorPaddingOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorPaddingOp(const XprType& expr, const PaddingDimensions& padding_dims, const Scalar padding_value) + : m_xpr(expr), m_padding_dims(padding_dims), m_padding_value(padding_value) {} + + EIGEN_DEVICE_FUNC + const PaddingDimensions& padding() const { return m_padding_dims; } + EIGEN_DEVICE_FUNC + Scalar padding_value() const { return m_padding_value; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const PaddingDimensions m_padding_dims; + const Scalar m_padding_value; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorPaddingOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = true, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = TensorEvaluator::RawAccess, + PreferBlockAccess = true, + CoordAccess = true, + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_padding(op.padding()), m_paddingValue(op.padding_value()), m_device(device) + { + // The padding op doesn't change the rank of the tensor. Directly padding a scalar would lead + // to a vector, which doesn't make sense. Instead one should reshape the scalar into a vector + // of 1 element first and then pad. + EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + + // Compute dimensions + m_dimensions = m_impl.dimensions(); + for (int i = 0; i < NumDims; ++i) { + m_dimensions[i] += m_padding[i].first + m_padding[i].second; + } + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputStrides[0] = 1; + m_outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1]; + } + m_outputStrides[NumDims] = m_outputStrides[NumDims-1] * m_dimensions[NumDims-1]; + } else { + m_inputStrides[NumDims - 1] = 1; + m_outputStrides[NumDims] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + m_outputStrides[i+1] = m_outputStrides[i+2] * m_dimensions[i+1]; + } + m_outputStrides[0] = m_outputStrides[1] * m_dimensions[0]; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + eigen_assert(index < dimensions().TotalSize()); + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + if (isPaddingAtIndexForDim(idx, i)) { + return m_paddingValue; + } + inputIndex += (idx - m_padding[i].first) * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + if (isPaddingAtIndexForDim(index, 0)) { + return m_paddingValue; + } + inputIndex += (index - m_padding[0].first); + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStrides[i+1]; + if (isPaddingAtIndexForDim(idx, i)) { + return m_paddingValue; + } + inputIndex += (idx - m_padding[i].first) * m_inputStrides[i]; + index -= idx * m_outputStrides[i+1]; + } + if (isPaddingAtIndexForDim(index, NumDims-1)) { + return m_paddingValue; + } + inputIndex += (index - m_padding[NumDims-1].first); + } + return m_impl.coeff(inputIndex); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + if (static_cast(Layout) == static_cast(ColMajor)) { + return packetColMajor(index); + } + return packetRowMajor(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + TensorOpCost cost = m_impl.costPerCoeff(vectorized); + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims; ++i) + updateCostPerDimension(cost, i, i == 0); + } else { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i >= 0; --i) + updateCostPerDimension(cost, i, i == NumDims - 1); + } + return cost; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + const size_t target_size = m_device.lastLevelCacheSize(); + return internal::TensorBlockResourceRequirements::merge( + internal::TensorBlockResourceRequirements::skewed(target_size), + m_impl.getResourceRequirements()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + // If one of the dimensions is zero, return empty block view. + if (desc.size() == 0) { + return TensorBlock(internal::TensorBlockKind::kView, NULL, + desc.dimensions()); + } + + static const bool IsColMajor = Layout == static_cast(ColMajor); + const int inner_dim_idx = IsColMajor ? 0 : NumDims - 1; + + Index offset = desc.offset(); + + // Compute offsets in the output tensor corresponding to the desc.offset(). + DSizes output_offsets; + for (int i = NumDims - 1; i > 0; --i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + const int stride_dim = IsColMajor ? dim : dim + 1; + output_offsets[dim] = offset / m_outputStrides[stride_dim]; + offset -= output_offsets[dim] * m_outputStrides[stride_dim]; + } + output_offsets[inner_dim_idx] = offset; + + // Offsets in the input corresponding to output offsets. + DSizes input_offsets = output_offsets; + for (int i = 0; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + input_offsets[dim] = input_offsets[dim] - m_padding[dim].first; + } + + // Compute offset in the input buffer (at this point it might be illegal and + // point outside of the input buffer, because we don't check for negative + // offsets, it will be autocorrected in the block iteration loop below). + Index input_offset = 0; + for (int i = 0; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + input_offset += input_offsets[dim] * m_inputStrides[dim]; + } + + // Destination buffer and scratch buffer both indexed from 0 and have the + // same dimensions as the requested block (for destination buffer this + // property is guaranteed by `desc.destination()`). + Index output_offset = 0; + const DSizes output_strides = + internal::strides(desc.dimensions()); + + // NOTE(ezhulenev): We initialize bock iteration state for `NumDims - 1` + // dimensions, skipping innermost dimension. In theory it should be possible + // to squeeze matching innermost dimensions, however in practice that did + // not show any improvements in benchmarks. Also in practice first outer + // dimension usually has padding, and will prevent squeezing. + + // Initialize output block iterator state. Dimension in this array are + // always in inner_most -> outer_most order (col major layout). + array it; + for (int i = 0; i < NumDims - 1; ++i) { + const int dim = IsColMajor ? i + 1 : NumDims - i - 2; + it[i].count = 0; + it[i].size = desc.dimension(dim); + + it[i].input_stride = m_inputStrides[dim]; + it[i].input_span = it[i].input_stride * (it[i].size - 1); + + it[i].output_stride = output_strides[dim]; + it[i].output_span = it[i].output_stride * (it[i].size - 1); + } + + const Index input_inner_dim_size = + static_cast(m_impl.dimensions()[inner_dim_idx]); + + // Total output size. + const Index output_size = desc.size(); + + // We will fill inner dimension of this size in the output. It might be + // larger than the inner dimension in the input, so we might have to pad + // before/after we copy values from the input inner dimension. + const Index output_inner_dim_size = desc.dimension(inner_dim_idx); + + // How many values to fill with padding BEFORE reading from the input inner + // dimension. + const Index output_inner_pad_before_size = + input_offsets[inner_dim_idx] < 0 + ? numext::mini(numext::abs(input_offsets[inner_dim_idx]), + output_inner_dim_size) + : 0; + + // How many values we can actually copy from the input inner dimension. + const Index output_inner_copy_size = numext::mini( + // Want to copy from input. + (output_inner_dim_size - output_inner_pad_before_size), + // Can copy from input. + numext::maxi(input_inner_dim_size - (input_offsets[inner_dim_idx] + + output_inner_pad_before_size), + Index(0))); + + eigen_assert(output_inner_copy_size >= 0); + + // How many values to fill with padding AFTER reading from the input inner + // dimension. + const Index output_inner_pad_after_size = + (output_inner_dim_size - output_inner_copy_size - + output_inner_pad_before_size); + + // Sanity check, sum of all sizes must be equal to the output size. + eigen_assert(output_inner_dim_size == + (output_inner_pad_before_size + output_inner_copy_size + + output_inner_pad_after_size)); + + // Keep track of current coordinates and padding in the output. + DSizes output_coord = output_offsets; + DSizes output_padded; + for (int i = 0; i < NumDims; ++i) { + const int dim = IsColMajor ? i : NumDims - i - 1; + output_padded[dim] = isPaddingAtIndexForDim(output_coord[dim], dim); + } + + typedef internal::StridedLinearBufferCopy LinCopy; + + // Prepare storage for the materialized padding result. + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage(desc, scratch); + + // TODO(ezhulenev): Squeeze multiple non-padded inner dimensions into a + // single logical inner dimension. + + // When possible we squeeze writes for the innermost (only if non-padded) + // dimension with the first padded dimension. This allows to reduce the + // number of calls to LinCopy and better utilize vector instructions. + const bool squeeze_writes = + NumDims > 1 && + // inner dimension is not padded + (input_inner_dim_size == m_dimensions[inner_dim_idx]) && + // and equal to the block inner dimension + (input_inner_dim_size == output_inner_dim_size); + + const int squeeze_dim = IsColMajor ? inner_dim_idx + 1 : inner_dim_idx - 1; + + // Maximum coordinate on a squeeze dimension that we can write to. + const Index squeeze_max_coord = + squeeze_writes ? numext::mini( + // max non-padded element in the input + static_cast(m_dimensions[squeeze_dim] - + m_padding[squeeze_dim].second), + // max element in the output buffer + static_cast(output_offsets[squeeze_dim] + + desc.dimension(squeeze_dim))) + : static_cast(0); + + // Iterate copying data from `m_impl.data()` to the output buffer. + for (Index size = 0; size < output_size;) { + // Detect if we are in the padded region (exclude innermost dimension). + bool is_padded = false; + for (int j = 1; j < NumDims; ++j) { + const int dim = IsColMajor ? j : NumDims - j - 1; + is_padded = output_padded[dim]; + if (is_padded) break; + } + + if (is_padded) { + // Fill single innermost dimension with padding value. + size += output_inner_dim_size; + + LinCopy::template Run( + typename LinCopy::Dst(output_offset, 1, block_storage.data()), + typename LinCopy::Src(0, 0, &m_paddingValue), + output_inner_dim_size); + + + } else if (squeeze_writes) { + // Squeeze multiple reads from innermost dimensions. + const Index squeeze_num = squeeze_max_coord - output_coord[squeeze_dim]; + size += output_inner_dim_size * squeeze_num; + + // Copy `squeeze_num` inner dimensions from input to output. + LinCopy::template Run( + typename LinCopy::Dst(output_offset, 1, block_storage.data()), + typename LinCopy::Src(input_offset, 1, m_impl.data()), + output_inner_dim_size * squeeze_num); + + // Update iteration state for only `squeeze_num - 1` processed inner + // dimensions, because we have another iteration state update at the end + // of the loop that will update iteration state for the last inner + // processed dimension. + it[0].count += (squeeze_num - 1); + input_offset += it[0].input_stride * (squeeze_num - 1); + output_offset += it[0].output_stride * (squeeze_num - 1); + output_coord[squeeze_dim] += (squeeze_num - 1); + + } else { + // Single read from innermost dimension. + size += output_inner_dim_size; + + { // Fill with padding before copying from input inner dimension. + const Index out = output_offset; + + LinCopy::template Run( + typename LinCopy::Dst(out, 1, block_storage.data()), + typename LinCopy::Src(0, 0, &m_paddingValue), + output_inner_pad_before_size); + } + + { // Copy data from input inner dimension. + const Index out = output_offset + output_inner_pad_before_size; + const Index in = input_offset + output_inner_pad_before_size; + + eigen_assert(output_inner_copy_size == 0 || m_impl.data() != NULL); + + LinCopy::template Run( + typename LinCopy::Dst(out, 1, block_storage.data()), + typename LinCopy::Src(in, 1, m_impl.data()), + output_inner_copy_size); + } + + { // Fill with padding after copying from input inner dimension. + const Index out = output_offset + output_inner_pad_before_size + + output_inner_copy_size; + + LinCopy::template Run( + typename LinCopy::Dst(out, 1, block_storage.data()), + typename LinCopy::Src(0, 0, &m_paddingValue), + output_inner_pad_after_size); + } + } + + for (int j = 0; j < NumDims - 1; ++j) { + const int dim = IsColMajor ? j + 1 : NumDims - j - 2; + + if (++it[j].count < it[j].size) { + input_offset += it[j].input_stride; + output_offset += it[j].output_stride; + output_coord[dim] += 1; + output_padded[dim] = isPaddingAtIndexForDim(output_coord[dim], dim); + break; + } + it[j].count = 0; + input_offset -= it[j].input_span; + output_offset -= it[j].output_span; + output_coord[dim] -= it[j].size - 1; + output_padded[dim] = isPaddingAtIndexForDim(output_coord[dim], dim); + } + } + + return block_storage.AsTensorMaterializedBlock(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return NULL; } + + private: + struct BlockIteratorState { + BlockIteratorState() + : count(0), + size(0), + input_stride(0), + input_span(0), + output_stride(0), + output_span(0) {} + + Index count; + Index size; + Index input_stride; + Index input_span; + Index output_stride; + Index output_span; + }; + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool isPaddingAtIndexForDim( + Index index, int dim_index) const { + return (!internal::index_pair_first_statically_eq(dim_index, 0) && + index < m_padding[dim_index].first) || + (!internal::index_pair_second_statically_eq(dim_index, 0) && + index >= m_dimensions[dim_index] - m_padding[dim_index].second); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool isLeftPaddingCompileTimeZero( + int dim_index) const { + return internal::index_pair_first_statically_eq(dim_index, 0); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE bool isRightPaddingCompileTimeZero( + int dim_index) const { + return internal::index_pair_second_statically_eq(dim_index, 0); + } + + + void updateCostPerDimension(TensorOpCost& cost, int i, bool first) const { + const double in = static_cast(m_impl.dimensions()[i]); + const double out = in + m_padding[i].first + m_padding[i].second; + if (out == 0) + return; + const double reduction = in / out; + cost *= reduction; + if (first) { + cost += TensorOpCost(0, 0, 2 * TensorOpCost::AddCost() + + reduction * (1 * TensorOpCost::AddCost())); + } else { + cost += TensorOpCost(0, 0, 2 * TensorOpCost::AddCost() + + 2 * TensorOpCost::MulCost() + + reduction * (2 * TensorOpCost::MulCost() + + 1 * TensorOpCost::DivCost())); + } + } + + protected: + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetColMajor(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + const Index initialIndex = index; + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index firstIdx = index; + const Index lastIdx = index + PacketSize - 1; + const Index lastPaddedLeft = m_padding[i].first * m_outputStrides[i]; + const Index firstPaddedRight = (m_dimensions[i] - m_padding[i].second) * m_outputStrides[i]; + const Index lastPaddedRight = m_outputStrides[i+1]; + + if (!isLeftPaddingCompileTimeZero(i) && lastIdx < lastPaddedLeft) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if (!isRightPaddingCompileTimeZero(i) && firstIdx >= firstPaddedRight && lastIdx < lastPaddedRight) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if ((isLeftPaddingCompileTimeZero(i) && isRightPaddingCompileTimeZero(i)) || (firstIdx >= lastPaddedLeft && lastIdx < firstPaddedRight)) { + // all the coefficient are between the 2 padding zones. + const Index idx = index / m_outputStrides[i]; + inputIndex += (idx - m_padding[i].first) * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + else { + // Every other case + return packetWithPossibleZero(initialIndex); + } + } + + const Index lastIdx = index + PacketSize - 1; + const Index firstIdx = index; + const Index lastPaddedLeft = m_padding[0].first; + const Index firstPaddedRight = (m_dimensions[0] - m_padding[0].second); + const Index lastPaddedRight = m_outputStrides[1]; + + if (!isLeftPaddingCompileTimeZero(0) && lastIdx < lastPaddedLeft) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if (!isRightPaddingCompileTimeZero(0) && firstIdx >= firstPaddedRight && lastIdx < lastPaddedRight) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if ((isLeftPaddingCompileTimeZero(0) && isRightPaddingCompileTimeZero(0)) || (firstIdx >= lastPaddedLeft && lastIdx < firstPaddedRight)) { + // all the coefficient are between the 2 padding zones. + inputIndex += (index - m_padding[0].first); + return m_impl.template packet(inputIndex); + } + // Every other case + return packetWithPossibleZero(initialIndex); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetRowMajor(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + const Index initialIndex = index; + Index inputIndex = 0; + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index firstIdx = index; + const Index lastIdx = index + PacketSize - 1; + const Index lastPaddedLeft = m_padding[i].first * m_outputStrides[i+1]; + const Index firstPaddedRight = (m_dimensions[i] - m_padding[i].second) * m_outputStrides[i+1]; + const Index lastPaddedRight = m_outputStrides[i]; + + if (!isLeftPaddingCompileTimeZero(i) && lastIdx < lastPaddedLeft) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if (!isRightPaddingCompileTimeZero(i) && firstIdx >= firstPaddedRight && lastIdx < lastPaddedRight) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if ((isLeftPaddingCompileTimeZero(i) && isRightPaddingCompileTimeZero(i)) || (firstIdx >= lastPaddedLeft && lastIdx < firstPaddedRight)) { + // all the coefficient are between the 2 padding zones. + const Index idx = index / m_outputStrides[i+1]; + inputIndex += (idx - m_padding[i].first) * m_inputStrides[i]; + index -= idx * m_outputStrides[i+1]; + } + else { + // Every other case + return packetWithPossibleZero(initialIndex); + } + } + + const Index lastIdx = index + PacketSize - 1; + const Index firstIdx = index; + const Index lastPaddedLeft = m_padding[NumDims-1].first; + const Index firstPaddedRight = (m_dimensions[NumDims-1] - m_padding[NumDims-1].second); + const Index lastPaddedRight = m_outputStrides[NumDims-1]; + + if (!isLeftPaddingCompileTimeZero(NumDims-1) && lastIdx < lastPaddedLeft) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if (!isRightPaddingCompileTimeZero(NumDims-1) && firstIdx >= firstPaddedRight && lastIdx < lastPaddedRight) { + // all the coefficient are in the padding zone. + return internal::pset1(m_paddingValue); + } + else if ((isLeftPaddingCompileTimeZero(NumDims-1) && isRightPaddingCompileTimeZero(NumDims-1)) || (firstIdx >= lastPaddedLeft && lastIdx < firstPaddedRight)) { + // all the coefficient are between the 2 padding zones. + inputIndex += (index - m_padding[NumDims-1].first); + return m_impl.template packet(inputIndex); + } + // Every other case + return packetWithPossibleZero(initialIndex); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetWithPossibleZero(Index index) const + { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + Dimensions m_dimensions; + array m_outputStrides; + array m_inputStrides; + TensorEvaluator m_impl; + PaddingDimensions m_padding; + + Scalar m_paddingValue; + + const Device EIGEN_DEVICE_REF m_device; +}; + + + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_PADDING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPatch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPatch.h new file mode 100644 index 0000000000000000000000000000000000000000..61a6c984244e26ded56ac213bbb9c5711e08b0c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorPatch.h @@ -0,0 +1,284 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_PATCH_H +#define EIGEN_CXX11_TENSOR_TENSOR_PATCH_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorPatch + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor patch class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions + 1; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorPatchOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorPatchOp type; +}; + +} // end namespace internal + + + +template +class TensorPatchOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorPatchOp(const XprType& expr, const PatchDim& patch_dims) + : m_xpr(expr), m_patch_dims(patch_dims) {} + + EIGEN_DEVICE_FUNC + const PatchDim& patch_dims() const { return m_patch_dims; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const PatchDim m_patch_dims; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorPatchOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value + 1; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device) + { + Index num_patches = 1; + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + const PatchDim& patch_dims = op.patch_dims(); + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < NumDims-1; ++i) { + m_dimensions[i] = patch_dims[i]; + num_patches *= (input_dims[i] - patch_dims[i] + 1); + } + m_dimensions[NumDims-1] = num_patches; + + m_inputStrides[0] = 1; + m_patchStrides[0] = 1; + for (int i = 1; i < NumDims-1; ++i) { + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + m_patchStrides[i] = m_patchStrides[i-1] * (input_dims[i-1] - patch_dims[i-1] + 1); + } + m_outputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1]; + } + } else { + for (int i = 0; i < NumDims-1; ++i) { + m_dimensions[i+1] = patch_dims[i]; + num_patches *= (input_dims[i] - patch_dims[i] + 1); + } + m_dimensions[0] = num_patches; + + m_inputStrides[NumDims-2] = 1; + m_patchStrides[NumDims-2] = 1; + for (int i = NumDims-3; i >= 0; --i) { + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + m_patchStrides[i] = m_patchStrides[i+1] * (input_dims[i+1] - patch_dims[i+1] + 1); + } + m_outputStrides[NumDims-1] = 1; + for (int i = NumDims-2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i+1] * m_dimensions[i+1]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + Index output_stride_index = (static_cast(Layout) == static_cast(ColMajor)) ? NumDims - 1 : 0; + // Find the location of the first element of the patch. + Index patchIndex = index / m_outputStrides[output_stride_index]; + // Find the offset of the element wrt the location of the first element. + Index patchOffset = index - patchIndex * m_outputStrides[output_stride_index]; + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 2; i > 0; --i) { + const Index patchIdx = patchIndex / m_patchStrides[i]; + patchIndex -= patchIdx * m_patchStrides[i]; + const Index offsetIdx = patchOffset / m_outputStrides[i]; + patchOffset -= offsetIdx * m_outputStrides[i]; + inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i]; + } + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 2; ++i) { + const Index patchIdx = patchIndex / m_patchStrides[i]; + patchIndex -= patchIdx * m_patchStrides[i]; + const Index offsetIdx = patchOffset / m_outputStrides[i+1]; + patchOffset -= offsetIdx * m_outputStrides[i+1]; + inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i]; + } + } + inputIndex += (patchIndex + patchOffset); + return m_impl.coeff(inputIndex); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + Index output_stride_index = (static_cast(Layout) == static_cast(ColMajor)) ? NumDims - 1 : 0; + Index indices[2] = {index, index + PacketSize - 1}; + Index patchIndices[2] = {indices[0] / m_outputStrides[output_stride_index], + indices[1] / m_outputStrides[output_stride_index]}; + Index patchOffsets[2] = {indices[0] - patchIndices[0] * m_outputStrides[output_stride_index], + indices[1] - patchIndices[1] * m_outputStrides[output_stride_index]}; + + Index inputIndices[2] = {0, 0}; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 2; i > 0; --i) { + const Index patchIdx[2] = {patchIndices[0] / m_patchStrides[i], + patchIndices[1] / m_patchStrides[i]}; + patchIndices[0] -= patchIdx[0] * m_patchStrides[i]; + patchIndices[1] -= patchIdx[1] * m_patchStrides[i]; + + const Index offsetIdx[2] = {patchOffsets[0] / m_outputStrides[i], + patchOffsets[1] / m_outputStrides[i]}; + patchOffsets[0] -= offsetIdx[0] * m_outputStrides[i]; + patchOffsets[1] -= offsetIdx[1] * m_outputStrides[i]; + + inputIndices[0] += (patchIdx[0] + offsetIdx[0]) * m_inputStrides[i]; + inputIndices[1] += (patchIdx[1] + offsetIdx[1]) * m_inputStrides[i]; + } + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 2; ++i) { + const Index patchIdx[2] = {patchIndices[0] / m_patchStrides[i], + patchIndices[1] / m_patchStrides[i]}; + patchIndices[0] -= patchIdx[0] * m_patchStrides[i]; + patchIndices[1] -= patchIdx[1] * m_patchStrides[i]; + + const Index offsetIdx[2] = {patchOffsets[0] / m_outputStrides[i+1], + patchOffsets[1] / m_outputStrides[i+1]}; + patchOffsets[0] -= offsetIdx[0] * m_outputStrides[i+1]; + patchOffsets[1] -= offsetIdx[1] * m_outputStrides[i+1]; + + inputIndices[0] += (patchIdx[0] + offsetIdx[0]) * m_inputStrides[i]; + inputIndices[1] += (patchIdx[1] + offsetIdx[1]) * m_inputStrides[i]; + } + } + inputIndices[0] += (patchIndices[0] + patchOffsets[0]); + inputIndices[1] += (patchIndices[1] + patchOffsets[1]); + + if (inputIndices[1] - inputIndices[0] == PacketSize - 1) { + PacketReturnType rslt = m_impl.template packet(inputIndices[0]); + return rslt; + } + else { + EIGEN_ALIGN_MAX CoeffReturnType values[PacketSize]; + values[0] = m_impl.coeff(inputIndices[0]); + values[PacketSize-1] = m_impl.coeff(inputIndices[1]); + EIGEN_UNROLL_LOOP + for (int i = 1; i < PacketSize-1; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + const double compute_cost = NumDims * (TensorOpCost::DivCost() + + TensorOpCost::MulCost() + + 2 * TensorOpCost::AddCost()); + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + protected: + Dimensions m_dimensions; + array m_outputStrides; + array m_inputStrides; + array m_patchStrides; + + TensorEvaluator m_impl; + +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_PATCH_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRandom.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRandom.h new file mode 100644 index 0000000000000000000000000000000000000000..0de404704a824dbe1139f292554adbcfd7de46a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRandom.h @@ -0,0 +1,319 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Benoit Steiner +// Copyright (C) 2018 Mehdi Goli Codeplay Software Ltd. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H +#define EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE uint64_t get_random_seed() { +#if defined(EIGEN_GPU_COMPILE_PHASE) + // We don't support 3d kernels since we currently only use 1 and + // 2d kernels. + gpu_assert(threadIdx.z == 0); + return blockIdx.x * blockDim.x + threadIdx.x + + gridDim.x * blockDim.x * (blockIdx.y * blockDim.y + threadIdx.y); +#else + // Rely on Eigen's random implementation. + return random(); +#endif +} + +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE unsigned PCG_XSH_RS_generator(uint64_t* state, uint64_t stream) { + // TODO: Unify with the implementation in the non blocking thread pool. + uint64_t current = *state; + // Update the internal state + *state = current * 6364136223846793005ULL + (stream << 1 | 1); + // Generate the random output (using the PCG-XSH-RS scheme) + return static_cast((current ^ (current >> 22)) >> (22 + (current >> 61))); +} + +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE uint64_t PCG_XSH_RS_state(uint64_t seed) { + seed = seed ? seed : get_random_seed(); + return seed * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL; +} + +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +T RandomToTypeUniform(uint64_t* state, uint64_t stream) { + unsigned rnd = PCG_XSH_RS_generator(state, stream); + return static_cast(rnd); +} + + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +Eigen::half RandomToTypeUniform(uint64_t* state, uint64_t stream) { + // Generate 10 random bits for the mantissa, merge with exponent. + unsigned rnd = PCG_XSH_RS_generator(state, stream); + const uint16_t half_bits = static_cast(rnd & 0x3ffu) | (static_cast(15) << 10); + Eigen::half result = Eigen::numext::bit_cast(half_bits); + // Return the final result + return result - Eigen::half(1.0f); +} + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +Eigen::bfloat16 RandomToTypeUniform(uint64_t* state, uint64_t stream) { + + // Generate 7 random bits for the mantissa, merge with exponent. + unsigned rnd = PCG_XSH_RS_generator(state, stream); + const uint16_t half_bits = static_cast(rnd & 0x7fu) | (static_cast(127) << 7); + Eigen::bfloat16 result = Eigen::numext::bit_cast(half_bits); + // Return the final result + return result - Eigen::bfloat16(1.0f); +} + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float RandomToTypeUniform(uint64_t* state, uint64_t stream) { + typedef union { + uint32_t raw; + float fp; + } internal; + internal result; + // Generate 23 random bits for the mantissa mantissa + const unsigned rnd = PCG_XSH_RS_generator(state, stream); + result.raw = rnd & 0x7fffffu; + // Set the exponent + result.raw |= (static_cast(127) << 23); + // Return the final result + return result.fp - 1.0f; +} + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double RandomToTypeUniform(uint64_t* state, uint64_t stream) { + typedef union { + uint64_t raw; + double dp; + } internal; + internal result; + result.raw = 0; + // Generate 52 random bits for the mantissa + // First generate the upper 20 bits + unsigned rnd1 = PCG_XSH_RS_generator(state, stream) & 0xfffffu; + // The generate the lower 32 bits + unsigned rnd2 = PCG_XSH_RS_generator(state, stream); + result.raw = (static_cast(rnd1) << 32) | rnd2; + // Set the exponent + result.raw |= (static_cast(1023) << 52); + // Return the final result + return result.dp - 1.0; +} + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +std::complex RandomToTypeUniform >(uint64_t* state, uint64_t stream) { + return std::complex(RandomToTypeUniform(state, stream), + RandomToTypeUniform(state, stream)); +} +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +std::complex RandomToTypeUniform >(uint64_t* state, uint64_t stream) { + return std::complex(RandomToTypeUniform(state, stream), + RandomToTypeUniform(state, stream)); +} + +template class UniformRandomGenerator { + public: + static constexpr bool PacketAccess = true; + + // Uses the given "seed" if non-zero, otherwise uses a random seed. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE UniformRandomGenerator( + uint64_t seed = 0) { + m_state = PCG_XSH_RS_state(seed); + #ifdef EIGEN_USE_SYCL + // In SYCL it is not possible to build PCG_XSH_RS_state in one step. + // Therefore, we need two steps to initializate the m_state. + // IN SYCL, the constructor of the functor is s called on the CPU + // and we get the clock seed here from the CPU. However, This seed is + //the same for all the thread. As unlike CUDA, the thread.ID, BlockID, etc is not a global function. + // and only available on the Operator() function (which is called on the GPU). + // Thus for CUDA (((CLOCK + global_thread_id)* 6364136223846793005ULL) + 0xda3e39cb94b95bdbULL) is passed to each thread + // but for SYCL ((CLOCK * 6364136223846793005ULL) + 0xda3e39cb94b95bdbULL) is passed to each thread and each thread adds + // the (global_thread_id* 6364136223846793005ULL) for itself only once, in order to complete the construction + // similar to CUDA Therefore, the thread Id injection is not available at this stage. + //However when the operator() is called the thread ID will be available. So inside the opeator, + // we add the thrreadID, BlockId,... (which is equivalent of i) + //to the seed and construct the unique m_state per thead similar to cuda. + m_exec_once =false; + #endif + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE UniformRandomGenerator( + const UniformRandomGenerator& other) { + m_state = other.m_state; + #ifdef EIGEN_USE_SYCL + m_exec_once =other.m_exec_once; + #endif + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + T operator()(Index i) const { + #ifdef EIGEN_USE_SYCL + if(!m_exec_once) { + // This is the second stage of adding thread Id to the CPU clock seed and build unique seed per thread + // The (i * 6364136223846793005ULL) is the remaining part of the PCG_XSH_RS_state on the GPU side + m_state += (i * 6364136223846793005ULL); + m_exec_once =true; + } + #endif + T result = RandomToTypeUniform(&m_state, i); + return result; + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Packet packetOp(Index i) const { + const int packetSize = internal::unpacket_traits::size; + EIGEN_ALIGN_MAX T values[packetSize]; + #ifdef EIGEN_USE_SYCL + if(!m_exec_once) { + // This is the second stage of adding thread Id to the CPU clock seed and build unique seed per thread + m_state += (i * 6364136223846793005ULL); + m_exec_once =true; + } + #endif + EIGEN_UNROLL_LOOP + for (int j = 0; j < packetSize; ++j) { + values[j] = RandomToTypeUniform(&m_state, i); + } + return internal::pload(values); + } + + private: + mutable uint64_t m_state; + #ifdef EIGEN_USE_SYCL + mutable bool m_exec_once; + #endif +}; + +template +struct functor_traits > { + enum { + // Rough estimate for floating point, multiplied by ceil(sizeof(T) / sizeof(float)). + Cost = 12 * NumTraits::AddCost * + ((sizeof(Scalar) + sizeof(float) - 1) / sizeof(float)), + PacketAccess = UniformRandomGenerator::PacketAccess + }; +}; + + + +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +T RandomToTypeNormal(uint64_t* state, uint64_t stream) { + // Use the ratio of uniform method to generate numbers following a normal + // distribution. See for example Numerical Recipes chapter 7.3.9 for the + // details. + T u, v, q; + do { + u = RandomToTypeUniform(state, stream); + v = T(1.7156) * (RandomToTypeUniform(state, stream) - T(0.5)); + const T x = u - T(0.449871); + const T y = numext::abs(v) + T(0.386595); + q = x*x + y * (T(0.196)*y - T(0.25472)*x); + } while (q > T(0.27597) && + (q > T(0.27846) || v*v > T(-4) * numext::log(u) * u*u)); + + return v/u; +} + +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +std::complex RandomToTypeNormal >(uint64_t* state, uint64_t stream) { + return std::complex(RandomToTypeNormal(state, stream), + RandomToTypeNormal(state, stream)); +} +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +std::complex RandomToTypeNormal >(uint64_t* state, uint64_t stream) { + return std::complex(RandomToTypeNormal(state, stream), + RandomToTypeNormal(state, stream)); +} + + +template class NormalRandomGenerator { + public: + static constexpr bool PacketAccess = true; + + // Uses the given "seed" if non-zero, otherwise uses a random seed. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE NormalRandomGenerator(uint64_t seed = 0) { + m_state = PCG_XSH_RS_state(seed); + #ifdef EIGEN_USE_SYCL + // In SYCL it is not possible to build PCG_XSH_RS_state in one step. + // Therefore, we need two steps to initializate the m_state. + // IN SYCL, the constructor of the functor is s called on the CPU + // and we get the clock seed here from the CPU. However, This seed is + //the same for all the thread. As unlike CUDA, the thread.ID, BlockID, etc is not a global function. + // and only available on the Operator() function (which is called on the GPU). + // Therefore, the thread Id injection is not available at this stage. However when the operator() + //is called the thread ID will be available. So inside the operator, + // we add the thrreadID, BlockId,... (which is equivalent of i) + //to the seed and construct the unique m_state per thead similar to cuda. + m_exec_once =false; + #endif + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE NormalRandomGenerator( + const NormalRandomGenerator& other) { + m_state = other.m_state; +#ifdef EIGEN_USE_SYCL + m_exec_once=other.m_exec_once; +#endif + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + T operator()(Index i) const { + #ifdef EIGEN_USE_SYCL + if(!m_exec_once) { + // This is the second stage of adding thread Id to the CPU clock seed and build unique seed per thread + m_state += (i * 6364136223846793005ULL); + m_exec_once =true; + } + #endif + T result = RandomToTypeNormal(&m_state, i); + return result; + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Packet packetOp(Index i) const { + const int packetSize = internal::unpacket_traits::size; + EIGEN_ALIGN_MAX T values[packetSize]; + #ifdef EIGEN_USE_SYCL + if(!m_exec_once) { + // This is the second stage of adding thread Id to the CPU clock seed and build unique seed per thread + m_state += (i * 6364136223846793005ULL); + m_exec_once =true; + } + #endif + EIGEN_UNROLL_LOOP + for (int j = 0; j < packetSize; ++j) { + values[j] = RandomToTypeNormal(&m_state, i); + } + return internal::pload(values); + } + + private: + mutable uint64_t m_state; + #ifdef EIGEN_USE_SYCL + mutable bool m_exec_once; + #endif +}; + + +template +struct functor_traits > { + enum { + // On average, we need to generate about 3 random numbers + // 15 mul, 8 add, 1.5 logs + Cost = 3 * functor_traits >::Cost + + 15 * NumTraits::AddCost + 8 * NumTraits::AddCost + + 3 * functor_traits >::Cost / 2, + PacketAccess = NormalRandomGenerator::PacketAccess + }; +}; + + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_RANDOM_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h new file mode 100644 index 0000000000000000000000000000000000000000..8cd78672267c0ada610b10eb17767661f9e98310 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h @@ -0,0 +1,1034 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// Copyright (C) 2016 Mehdi Goli, Codeplay Software Ltd +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_H +#define EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_H + +// clang is incompatible with the CUDA syntax wrt making a kernel a class friend, +// so we'll use a macro to make clang happy. +#ifndef KERNEL_FRIEND +#if defined(__clang__) && (defined(__CUDA__) || defined(__HIP__)) +#define KERNEL_FRIEND friend __global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 +#else +#define KERNEL_FRIEND friend +#endif +#endif + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + + +/** \class TensorReduction + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor reduction class. + * + */ + +namespace internal { + template class MakePointer_ > + struct traits > + : traits +{ + typedef traits XprTraits; + typedef typename XprTraits::Scalar Scalar; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + static constexpr int NumDimensions = XprTraits::NumDimensions - array_size::value; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; + + template struct MakePointer { + // Intermediate typedef to workaround MSVC issue. + typedef MakePointer_ MakePointerT; + typedef typename MakePointerT::Type Type; + }; +}; + +template class MakePointer_> +struct eval, Eigen::Dense> +{ + typedef const TensorReductionOp& type; +}; + +template class MakePointer_> +struct nested, 1, typename eval >::type> +{ + typedef TensorReductionOp type; +}; + + +template struct DimInitializer { + template EIGEN_DEVICE_FUNC + static void run(const InputDims& input_dims, + const array::value>& reduced, + OutputDims* output_dims, ReducedDims* reduced_dims) { + const int NumInputDims = internal::array_size::value; + int outputIndex = 0; + int reduceIndex = 0; + for (int i = 0; i < NumInputDims; ++i) { + if (reduced[i]) { + (*reduced_dims)[reduceIndex] = input_dims[i]; + ++reduceIndex; + } else { + (*output_dims)[outputIndex] = input_dims[i]; + ++outputIndex; + } + } + } +}; + +template <> struct DimInitializer > { + template EIGEN_DEVICE_FUNC + static void run(const InputDims& input_dims, const array&, + Sizes<>*, array* reduced_dims) { + const int NumInputDims = internal::array_size::value; + for (int i = 0; i < NumInputDims; ++i) { + (*reduced_dims)[i] = input_dims[i]; + } + } +}; + + +template +struct are_inner_most_dims { + static const bool value = false; +}; +template +struct preserve_inner_most_dims { + static const bool value = false; +}; + +template +struct are_inner_most_dims{ + static const bool tmp1 = indices_statically_known_to_increase(); + static const bool tmp2 = index_statically_eq(0, 0); + static const bool tmp3 = index_statically_eq(array_size::value-1, array_size::value-1); + static const bool value = tmp1 & tmp2 & tmp3; +}; +template +struct are_inner_most_dims{ + static const bool tmp1 = indices_statically_known_to_increase(); + static const bool tmp2 = index_statically_eq(0, NumTensorDims - array_size::value); + static const bool tmp3 = index_statically_eq(array_size::value - 1, NumTensorDims - 1); + static const bool value = tmp1 & tmp2 & tmp3; + +}; +template +struct preserve_inner_most_dims{ + static const bool tmp1 = indices_statically_known_to_increase(); + static const bool tmp2 = index_statically_gt(0, 0); + static const bool value = tmp1 & tmp2; + +}; +template +struct preserve_inner_most_dims{ + static const bool tmp1 = indices_statically_known_to_increase(); + static const bool tmp2 = index_statically_lt(array_size::value - 1, NumTensorDims - 1); + static const bool value = tmp1 & tmp2; +}; + + +template +struct GenericDimReducer { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex, Op& reducer, typename Self::CoeffReturnType* accum) { + EIGEN_STATIC_ASSERT((DimIndex > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + for (int j = 0; j < self.m_reducedDims[DimIndex]; ++j) { + const typename Self::Index input = firstIndex + j * self.m_reducedStrides[DimIndex]; + GenericDimReducer::reduce(self, input, reducer, accum); + } + } +}; +template +struct GenericDimReducer<0, Self, Op> { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex, Op& reducer, typename Self::CoeffReturnType* accum) { + for (int j = 0; j < self.m_reducedDims[0]; ++j) { + const typename Self::Index input = firstIndex + j * self.m_reducedStrides[0]; + reducer.reduce(self.m_impl.coeff(input), accum); + } + } +}; +template +struct GenericDimReducer<-1, Self, Op> { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index index, Op& reducer, typename Self::CoeffReturnType* accum) { + reducer.reduce(self.m_impl.coeff(index), accum); + } +}; + +template +struct InnerMostDimReducer { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer) { + typename Self::CoeffReturnType accum = reducer.initialize(); + for (typename Self::Index j = 0; j < numValuesToReduce; ++j) { + reducer.reduce(self.m_impl.coeff(firstIndex + j), &accum); + } + return reducer.finalize(accum); + } +}; + +template +struct InnerMostDimReducer { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer0) { + using Index = typename Self::Index; + constexpr Index packetSize = internal::unpacket_traits::size; + Index start = 0; + typename Self::PacketReturnType paccum0 = reducer0.template initializePacket(); + if (!Self::ReducerTraits::IsStateful && numValuesToReduce >= 4*packetSize) { + const Index VectorizedSize4 = (numValuesToReduce / (4*packetSize)) * (4*packetSize); + typename Self::PacketReturnType paccum1 = reducer0.template initializePacket(); + typename Self::PacketReturnType paccum2 = reducer0.template initializePacket(); + typename Self::PacketReturnType paccum3 = reducer0.template initializePacket(); + const Index offset0 = firstIndex; + const Index offset1 = firstIndex + packetSize; + const Index offset2 = firstIndex + 2*packetSize; + const Index offset3 = firstIndex + 3*packetSize; + for (Index j = 0; j < VectorizedSize4; j += 4*packetSize) { + reducer0.reducePacket(self.m_impl.template packet(offset0 + j), &paccum0); + reducer0.reducePacket(self.m_impl.template packet(offset1 + j), &paccum1); + reducer0.reducePacket(self.m_impl.template packet(offset2 + j), &paccum2); + reducer0.reducePacket(self.m_impl.template packet(offset3 + j), &paccum3); + } + reducer0.reducePacket(paccum1, &paccum0); + reducer0.reducePacket(paccum2, &paccum0); + reducer0.reducePacket(paccum3, &paccum0); + start = VectorizedSize4; + } + if (start <= (numValuesToReduce - packetSize)) { + const Index VectorizedSize = (numValuesToReduce / packetSize) * packetSize; + for (Index j = start; j < VectorizedSize; j += packetSize) { + reducer0.reducePacket(self.m_impl.template packet(firstIndex + j), &paccum0); + } + start = VectorizedSize; + } + typename Self::CoeffReturnType accum = reducer0.initialize(); + for (Index j = start; j < numValuesToReduce; ++j) { + reducer0.reduce(self.m_impl.coeff(firstIndex + j), &accum); + } + return reducer0.finalizeBoth(accum, paccum0); + } +}; + + +#if !defined(EIGEN_HIPCC) + +// The following implements tree-based reduction, which improves the accuracy +// of sum and mean reductions, since each of the n inputs only participates in +// O(log n) additions. +template +EIGEN_DEVICE_FUNC inline Index LeafSize() { return 1024; } +template <> +EIGEN_DEVICE_FUNC inline Index LeafSize() { return 200; } +template <> +EIGEN_DEVICE_FUNC inline Index LeafSize() { return 128; } + +template +struct InnerMostDimReducer { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType + reduce(const Self& self, typename Self::Index firstIndex, + typename Self::Index numValuesToReduce, Op& reducer) { + const Index kLeafSize = LeafSize(); + typename Self::CoeffReturnType accum = reducer.initialize(); + if (numValuesToReduce > kLeafSize) { + const typename Self::Index half = numValuesToReduce / 2; + // Recursively reduce the two halves. + reducer.reduce(reduce(self, firstIndex, half, reducer), &accum); + reducer.reduce( + reduce(self, firstIndex + half, numValuesToReduce - half, reducer), + &accum); + return reducer.finalize(accum); + } else { + return InnerMostDimReducer::reduce(self, firstIndex, numValuesToReduce, reducer); + } + } +}; + +template +struct InnerMostDimReducer { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType + reduce(const Self& self, typename Self::Index firstIndex, + typename Self::Index numValuesToReduce, Op& reducer) { + const Index kLeafSize = LeafSize(); + const typename Self::Index packetSize = + internal::unpacket_traits::size; + typename Self::CoeffReturnType accum = reducer.initialize(); + if (numValuesToReduce > packetSize * kLeafSize) { + // Make sure the split point is aligned on a packet boundary. + const typename Self::Index split = + packetSize * + divup(firstIndex + divup(numValuesToReduce, typename Self::Index(2)), + packetSize); + const typename Self::Index num_left = + numext::mini(split - firstIndex, numValuesToReduce); + reducer.reduce(reduce(self, firstIndex, num_left, reducer), &accum); + if (num_left < numValuesToReduce) { + reducer.reduce( + reduce(self, split, numValuesToReduce - num_left, reducer), &accum); + } + return reducer.finalize(accum); + } else { + return InnerMostDimReducer::reduce(self, firstIndex, numValuesToReduce, reducer); + } + } +}; +#endif + +template +struct InnerMostDimPreserver { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self&, typename Self::Index, Op&, typename Self::PacketReturnType*) { + eigen_assert(false && "should never be called"); + } +}; + +template +struct InnerMostDimPreserver { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex, Op& reducer, typename Self::PacketReturnType* accum) { + EIGEN_STATIC_ASSERT((DimIndex > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + for (typename Self::Index j = 0; j < self.m_reducedDims[DimIndex]; ++j) { + const typename Self::Index input = firstIndex + j * self.m_reducedStrides[DimIndex]; + InnerMostDimPreserver::reduce(self, input, reducer, accum); + } + } +}; + +template +struct InnerMostDimPreserver<0, Self, Op, true> { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex, Op& reducer0, typename Self::PacketReturnType* accum0) { + using Index = typename Self::Index; + const Index stride = self.m_reducedStrides[0]; + const Index size = self.m_reducedDims[0]; + if (!Self::ReducerTraits::IsStateful && size >= 16) { + const Index unrolled_size4 = (size / 4) * 4; + typename Self::PacketReturnType accum1 = reducer0.template initializePacket(); + typename Self::PacketReturnType accum2 = reducer0.template initializePacket(); + typename Self::PacketReturnType accum3 = reducer0.template initializePacket(); + for (Index j = 0; j < unrolled_size4; j += 4) { + const Index input0 = firstIndex + j * stride; + reducer0.reducePacket(self.m_impl.template packet(input0), accum0); + const Index input1 = firstIndex + (j+1) * stride; + reducer0.reducePacket(self.m_impl.template packet(input1), &accum1); + const Index input2 = firstIndex + (j+2) * stride; + reducer0.reducePacket(self.m_impl.template packet(input2), &accum2); + const Index input3 = firstIndex + (j+3) * stride; + reducer0.reducePacket(self.m_impl.template packet(input3), &accum3); + } + reducer0.reducePacket(accum1, accum0); + reducer0.reducePacket(accum2, accum0); + reducer0.reducePacket(accum3, accum0); + for (Index j = unrolled_size4; j < size; ++j) { + Index input = firstIndex + j * stride; + reducer0.reducePacket(self.m_impl.template packet(input), accum0); + } + } else { + for (Index j = 0; j < size; ++j) { + Index input = firstIndex + j * stride; + reducer0.reducePacket(self.m_impl.template packet(input), accum0); + } + } + } +}; +template +struct InnerMostDimPreserver<-1, Self, Op, true> { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self&, typename Self::Index, Op&, typename Self::PacketReturnType*) { + eigen_assert(false && "should never be called"); + } +}; + +// Default full reducer +template +struct FullReducer { + static constexpr bool HasOptimizedImplementation = false; + + static EIGEN_DEVICE_FUNC void run(const Self& self, Op& reducer, const Device&, typename Self::EvaluatorPointerType output) { + const typename Self::Index num_coeffs = array_prod(self.m_impl.dimensions()); + *output = InnerMostDimReducer::reduce(self, 0, num_coeffs, reducer); + } +}; + + +#ifdef EIGEN_USE_THREADS +// Multithreaded full reducers +template +struct FullReducerShard { + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void run(const Self& self, typename Self::Index firstIndex, + typename Self::Index numValuesToReduce, Op& reducer, + typename Self::CoeffReturnType* output) { + *output = InnerMostDimReducer::reduce( + self, firstIndex, numValuesToReduce, reducer); + } +}; + +// Multithreaded full reducer +template +struct FullReducer { + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful; + static constexpr Index PacketSize = + unpacket_traits::size; + + // launch one reducer per thread and accumulate the result. + static void run(const Self& self, Op& reducer, const ThreadPoolDevice& device, + typename Self::CoeffReturnType* output) { + typedef typename Self::Index Index; + const Index num_coeffs = array_prod(self.m_impl.dimensions()); + if (num_coeffs == 0) { + *output = reducer.finalize(reducer.initialize()); + return; + } + const TensorOpCost cost = + self.m_impl.costPerCoeff(Vectorizable) + + TensorOpCost(0, 0, internal::functor_traits::Cost, Vectorizable, + PacketSize); + const Index num_threads = TensorCostModel::numThreads( + num_coeffs, cost, device.numThreads()); + if (num_threads == 1) { + *output = + InnerMostDimReducer::reduce(self, 0, num_coeffs, reducer); + return; + } + const Index blocksize = num_coeffs / num_threads; + const Index numblocks = blocksize > 0 ? num_coeffs / blocksize : 0; + eigen_assert(num_coeffs >= numblocks * blocksize); + + Barrier barrier(internal::convert_index(numblocks)); + MaxSizeVector shards(numblocks, reducer.initialize()); + for (Index i = 0; i < numblocks; ++i) { + device.enqueue_with_barrier(&barrier, &FullReducerShard::run, + self, i * blocksize, blocksize, reducer, + &shards[i]); + } + typename Self::CoeffReturnType finalShard; + if (numblocks * blocksize < num_coeffs) { + finalShard = InnerMostDimReducer::reduce( + self, numblocks * blocksize, num_coeffs - numblocks * blocksize, + reducer); + } else { + finalShard = reducer.initialize(); + } + barrier.Wait(); + + for (Index i = 0; i < numblocks; ++i) { + reducer.reduce(shards[i], &finalShard); + } + *output = reducer.finalize(finalShard); + } +}; + +#endif + + +// Default inner reducer +template +struct InnerReducer { + static constexpr bool HasOptimizedImplementation = false; + + EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*, typename Self::Index, typename Self::Index) { + eigen_assert(false && "Not implemented"); + return true; + } +}; + +// Default outer reducer +template +struct OuterReducer { + static constexpr bool HasOptimizedImplementation = false; + + EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*, typename Self::Index, typename Self::Index) { + eigen_assert(false && "Not implemented"); + return true; + } +}; + +#ifdef EIGEN_USE_SYCL +// Default Generic reducer +template +struct GenericReducer { + static constexpr bool HasOptimizedImplementation = false; + + EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*, typename Self::Index, typename Self::Index) { + eigen_assert(false && "Not implemented"); + return true; + } +}; +#endif + +#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC)) +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernel(R, const S, I_, typename S::CoeffReturnType*, unsigned int*); + + +#if defined(EIGEN_HAS_GPU_FP16) +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionInitFullReduxKernelHalfFloat(R, const S, I_, internal::packet_traits::type*); +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernelHalfFloat(R, const S, I_, half*, internal::packet_traits::type*); +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernelHalfFloat(R, const S, I_, I_, half*); + +#endif + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*); + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void OuterReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*); +#endif + +/** + * For SYCL, the return type of the reduction is deduced from the initialize method of the given Op. + * This allows the reduction to have a different type for the accumulator than the input data type. + * If this is the case, the functor needs to have two reduce method: one for reducing an element of the input + * with the accumulator and the other for reducing two accumulators. + * Such a reducer can be useful for instance when the accumulator is a boolean or a bitset that checks for + * some properties of the input. + */ +template +struct ReductionReturnType { +#if defined(EIGEN_USE_SYCL) + typedef std::remove_const_t().initialize())> type; +#else + typedef std::remove_const_t type; +#endif +}; + +} // end namespace internal + + +template class MakePointer_> +class TensorReductionOp : public TensorBase, ReadOnlyAccessors> { + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef std::remove_const_t CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorReductionOp(const XprType& expr, const Dims& dims) : m_expr(expr), m_dims(dims) + { } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + TensorReductionOp(const XprType& expr, const Dims& dims, const Op& reducer) : m_expr(expr), m_dims(dims), m_reducer(reducer) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const XprType& expression() const { return m_expr; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Dims& dims() const { return m_dims; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Op& reducer() const { return m_reducer; } + + protected: + typename XprType::Nested m_expr; + const Dims m_dims; + const Op m_reducer; +}; + +template +struct TensorReductionEvaluatorBase; + +// Eval as rvalue +template class MakePointer_, typename Device> +struct TensorReductionEvaluatorBase, Device> +{ + typedef internal::reducer_traits ReducerTraits; + typedef Dims ReducedDims; + typedef TensorReductionOp XprType; + typedef typename XprType::Index Index; + typedef ArgType ChildType; + typedef typename TensorEvaluator::Dimensions InputDimensions; + static constexpr int NumInputDims = internal::array_size::value; + static constexpr int NumReducedDims = internal::array_size::value; + static constexpr int NumOutputDims = NumInputDims - NumReducedDims; + typedef std::conditional_t, DSizes > Dimensions; + typedef typename XprType::Scalar Scalar; + typedef TensorReductionEvaluatorBase, Device> Self; + static constexpr bool InputPacketAccess = TensorEvaluator::PacketAccess; + typedef typename internal::ReductionReturnType::type CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr Index PacketSize = PacketType::size; + + typedef typename Eigen::internal::traits::PointerType TensorPointerType; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + // Subset of strides of the input tensor for the non-reduced dimensions. + // Indexed by output dimensions. + static constexpr int NumPreservedStrides = max_n_1::size; + + // For full reductions +#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC)) + static constexpr bool RunningOnGPU = internal::is_same::value; + static constexpr bool RunningOnSycl = false; +#elif defined(EIGEN_USE_SYCL) +static constexpr bool RunningOnSycl = internal::is_same, Eigen::SyclDevice>::value; +static constexpr bool RunningOnGPU = false; +#else + static constexpr bool RunningOnGPU = false; + static constexpr bool RunningOnSycl = false; +#endif + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = Self::InputPacketAccess && ReducerTraits::PacketAccess, + BlockAccess = false, + PreferBlockAccess = true, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + static constexpr bool ReducingInnerMostDims = internal::are_inner_most_dims::value; + static constexpr bool PreservingInnerMostDims = internal::preserve_inner_most_dims::value; + static constexpr bool RunningFullReduction = (NumOutputDims==0); + + EIGEN_STRONG_INLINE TensorReductionEvaluatorBase(const XprType& op, const Device& device) + : m_impl(op.expression(), device), + m_reducer(op.reducer()), + m_result(NULL), + m_device(device) { + EIGEN_STATIC_ASSERT((NumInputDims >= NumReducedDims), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT((!ReducingInnerMostDims | !PreservingInnerMostDims | (NumReducedDims == NumInputDims)), + YOU_MADE_A_PROGRAMMING_MISTAKE); + + // Build the bitmap indicating if an input dimension is reduced or not. + for (int i = 0; i < NumInputDims; ++i) { + m_reduced[i] = false; + } + for (int i = 0; i < NumReducedDims; ++i) { + eigen_assert(op.dims()[i] >= 0); + eigen_assert(op.dims()[i] < NumInputDims); + m_reduced[op.dims()[i]] = true; + } + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + internal::DimInitializer::run(input_dims, m_reduced, &m_dimensions, &m_reducedDims); + + // Precompute output strides. + if (NumOutputDims > 0) { + if (static_cast(Layout) == static_cast(ColMajor)) { + m_outputStrides[0] = 1; + for (int i = 1; i < NumOutputDims; ++i) { + m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i]); + } + } else { + m_outputStrides[static_cast(NumOutputDims - 1)] = 1; + for (int i = NumOutputDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor(m_outputStrides[i]); + } + } + } + + // Precompute input strides. + if (NumInputDims > 0) { + array input_strides; + if (static_cast(Layout) == static_cast(ColMajor)) { + input_strides[0] = 1; + for (int i = 1; i < NumInputDims; ++i) { + input_strides[i] = input_strides[i-1] * input_dims[i-1]; + } + } else { + input_strides.back() = 1; + for (int i = NumInputDims - 2; i >= 0; --i) { + input_strides[i] = input_strides[i + 1] * input_dims[i + 1]; + } + } + + int outputIndex = 0; + int reduceIndex = 0; + for (int i = 0; i < NumInputDims; ++i) { + if (m_reduced[i]) { + m_reducedStrides[reduceIndex] = input_strides[i]; + ++reduceIndex; + } else { + m_preservedStrides[outputIndex] = input_strides[i]; + m_output_to_input_dim_map[outputIndex] = i; + ++outputIndex; + } + } + } + + // Special case for full reductions + if (NumOutputDims == 0) { + m_preservedStrides[0] = internal::array_prod(input_dims); + } + + m_numValuesToReduce = + NumOutputDims == 0 + ? internal::array_prod(input_dims) + : (static_cast(Layout) == static_cast(ColMajor)) + ? m_preservedStrides[0] + : m_preservedStrides[static_cast(NumOutputDims - 1)]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE + bool evalSubExprsIfNeededCommon(EvaluatorPointerType data) { + // Use the FullReducer if possible. + if ((RunningFullReduction && RunningOnSycl) ||(RunningFullReduction && + internal::FullReducer::HasOptimizedImplementation && + ((RunningOnGPU && (m_device.majorDeviceVersion() >= 3)) || + !RunningOnGPU))) { + bool need_assign = false; + if (!data) { + m_result = static_cast(m_device.get((CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType)))); + data = m_result; + need_assign = true; + } + Op reducer(m_reducer); + internal::FullReducer::run(*this, reducer, m_device, data); + return need_assign; + } + + // Attempt to use an optimized reduction. + else if ((RunningOnGPU && (m_device.majorDeviceVersion() >= 3)) || (RunningOnSycl)) { + bool reducing_inner_dims = true; + for (int i = 0; i < NumReducedDims; ++i) { + if (static_cast(Layout) == static_cast(ColMajor)) { + reducing_inner_dims &= m_reduced[i]; + } else { + reducing_inner_dims &= m_reduced[NumInputDims - 1 - i]; + } + } + if (internal::InnerReducer::HasOptimizedImplementation && + (reducing_inner_dims || ReducingInnerMostDims)) { + const Index num_values_to_reduce = internal::array_prod(m_reducedDims); + const Index num_coeffs_to_preserve = internal::array_prod(m_dimensions); + if (!data) { + if ((num_coeffs_to_preserve < 1024 && num_values_to_reduce > num_coeffs_to_preserve && num_values_to_reduce > 128) || (RunningOnSycl)) { + data = static_cast(m_device.get((CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve))); + m_result = data; + } + else { + return true; + } + } + Op reducer(m_reducer); + // For SYCL this if always return false + if (internal::InnerReducer::run(*this, reducer, m_device, data, num_values_to_reduce, num_coeffs_to_preserve)) { + if (m_result) { + m_device.deallocate_temp(m_result); + m_result = NULL; + } + return true; + } else { + return (m_result != NULL); + } + } + + bool preserving_inner_dims = true; + for (int i = 0; i < NumReducedDims; ++i) { + if (static_cast(Layout) == static_cast(ColMajor)) { + preserving_inner_dims &= m_reduced[NumInputDims - 1 - i]; + } else { + preserving_inner_dims &= m_reduced[i]; + } + } + if (internal::OuterReducer::HasOptimizedImplementation && + preserving_inner_dims) { + const Index num_values_to_reduce = internal::array_prod(m_reducedDims); + const Index num_coeffs_to_preserve = internal::array_prod(m_dimensions); + if (!data) { + if ((num_coeffs_to_preserve < 1024 && num_values_to_reduce > num_coeffs_to_preserve && num_values_to_reduce > 32) || (RunningOnSycl)) { + data = static_cast(m_device.get((CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve))); + m_result = data; + } + else { + return true; + } + } + Op reducer(m_reducer); + // For SYCL this if always return false + if (internal::OuterReducer::run(*this, reducer, m_device, data, num_values_to_reduce, num_coeffs_to_preserve)) { + if (m_result) { + m_device.deallocate_temp(m_result); + m_result = NULL; + } + return true; + } else { + return (m_result != NULL); + } + } + #if defined(EIGEN_USE_SYCL) + // If there is no Optimised version for SYCL, the reduction expression + // must break into two subexpression and use the SYCL generic Reducer on the device. + if(RunningOnSycl) { + const Index num_values_to_reduce = internal::array_prod(m_reducedDims); + const Index num_coeffs_to_preserve = internal::array_prod(m_dimensions); + if (!data) { + data = static_cast(m_device.get((CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve))); + m_result = data; + } + Op reducer(m_reducer); + internal::GenericReducer::run(*this, reducer, m_device, data, num_values_to_reduce, num_coeffs_to_preserve); + return (m_result != NULL); + } + #endif + } + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE + void + evalSubExprsIfNeededAsync(EvaluatorPointerType data, + EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(NULL, [this, data, done](bool) { + done(evalSubExprsIfNeededCommon(data)); + }); + } +#endif + + EIGEN_STRONG_INLINE + bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + m_impl.evalSubExprsIfNeeded(NULL); + return evalSubExprsIfNeededCommon(data); + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + if (m_result) { + m_device.deallocate_temp(m_result); + m_result = NULL; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + if (( RunningFullReduction || RunningOnGPU) && m_result ) { + return *(m_result + index); + } + Op reducer(m_reducer); + if (ReducingInnerMostDims || RunningFullReduction) { + const Index num_values_to_reduce = + (static_cast(Layout) == static_cast(ColMajor)) ? m_preservedStrides[0] : m_preservedStrides[NumPreservedStrides - 1]; + return internal::InnerMostDimReducer::reduce(*this, firstInput(index), + num_values_to_reduce, reducer); + } else { + typename Self::CoeffReturnType accum = reducer.initialize(); + internal::GenericDimReducer::reduce(*this, firstInput(index), reducer, &accum); + return reducer.finalize(accum); + } + } + + // TODO(bsteiner): provide a more efficient implementation. + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index + PacketSize - 1 < Index(internal::array_prod(dimensions()))); + + if (RunningOnGPU && m_result) { + return internal::pload(m_result + index); + } + + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + if (ReducingInnerMostDims) { + const Index num_values_to_reduce = + (static_cast(Layout) == static_cast(ColMajor)) ? m_preservedStrides[0] : m_preservedStrides[NumPreservedStrides - 1]; + const Index firstIndex = firstInput(index); + for (Index i = 0; i < PacketSize; ++i) { + Op reducer(m_reducer); + values[i] = internal::InnerMostDimReducer::reduce(*this, firstIndex + i * num_values_to_reduce, + num_values_to_reduce, reducer); + } + } else if (PreservingInnerMostDims) { + const Index firstIndex = firstInput(index); + const int innermost_dim = (static_cast(Layout) == static_cast(ColMajor)) ? 0 : NumOutputDims - 1; + // TBD: extend this the the n innermost dimensions that we preserve. + if (((firstIndex % m_dimensions[innermost_dim]) + PacketSize - 1) < m_dimensions[innermost_dim]) { + Op reducer(m_reducer); + typename Self::PacketReturnType accum = reducer.template initializePacket(); + internal::InnerMostDimPreserver::reduce(*this, firstIndex, reducer, &accum); + return reducer.finalizePacket(accum); + } else { + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index + i); + } + } + } else { + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index + i); + } + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + // Must be called after evalSubExprsIfNeeded(). + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + if (RunningFullReduction && m_result) { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize); + } else { + const Index num_values_to_reduce = internal::array_prod(m_reducedDims); + const double compute_cost = num_values_to_reduce * internal::functor_traits::Cost; + return m_impl.costPerCoeff(vectorized) * num_values_to_reduce + + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_result; } + EIGEN_DEVICE_FUNC const TensorEvaluator& impl() const { return m_impl; } + EIGEN_DEVICE_FUNC const Device& device() const { return m_device; } + + private: + template friend struct internal::GenericDimReducer; + template friend struct internal::InnerMostDimReducer; + template friend struct internal::InnerMostDimPreserver; + template friend struct internal::FullReducer; +#ifdef EIGEN_USE_THREADS + template friend struct internal::FullReducerShard; +#endif +#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC)) + template KERNEL_FRIEND void internal::FullReductionKernel(R, const S, I_, typename S::CoeffReturnType*, unsigned int*); +#if defined(EIGEN_HAS_GPU_FP16) + template KERNEL_FRIEND void internal::ReductionInitFullReduxKernelHalfFloat(R, const S, I_, internal::packet_traits::type*); + template KERNEL_FRIEND void internal::FullReductionKernelHalfFloat(R, const S, I_, half*, internal::packet_traits::type*); + template KERNEL_FRIEND void internal::InnerReductionKernelHalfFloat(R, const S, I_, I_, half*); +#endif + template KERNEL_FRIEND void internal::InnerReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*); + + template KERNEL_FRIEND void internal::OuterReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*); +#endif + +#if defined(EIGEN_USE_SYCL) + template < typename Evaluator_, typename Op__> friend class TensorSycl::internal::GenericNondeterministicReducer; + // SYCL need the Generic reducer for the case the recution algorithm is neither inner, outer, and full reducer + template friend struct internal::GenericReducer; +#endif + + + template friend struct internal::InnerReducer; + + struct BlockIteratorState { + Index input_dim; + Index output_size; + Index output_count; + }; + + // Returns the Index in the input tensor of the first value that needs to be + // used to compute the reduction at output index "index". + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index firstInput(Index index) const { + if (ReducingInnerMostDims) { + if (static_cast(Layout) == static_cast(ColMajor)) { + return index * m_preservedStrides[0]; + } else { + return index * m_preservedStrides[NumPreservedStrides - 1]; + } + } + // TBD: optimize the case where we preserve the innermost dimensions. + Index startInput = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumOutputDims - 1; i > 0; --i) { + // This is index_i in the output tensor. + const Index idx = index / m_outputStrides[i]; + startInput += idx * m_preservedStrides[i]; + index -= idx * m_outputStrides[i]; + } + if (PreservingInnerMostDims) { + eigen_assert(m_preservedStrides[0] == 1); + startInput += index; + } else { + startInput += index * m_preservedStrides[0]; + } + } else { + for (int i = 0; i < NumOutputDims - 1; ++i) { + // This is index_i in the output tensor. + const Index idx = index / m_outputStrides[i]; + startInput += idx * m_preservedStrides[i]; + index -= idx * m_outputStrides[i]; + } + if (PreservingInnerMostDims) { + eigen_assert(m_preservedStrides[NumPreservedStrides - 1] == 1); + startInput += index; + } else { + startInput += index * m_preservedStrides[NumPreservedStrides - 1]; + } + } + return startInput; + } + + // Bitmap indicating if an input dimension is reduced or not. + array m_reduced; + // Dimensions of the output of the operation. + Dimensions m_dimensions; + // Precomputed strides for the output tensor. + array m_outputStrides; + array, NumOutputDims> m_fastOutputStrides; + array m_preservedStrides; + // Map from output to input dimension index. + array m_output_to_input_dim_map; + // How many values go into each reduction + Index m_numValuesToReduce; + + // Subset of strides of the input tensor for the reduced dimensions. + // Indexed by reduced dimensions. + array m_reducedStrides; + // Size of the input dimensions that are reduced. + // Indexed by reduced dimensions. + array m_reducedDims; + + // Evaluator for the input expression. + TensorEvaluator m_impl; + + // Operation to apply for computing the reduction. + Op m_reducer; + + EvaluatorPointerType m_result; + + const Device EIGEN_DEVICE_REF m_device; +}; + +template class MakePointer_, typename Device> +struct TensorEvaluator, Device> +: public TensorReductionEvaluatorBase, Device> { + typedef TensorReductionEvaluatorBase, Device> Base; + EIGEN_STRONG_INLINE TensorEvaluator(const typename Base::XprType& op, const Device& device) : Base(op, device){} +}; + + +template class MakePointer_> +struct TensorEvaluator, Eigen::SyclDevice> +: public TensorReductionEvaluatorBase, Eigen::SyclDevice> { + + typedef TensorReductionEvaluatorBase, Eigen::SyclDevice> Base; + EIGEN_STRONG_INLINE TensorEvaluator(const typename Base::XprType& op, const Eigen::SyclDevice& device) : Base(op, device){} + // The coeff function in the base the recursive method which is not an standard layout and cannot be used in the SYCL kernel + //Therefore the coeff function should be overridden by for SYCL kernel + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Base::CoeffReturnType coeff(typename Base::Index index) const { + return *(this->data() + index); + } + // The packet function in the base the recursive method which is not an standard layout and cannot be used in the SYCL kernel + //Therefore the packet function should be overridden by for SYCL kernel + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Base::PacketReturnType packet(typename Base::Index index) const { + return internal::pload(this->data() + index); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionGpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionGpu.h new file mode 100644 index 0000000000000000000000000000000000000000..600c2b0ff764efc3d52dcc6707539f2a5ad74fed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionGpu.h @@ -0,0 +1,985 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_GPU_H +#define EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_GPU_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + + +#if defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC) +// Full reducers for GPU, don't vectorize for now + +// Reducer function that enables multiple gpu thread to safely accumulate at the same +// output address. It basically reads the current value of the output variable, and +// attempts to update it with the new value. If in the meantime another gpu thread +// updated the content of the output address it will try again. +template +__device__ EIGEN_ALWAYS_INLINE void atomicReduce(T* output, T accum, R& reducer) { +#if (defined(EIGEN_HIP_DEVICE_COMPILE) && defined(__HIP_ARCH_HAS_WARP_SHUFFLE__)) || (EIGEN_CUDA_ARCH >= 300) + if (sizeof(T) == 4) + { + unsigned int oldval = *reinterpret_cast(output); + unsigned int newval = oldval; + reducer.reduce(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + unsigned int readback; + while ((readback = atomicCAS((unsigned int*)output, oldval, newval)) != oldval) { + oldval = readback; + newval = oldval; + reducer.reduce(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + } + } + else if (sizeof(T) == 8) { + unsigned long long oldval = *reinterpret_cast(output); + unsigned long long newval = oldval; + reducer.reduce(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + unsigned long long readback; + while ((readback = atomicCAS(reinterpret_cast(output), oldval, newval)) != oldval) { + oldval = readback; + newval = oldval; + reducer.reduce(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + } + } + else { + gpu_assert(0 && "Wordsize not supported"); + } +#else // EIGEN_CUDA_ARCH >= 300 + EIGEN_UNUSED_VARIABLE(output); + EIGEN_UNUSED_VARIABLE(accum); + EIGEN_UNUSED_VARIABLE(reducer); + gpu_assert(0 && "Shouldn't be called on unsupported device"); +#endif // EIGEN_CUDA_ARCH >= 300 +} + +// We extend atomicExch to support extra data types +template +__device__ inline Type atomicExchCustom(Type* address, Type val) { + return atomicExch(address, val); +} + +template <> +__device__ inline double atomicExchCustom(double* address, double val) { + unsigned long long int* address_as_ull = reinterpret_cast(address); + return __longlong_as_double(atomicExch(address_as_ull, __double_as_longlong(val))); +} + +#ifdef EIGEN_HAS_GPU_FP16 +template +__device__ inline void atomicReduce(half2* output, half2 accum, R& reducer) { + unsigned int oldval = *reinterpret_cast(output); + unsigned int newval = oldval; + reducer.reducePacket(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + unsigned int readback; + while ((readback = atomicCAS((unsigned int*)output, oldval, newval)) != oldval) { + oldval = readback; + newval = oldval; + reducer.reducePacket(accum, reinterpret_cast(&newval)); + if (newval == oldval) { + return; + } + } +} +#ifdef EIGEN_GPU_COMPILE_PHASE +// reduction should be associative since reduction is not atomic in wide vector but atomic in half2 operations +template +__device__ inline void atomicReduce(Packet4h2* output, Packet4h2 accum, R& reducer) { + half2* houtput=reinterpret_cast(output); + half2* haccum=reinterpret_cast(&accum); + for(int i=0;i<4;++i){ + atomicReduce(houtput+i,*(haccum+i),reducer); + } +} +#endif // EIGEN_GPU_COMPILE_PHASE +#endif // EIGEN_HAS_GPU_FP16 + +template <> +__device__ inline void atomicReduce(float* output, float accum, SumReducer&) { +#if (defined(EIGEN_HIP_DEVICE_COMPILE) && defined(__HIP_ARCH_HAS_WARP_SHUFFLE__)) || (EIGEN_CUDA_ARCH >= 300) + atomicAdd(output, accum); +#else // EIGEN_CUDA_ARCH >= 300 + EIGEN_UNUSED_VARIABLE(output); + EIGEN_UNUSED_VARIABLE(accum); + gpu_assert(0 && "Shouldn't be called on unsupported device"); +#endif // EIGEN_CUDA_ARCH >= 300 +} + + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionInitKernel(const CoeffType val, Index num_preserved_coeffs, CoeffType* output) { + const Index thread_id = blockIdx.x * blockDim.x + threadIdx.x; + const Index num_threads = blockDim.x * gridDim.x; + for (Index i = thread_id; i < num_preserved_coeffs; i += num_threads) { + output[i] = val; + } +} + + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernel(Reducer reducer, const Self input, Index num_coeffs, + typename Self::CoeffReturnType* output, unsigned int* semaphore) { +#if (defined(EIGEN_HIP_DEVICE_COMPILE) && defined(__HIP_ARCH_HAS_WARP_SHUFFLE__)) || (EIGEN_CUDA_ARCH >= 300) + // Initialize the output value + const Index first_index = blockIdx.x * BlockSize * NumPerThread + threadIdx.x; + if (gridDim.x == 1) { + if (first_index == 0) { + *output = reducer.initialize(); + } + } + else { + if (threadIdx.x == 0) { + unsigned int block = atomicCAS(semaphore, 0u, 1u); + if (block == 0) { + // We're the first block to run, initialize the output value + atomicExchCustom(output, reducer.initialize()); + __threadfence(); + atomicExch(semaphore, 2u); + } + else { + // Wait for the first block to initialize the output value. + // Use atomicCAS here to ensure that the reads aren't cached + unsigned int val; + do { + val = atomicCAS(semaphore, 2u, 2u); + } + while (val < 2u); + } + } + } + + __syncthreads(); + + eigen_assert(gridDim.x == 1 || *semaphore >= 2u); + + typename Self::CoeffReturnType accum = reducer.initialize(); + Index max_iter = numext::mini(num_coeffs - first_index, NumPerThread*BlockSize); + for (Index i = 0; i < max_iter; i+=BlockSize) { + const Index index = first_index + i; + eigen_assert(index < num_coeffs); + typename Self::CoeffReturnType val = input.m_impl.coeff(index); + reducer.reduce(val, &accum); + } + +#pragma unroll + for (int offset = warpSize/2; offset > 0; offset /= 2) { + #if defined(EIGEN_HIPCC) + // use std::is_floating_point to determine the type of reduced_val + // This is needed because when Type == double, hipcc will give a "call to __shfl_down is ambguous" error + // and list the float and int versions of __shfl_down as the candidate functions. + if (std::is_floating_point::value) { + reducer.reduce(__shfl_down(static_cast(accum), offset, warpSize), &accum); + } else { + reducer.reduce(__shfl_down(static_cast(accum), offset, warpSize), &accum); + } + #elif defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000 + reducer.reduce(__shfl_down(accum, offset, warpSize), &accum); + #else + reducer.reduce(__shfl_down_sync(0xFFFFFFFF, accum, offset, warpSize), &accum); + #endif + } + + if ((threadIdx.x & (warpSize - 1)) == 0) { + atomicReduce(output, accum, reducer); + } + + if (gridDim.x > 1 && threadIdx.x == 0) { + // Let the last block reset the semaphore + atomicInc(semaphore, gridDim.x + 1); +#if defined(EIGEN_HIPCC) + __threadfence_system(); +#endif + } +#else // EIGEN_CUDA_ARCH >= 300 + EIGEN_UNUSED_VARIABLE(reducer); + EIGEN_UNUSED_VARIABLE(input); + EIGEN_UNUSED_VARIABLE(num_coeffs); + EIGEN_UNUSED_VARIABLE(output); + EIGEN_UNUSED_VARIABLE(semaphore); + gpu_assert(0 && "Shouldn't be called on unsupported device"); +#endif // EIGEN_CUDA_ARCH >= 300 +} + + +#ifdef EIGEN_HAS_GPU_FP16 +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionInitFullReduxKernelHalfFloat( + Reducer reducer, const Self input, Index num_coeffs, half* scratch) { + eigen_assert(blockDim.x == 1); + eigen_assert(gridDim.x == 1); + typedef packet_traits::type packet_type; + Index packet_remainder = + num_coeffs % Index(unpacket_traits::size); + if (packet_remainder != 0) { + half2* h2scratch = reinterpret_cast(scratch); + for (Index i = num_coeffs - packet_remainder; i + 2 <= num_coeffs; i += 2) { + *h2scratch = + __halves2half2(input.coeff(i), input.coeff(i + 1)); + h2scratch++; + } + if ((num_coeffs & 1) != 0) { + half lastCoeff = input.coeff(num_coeffs - 1); + *h2scratch = __halves2half2(lastCoeff, reducer.initialize()); + } + } else { + packet_type reduce = reducer.template initializePacket(); + internal::pstoreu(scratch, reduce); + } +} + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionInitKernelHalfFloat(Reducer reducer, const Self /*input*/, Index num_coeffs, half* output) { + const Index thread_id = blockIdx.x * blockDim.x + threadIdx.x; + const Index num_threads = blockDim.x * gridDim.x; + typedef typename packet_traits::type PacketType; + + const Index num_packets = + num_coeffs / Index(unpacket_traits::size); + PacketType* p_output = reinterpret_cast(output); + for (Index i = thread_id; i < num_packets; i += num_threads) { + p_output[i] = reducer.template initializePacket(); + } + Index packet_remainder = + num_coeffs % Index(unpacket_traits::size); + if (thread_id < packet_remainder) { + output[num_coeffs - packet_remainder + thread_id] = reducer.initialize(); + } +} + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernelHalfFloat( + Reducer reducer, const Self input, Index num_coeffs, + half* output, half* scratch) { + typedef typename packet_traits::type PacketType; + const int packet_width = unpacket_traits::size; + eigen_assert(NumPerThread % packet_width == 0); + const Index first_index = + blockIdx.x * BlockSize * NumPerThread + packet_width * threadIdx.x; + + // Initialize the output value if it wasn't initialized by the ReductionInitKernel + + if (gridDim.x == 1) { + if (first_index == 0) { + int rem = num_coeffs % packet_width; + if (rem != 0) { + half2* p_scratch = reinterpret_cast(scratch); + pstoreu(scratch, reducer.template initializePacket()); + for (int i = 0; i < rem / 2; i++) { + *p_scratch = __halves2half2( + input.coeff(num_coeffs - packet_width + 2 * i), + input.coeff(num_coeffs - packet_width + 2 * i + 1)); + p_scratch++; + } + if ((num_coeffs & 1) != 0) { + half last = input.coeff(num_coeffs - 1); + *p_scratch = __halves2half2(last, reducer.initialize()); + } + } else { + PacketType reduce = reducer.template initializePacket(); + pstoreu(scratch, reduce); + } + } + __syncthreads(); + } + + PacketType accum = reducer.template initializePacket(); + const Index max_iter = + numext::mini((num_coeffs - first_index) / packet_width, + NumPerThread * BlockSize / packet_width); + for (Index i = 0; i < max_iter; i += BlockSize) { + const Index index = first_index + packet_width * i; + eigen_assert(index + packet_width < num_coeffs); + PacketType val = input.template packet(index); + reducer.reducePacket(val, &accum); + } + +#pragma unroll + for (int offset = warpSize/2; offset > 0; offset /= 2) { + #if defined(EIGEN_HIPCC) + PacketType r1; + half2* hr = reinterpret_cast(&r1); + half2* hacc = reinterpret_cast(&accum); + for (int i = 0; i < packet_width / 2; i++) { + // FIXME : remove this workaround once we have native half/half2 support for __shfl_down + union { int i; half2 h; } wka_in, wka_out; + wka_in.h = hacc[i]; + wka_out.i = __shfl_down(wka_in.i, offset, warpSize); + hr[i] = wka_out.h; + } + reducer.reducePacket(r1, &accum); + #elif defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000 + PacketType r1; + half2* hr = reinterpret_cast(&r1); + half2* hacc = reinterpret_cast(&accum); + for (int i = 0; i < packet_width / 2; i++) { + hr[i] = __shfl_down(hacc[i], offset, warpSize); + } + reducer.reducePacket(r1, &accum); + #else + PacketType r1; + half2* hr = reinterpret_cast(&r1); + half2* hacc = reinterpret_cast(&accum); + for (int i = 0; i < packet_width / 2; i++) { + hr[i] = __shfl_down_sync(0xFFFFFFFF, hacc[i], (unsigned)offset, warpSize); + } + reducer.reducePacket(r1, &accum); + + #endif + } + + if ((threadIdx.x & (warpSize - 1)) == 0) { + atomicReduce(reinterpret_cast(scratch), accum, reducer); + } + + __syncthreads(); + half2* rv1 = reinterpret_cast(scratch); + if (packet_width > 2) { + reducer.reducePacket(rv1[2], rv1); + reducer.reducePacket(rv1[3], rv1 + 1); + reducer.reducePacket(rv1[1], rv1); + } + if (gridDim.x == 1) { + if (first_index == 0) { + half tmp = __low2half(*rv1); + reducer.reduce(__high2half(*rv1), &tmp); + *output = tmp; + } + } +} + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionCleanupKernelHalfFloat(Op reducer, half* output, half* scratch) { + eigen_assert(threadIdx.x == 1); + typedef packet_traits::type packet_type; + if (unpacket_traits::size == 1) { + *output = *scratch; + } else { + half2* pscratch = reinterpret_cast(scratch); + half tmp = __float2half(0.f); + for (int i = 0; i < unpacket_traits::size; i += 2) { + reducer.reduce(__low2half(*pscratch), &tmp); + reducer.reduce(__high2half(*pscratch), &tmp); + pscratch++; + } + *output = tmp; + } +} + +#endif // EIGEN_HAS_GPU_FP16 + +template +struct FullReductionLauncher { + static void run(const Self&, Op&, const GpuDevice&, OutputType*, typename Self::Index) { + gpu_assert(false && "Should only be called on doubles, floats and half floats"); + } +}; + +// Specialization for float and double +template +struct FullReductionLauncher< + Self, Op, OutputType, PacketAccess, + std::enable_if_t< + internal::is_same::value || + internal::is_same::value, + void>> { + static void run(const Self& self, Op& reducer, const GpuDevice& device, OutputType* output, typename Self::Index num_coeffs) { + + typedef typename Self::Index Index; + const int block_size = 256; + const int num_per_thread = 128; + const int num_blocks = divup(num_coeffs, block_size * num_per_thread); + + unsigned int* semaphore = NULL; + if (num_blocks > 1) { + semaphore = device.semaphore(); + } + + LAUNCH_GPU_KERNEL((FullReductionKernel), + num_blocks, block_size, 0, device, reducer, self, num_coeffs, output, semaphore); + } +}; + +#ifdef EIGEN_HAS_GPU_FP16 +template +struct FullReductionLauncher { + static void run(const Self&, Op&, const GpuDevice&, half*, typename Self::Index) { + gpu_assert(false && "Should not be called since there is no packet accessor"); + } +}; + +template +struct FullReductionLauncher { + static void run(const Self& self, Op& reducer, const GpuDevice& device, half* output, typename Self::Index num_coeffs) { + typedef typename Self::Index Index; + + const int block_size = 256; + const int num_per_thread = 128; + const int num_blocks = divup(num_coeffs, block_size * num_per_thread); + half* scratch = static_cast(device.scratchpad()); + + if (num_blocks > 1) { + // We initialize the output and the scrathpad outside the reduction kernel when we can't be sure that there + // won't be a race conditions between multiple thread blocks. + LAUNCH_GPU_KERNEL((ReductionInitFullReduxKernelHalfFloat), + 1, 1, 0, device, reducer, self, num_coeffs, scratch); + } + + LAUNCH_GPU_KERNEL((FullReductionKernelHalfFloat), + num_blocks, block_size, 0, device, reducer, self, num_coeffs, output, scratch); + + if (num_blocks > 1) { + LAUNCH_GPU_KERNEL((ReductionCleanupKernelHalfFloat), + 1, 1, 0, device, reducer, output, scratch); + } + } +}; +#endif // EIGEN_HAS_GPU_FP16 + + +template +struct FullReducer { + // Unfortunately nvidia doesn't support well exotic types such as complex, + // so reduce the scope of the optimized version of the code to the simple cases + // of doubles, floats and half floats +#ifdef EIGEN_HAS_GPU_FP16 + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful && + (internal::is_same::value || + internal::is_same::value || + (internal::is_same::value && reducer_traits::PacketAccess)); +#else // EIGEN_HAS_GPU_FP16 + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful && + (internal::is_same::value || + internal::is_same::value); +#endif // EIGEN_HAS_GPU_FP16 + + template + static void run(const Self& self, Op& reducer, const GpuDevice& device, OutputType* output) { + gpu_assert(HasOptimizedImplementation && "Should only be called on doubles, floats or half floats"); + const Index num_coeffs = array_prod(self.m_impl.dimensions()); + // Don't crash when we're called with an input tensor of size 0. + if (num_coeffs == 0) { + return; + } + + FullReductionLauncher::PacketAccess>::run(self, reducer, device, output, num_coeffs); + } +}; + + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernel(Reducer reducer, const Self input, Index num_coeffs_to_reduce, Index num_preserved_coeffs, + typename Self::CoeffReturnType* output) { +#if (defined(EIGEN_HIP_DEVICE_COMPILE) && defined(__HIP_ARCH_HAS_WARP_SHUFFLE__)) || (EIGEN_CUDA_ARCH >= 300) + typedef typename Self::CoeffReturnType Type; + eigen_assert(blockDim.y == 1); + eigen_assert(blockDim.z == 1); + eigen_assert(gridDim.y == 1); + eigen_assert(gridDim.z == 1); + + const int unroll_times = 16; + eigen_assert(NumPerThread % unroll_times == 0); + + const Index input_col_blocks = divup(num_coeffs_to_reduce, blockDim.x * NumPerThread); + const Index num_input_blocks = input_col_blocks * num_preserved_coeffs; + + const Index num_threads = blockDim.x * gridDim.x; + const Index thread_id = blockIdx.x * blockDim.x + threadIdx.x; + + // Initialize the output values if they weren't initialized by the ReductionInitKernel + if (gridDim.x == 1) { + for (Index i = thread_id; i < num_preserved_coeffs; i += num_threads) { + output[i] = reducer.initialize(); + } + __syncthreads(); + } + + for (Index i = blockIdx.x; i < num_input_blocks; i += gridDim.x) { + const Index row = i / input_col_blocks; + + if (row < num_preserved_coeffs) { + const Index col_block = i % input_col_blocks; + const Index col_begin = col_block * blockDim.x * NumPerThread + threadIdx.x; + + Type reduced_val = reducer.initialize(); + + for (Index j = 0; j < NumPerThread; j += unroll_times) { + const Index last_col = col_begin + blockDim.x * (j + unroll_times - 1); + if (last_col >= num_coeffs_to_reduce) { + for (Index col = col_begin + blockDim.x * j; col < num_coeffs_to_reduce; col += blockDim.x) { + const Type val = input.m_impl.coeff(row * num_coeffs_to_reduce + col); + reducer.reduce(val, &reduced_val); + } + break; + } else { + // Faster version of the loop with no branches after unrolling. +#pragma unroll + for (int k = 0; k < unroll_times; ++k) { + const Index col = col_begin + blockDim.x * (j + k); + reducer.reduce(input.m_impl.coeff(row * num_coeffs_to_reduce + col), &reduced_val); + } + } + } + +#pragma unroll + for (int offset = warpSize/2; offset > 0; offset /= 2) { + #if defined(EIGEN_HIPCC) + // use std::is_floating_point to determine the type of reduced_val + // This is needed because when Type == double, hipcc will give a "call to __shfl_down is ambguous" error + // and list the float and int versions of __shfl_down as the candidate functions. + if (std::is_floating_point::value) { + reducer.reduce(__shfl_down(static_cast(reduced_val), offset), &reduced_val); + } else { + reducer.reduce(__shfl_down(static_cast(reduced_val), offset), &reduced_val); + } + #elif defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000 + reducer.reduce(__shfl_down(reduced_val, offset), &reduced_val); + #else + reducer.reduce(__shfl_down_sync(0xFFFFFFFF, reduced_val, offset), &reduced_val); + #endif + } + + if ((threadIdx.x & (warpSize - 1)) == 0) { + atomicReduce(&(output[row]), reduced_val, reducer); + } + } + } +#else // EIGEN_CUDA_ARCH >= 300 + gpu_assert(0 && "Shouldn't be called on unsupported device"); +#endif // EIGEN_CUDA_ARCH >= 300 +} + +#ifdef EIGEN_HAS_GPU_FP16 + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernelHalfFloat(Reducer reducer, const Self input, Index num_coeffs_to_reduce, Index num_preserved_coeffs, + half* output) { + eigen_assert(blockDim.y == 1); + eigen_assert(blockDim.z == 1); + eigen_assert(gridDim.y == 1); + eigen_assert(gridDim.z == 1); + + typedef typename packet_traits::type PacketType; + const int packet_width = unpacket_traits::size; + const int unroll_times = 16 / packet_width; + eigen_assert(NumPerThread % unroll_times == 0); + eigen_assert(unroll_times % 2 == 0); + + const Index input_col_blocks = divup(num_coeffs_to_reduce, blockDim.x * NumPerThread * 2); + const Index num_input_blocks = divup(input_col_blocks * num_preserved_coeffs, 2); + + const Index num_threads = blockDim.x * gridDim.x; + const Index thread_id = blockIdx.x * blockDim.x + threadIdx.x; + + // Initialize the output values if they weren't initialized by the ReductionInitKernel + if (gridDim.x == 1) { + Index i = packet_width * thread_id; + for (; i + packet_width <= num_preserved_coeffs; + i += packet_width * num_threads) { + PacketType* poutput = reinterpret_cast(output + i); + *poutput = reducer.template initializePacket(); + } + if (i < num_preserved_coeffs) { + output[i] = reducer.initialize(); + } + __syncthreads(); + } + + for (Index i = blockIdx.x; i < num_input_blocks; i += gridDim.x) { + const Index row = 2 * (i / input_col_blocks); // everybody takes 2 rows + + if (row + 1 < num_preserved_coeffs) { + const Index col_block = i % input_col_blocks; + const Index col_begin = + packet_width * (col_block * blockDim.x * NumPerThread + threadIdx.x); + + PacketType reduced_val1 = reducer.template initializePacket(); + PacketType reduced_val2 = reducer.template initializePacket(); + + for (Index j = 0; j < NumPerThread; j += unroll_times) { + const Index last_col = + col_begin + blockDim.x * (j + unroll_times - 1) * packet_width; + if (last_col >= num_coeffs_to_reduce) { + Index col = col_begin + blockDim.x * j; + for (; col + packet_width <= num_coeffs_to_reduce; + col += blockDim.x) { + const PacketType val1 = input.m_impl.template packet( + row * num_coeffs_to_reduce + col); + reducer.reducePacket(val1, &reduced_val1); + const PacketType val2 = input.m_impl.template packet( + (row + 1) * num_coeffs_to_reduce + col); + reducer.reducePacket(val2, &reduced_val2); + } + if (col < num_coeffs_to_reduce) { + PacketType r1 = reducer.template initializePacket(); + PacketType r2 = reducer.template initializePacket(); + half2* hr1 = reinterpret_cast(&r1); + half2* hr2 = reinterpret_cast(&r2); + while (col + 1 < num_coeffs_to_reduce) { + *hr1 = __halves2half2( + input.m_impl.coeff(row * num_coeffs_to_reduce + col), + input.m_impl.coeff(row * num_coeffs_to_reduce + col + 1)); + *hr2 = __halves2half2( + input.m_impl.coeff((row + 1) * num_coeffs_to_reduce + col), + input.m_impl.coeff((row + 1) * num_coeffs_to_reduce + col + + 1)); + hr1++; + hr2++; + col += 2; + } + if (col < num_coeffs_to_reduce) { + // Peel; + const half last1 = + input.m_impl.coeff(row * num_coeffs_to_reduce + col); + *hr1 = __halves2half2(last1, reducer.initialize()); + const half last2 = + input.m_impl.coeff((row + 1) * num_coeffs_to_reduce + col); + *hr2 = __halves2half2(last2, reducer.initialize()); + } + reducer.reducePacket(r1, &reduced_val1); + reducer.reducePacket(r2, &reduced_val2); + } + break; + } else { + // Faster version of the loop with no branches after unrolling. +#pragma unroll + for (int k = 0; k < unroll_times; ++k) { + const Index col = col_begin + blockDim.x * (j + k) * packet_width; + reducer.reducePacket(input.m_impl.template packet( + row * num_coeffs_to_reduce + col), + &reduced_val1); + reducer.reducePacket(input.m_impl.template packet( + (row + 1) * num_coeffs_to_reduce + col), + &reduced_val2); + } + } + } + +#pragma unroll + for (int offset = warpSize/2; offset > 0; offset /= 2) { + #if defined(EIGEN_HIPCC) + PacketType r1; + PacketType r2; + half2* hr1 = reinterpret_cast(&r1); + half2* hr2 = reinterpret_cast(&r2); + half2* rv1 = reinterpret_cast(&reduced_val1); + half2* rv2 = reinterpret_cast(&reduced_val2); + for (int i = 0; i < packet_width / 2; i++) { + // FIXME : remove this workaround once we have native half/half2 support for __shfl_down + union { int i; half2 h; } wka_in1, wka_out1; + wka_in1.h = rv1[i]; + wka_out1.i = __shfl_down(wka_in1.i, offset, warpSize); + hr1[i] = wka_out1.h; + + union { int i; half2 h; } wka_in2, wka_out2; + wka_in2.h = rv2[i]; + wka_out2.i = __shfl_down(wka_in2.i, offset, warpSize); + hr2[i] = wka_out2.h; + } + reducer.reducePacket(r1, &reduced_val1); + reducer.reducePacket(r2, &reduced_val2); + #elif defined(EIGEN_CUDA_SDK_VER) && EIGEN_CUDA_SDK_VER < 90000 + PacketType r1; + PacketType r2; + half2* hr1 = reinterpret_cast(&r1); + half2* hr2 = reinterpret_cast(&r2); + half2* rv1 = reinterpret_cast(&reduced_val1); + half2* rv2 = reinterpret_cast(&reduced_val2); + for (int i = 0; i < packet_width / 2; i++) { + hr1[i] = __shfl_down(rv1[i], offset, warpSize); + hr2[i] = __shfl_down(rv2[i], offset, warpSize); + } + reducer.reducePacket(r1, &reduced_val1); + reducer.reducePacket(r2, &reduced_val2); + #else + PacketType r1; + PacketType r2; + half2* hr1 = reinterpret_cast(&r1); + half2* hr2 = reinterpret_cast(&r2); + half2* rr1 = reinterpret_cast(&reduced_val1); + half2* rr2 = reinterpret_cast(&reduced_val2); + for (int j = 0; j < packet_width / 2; j++) { + hr1[j] = + __shfl_down_sync(0xFFFFFFFF, rr1[j], (unsigned)offset, warpSize); + hr2[j] = + __shfl_down_sync(0xFFFFFFFF, rr2[j], (unsigned)offset, warpSize); + } + reducer.reducePacket(r1, &reduced_val1); + reducer.reducePacket(r2, &reduced_val2); + + #endif + } + half2* rv1 = reinterpret_cast(&reduced_val1); + half2* rv2 = reinterpret_cast(&reduced_val2); + half2 val; + if (packet_width > 2) { + reducer.reducePacket(rv1[2], rv1); + reducer.reducePacket(rv1[3], rv1 + 1); + reducer.reducePacket(rv1[1], rv1); + reducer.reducePacket(rv2[2], rv2); + reducer.reducePacket(rv2[3], rv2 + 1); + reducer.reducePacket(rv2[1], rv2); + } + half val1 = __low2half(*rv1); + reducer.reduce(__high2half(*rv1), &val1); + half val2 = __low2half(*rv2); + reducer.reduce(__high2half(*rv2), &val2); + val = __halves2half2(val1, val2); + if ((threadIdx.x & (warpSize - 1)) == 0) { + half* loc = output + row; + atomicReduce(reinterpret_cast(loc), val, reducer); + } + } + } +} + +#endif // EIGEN_HAS_GPU_FP16 + +template +struct InnerReductionLauncher { + static EIGEN_DEVICE_FUNC bool run(const Self&, Op&, const GpuDevice&, OutputType*, typename Self::Index, typename Self::Index) { + gpu_assert(false && "Should only be called to reduce doubles, floats and half floats on a gpu device"); + return true; + } +}; + +// Specialization for float and double +template +struct InnerReductionLauncher< + Self, Op, OutputType, PacketAccess, + std::enable_if_t< + internal::is_same::value || + internal::is_same::value, + void>> { + static bool run(const Self& self, Op& reducer, const GpuDevice& device, OutputType* output, typename Self::Index num_coeffs_to_reduce, typename Self::Index num_preserved_vals) { + typedef typename Self::Index Index; + + const Index num_coeffs = num_coeffs_to_reduce * num_preserved_vals; + const int block_size = 256; + const int num_per_thread = 128; + const int dyn_blocks = divup(num_coeffs, block_size * num_per_thread); + const int max_blocks = device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor() / block_size; + const int num_blocks = numext::mini(max_blocks, dyn_blocks); + + if (num_blocks > 1) { + // We initialize the outputs outside the reduction kernel when we can't be sure that there + // won't be a race conditions between multiple thread blocks. + const int dyn_blocks2 = divup(num_preserved_vals, 1024); + const int max_blocks2 = device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor() / 1024; + const int num_blocks2 = numext::mini(max_blocks2, dyn_blocks2); + LAUNCH_GPU_KERNEL((ReductionInitKernel), + num_blocks2, 1024, 0, device, reducer.initialize(), + num_preserved_vals, output); + } + + LAUNCH_GPU_KERNEL((InnerReductionKernel), + num_blocks, block_size, 0, device, reducer, self, num_coeffs_to_reduce, num_preserved_vals, output); + + return false; + } +}; + +#ifdef EIGEN_HAS_GPU_FP16 +template +struct InnerReductionLauncher { + static bool run(const Self&, Op&, const GpuDevice&, half*, typename Self::Index, typename Self::Index) { + gpu_assert(false && "Should not be called since there is no packet accessor"); + return true; + } +}; + +template +struct InnerReductionLauncher { + static bool run(const Self& self, Op& reducer, const GpuDevice& device, half* output, typename Self::Index num_coeffs_to_reduce, typename Self::Index num_preserved_vals) { + typedef typename Self::Index Index; + + if (num_preserved_vals % 2 != 0) { + // Not supported yet, revert to the slower code path + return true; + } + + const Index num_coeffs = num_coeffs_to_reduce * num_preserved_vals; + const int block_size = /*256*/128; + const int num_per_thread = /*128*/64; + const int dyn_blocks = divup(num_coeffs, block_size * num_per_thread); + const int max_blocks = device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor() / block_size; + const int num_blocks = numext::mini(max_blocks, dyn_blocks); + + if (num_blocks > 1) { + // We initialize the outputs outside the reduction kernel when we can't be sure that there + // won't be a race conditions between multiple thread blocks. + LAUNCH_GPU_KERNEL((ReductionInitKernelHalfFloat), + 1, 1, 0, device, reducer, self, num_preserved_vals, output); + } + + LAUNCH_GPU_KERNEL((InnerReductionKernelHalfFloat), + num_blocks, block_size, 0, device, reducer, self, num_coeffs_to_reduce, num_preserved_vals, output); + + return false; + } +}; +#endif // EIGEN_HAS_GPU_FP16 + + +template +struct InnerReducer { + // Unfortunately nvidia doesn't support well exotic types such as complex, + // so reduce the scope of the optimized version of the code to the simple case + // of floats and half floats. +#ifdef EIGEN_HAS_GPU_FP16 + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful && + (internal::is_same::value || + internal::is_same::value || + (internal::is_same::value && reducer_traits::PacketAccess)); +#else // EIGEN_HAS_GPU_FP16 + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful && + (internal::is_same::value || + internal::is_same::value); +#endif // EIGEN_HAS_GPU_FP16 + + template + static bool run(const Self& self, Op& reducer, const GpuDevice& device, OutputType* output, typename Self::Index num_coeffs_to_reduce, typename Self::Index num_preserved_vals) { + gpu_assert(HasOptimizedImplementation && "Should only be called on doubles, floats or half floats"); + const Index num_coeffs = array_prod(self.m_impl.dimensions()); + // Don't crash when we're called with an input tensor of size 0. + if (num_coeffs == 0) { + return true; + } + // It's faster to use the usual code. + if (num_coeffs_to_reduce <= 128) { + return true; + } + + return InnerReductionLauncher::PacketAccess>::run(self, reducer, device, output, num_coeffs_to_reduce, num_preserved_vals); + } +}; + +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void OuterReductionKernel(Reducer reducer, const Self input, Index num_coeffs_to_reduce, Index num_preserved_coeffs, + typename Self::CoeffReturnType* output) { + const Index num_threads = blockDim.x * gridDim.x; + const Index thread_id = blockIdx.x * blockDim.x + threadIdx.x; + // Initialize the output values if they weren't initialized by the ReductionInitKernel + if (gridDim.x == 1) { + for (Index i = thread_id; i < num_preserved_coeffs; i += num_threads) { + output[i] = reducer.initialize(); + } + __syncthreads(); + } + + // Do the reduction. + const Index max_iter = num_preserved_coeffs * divup(num_coeffs_to_reduce, NumPerThread); + for (Index i = thread_id; i < max_iter; i += num_threads) { + const Index input_col = i % num_preserved_coeffs; + const Index input_row = (i / num_preserved_coeffs) * NumPerThread; + typename Self::CoeffReturnType reduced_val = reducer.initialize(); + const Index max_row = numext::mini(input_row + NumPerThread, num_coeffs_to_reduce); + for (Index j = input_row; j < max_row; j++) { + typename Self::CoeffReturnType val = input.m_impl.coeff(j * num_preserved_coeffs + input_col); + reducer.reduce(val, &reduced_val); + } + atomicReduce(&(output[input_col]), reduced_val, reducer); + } +} + + +template +struct OuterReducer { + // Unfortunately nvidia doesn't support well exotic types such as complex, + // so reduce the scope of the optimized version of the code to the simple case + // of floats. + static constexpr bool HasOptimizedImplementation = !Self::ReducerTraits::IsStateful && + (internal::is_same::value || + internal::is_same::value); + template + static + #if !defined(EIGEN_HIPCC) + // FIXME : leaving this EIGEN_DEVICE_FUNC in, results in the following runtime error + // (in the cxx11_tensor_reduction_gpu test) + // + // terminate called after throwing an instance of 'std::runtime_error' + // what(): No device code available for function: _ZN5Eigen8internal20OuterReductionKernelIL... + // + // don't know why this happens (and why is it a runtime error instead of a compile time error) + // + // this will be fixed by HIP PR#457 + EIGEN_DEVICE_FUNC + #endif + bool run(const Self&, Op&, const Device&, OutputType*, typename Self::Index, typename Self::Index) { + gpu_assert(false && "Should only be called to reduce doubles or floats on a gpu device"); + return true; + } + + static bool run(const Self& self, Op& reducer, const GpuDevice& device, float* output, typename Self::Index num_coeffs_to_reduce, typename Self::Index num_preserved_vals) { + typedef typename Self::Index Index; + + // It's faster to use the usual code. + if (num_coeffs_to_reduce <= 32) { + return true; + } + + const Index num_coeffs = num_coeffs_to_reduce * num_preserved_vals; + const int block_size = 256; + const int num_per_thread = 16; + const int dyn_blocks = divup(num_coeffs, block_size * num_per_thread); + const int max_blocks = device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor() / block_size; + const int num_blocks = numext::mini(max_blocks, dyn_blocks); + + if (num_blocks > 1) { + // We initialize the outputs in the reduction kernel itself when we don't have to worry + // about race conditions between multiple thread blocks. + const int dyn_blocks2 = divup(num_preserved_vals, 1024); + const int max_blocks2 = device.getNumGpuMultiProcessors() * + device.maxGpuThreadsPerMultiProcessor() / 1024; + const int num_blocks2 = numext::mini(max_blocks2, dyn_blocks2); + LAUNCH_GPU_KERNEL((ReductionInitKernel), + num_blocks2, 1024, 0, device, reducer.initialize(), + num_preserved_vals, output); + } + + LAUNCH_GPU_KERNEL((OuterReductionKernel), + num_blocks, block_size, 0, device, reducer, self, num_coeffs_to_reduce, num_preserved_vals, output); + + return false; + } +}; + +#endif // defined(EIGEN_USE_GPU) && defined(EIGEN_GPUCC) + + +} // end namespace internal +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_REDUCTION_GPU_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionSycl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionSycl.h new file mode 100644 index 0000000000000000000000000000000000000000..ea3c2dce586fd41226d75643da9153142ab8892d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReductionSycl.h @@ -0,0 +1,581 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Mehdi Goli Codeplay Software Ltd. +// Ralph Potter Codeplay Software Ltd. +// Luke Iwanski Codeplay Software Ltd. +// Contact: +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/***************************************************************** + * TensorReductionSycl.h + * + * \brief: + * This is the specialization of the reduction operation. Two phase reduction approach + * is used since the GPU does not have Global Synchronization for global memory among + * different work-group/thread block. To solve the problem, we need to create two kernels + * to reduce the data, where the first kernel reduce the data locally and each local + * workgroup/thread-block save the input data into global memory. In the second phase (global reduction) + * one work-group uses one work-group/thread-block to reduces the intermediate data into one single element. + * Here is an NVIDIA presentation explaining the optimized two phase reduction algorithm on GPU: + * https://developer.download.nvidia.com/assets/cuda/files/reduction.pdf + * + *****************************************************************/ + +#ifndef UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_REDUCTION_SYCL_HPP +#define UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_REDUCTION_SYCL_HPP +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace TensorSycl { +namespace internal { + +template +struct OpDefiner { + typedef typename Vectorise::PacketReturnType PacketReturnType; + typedef Op type; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE type get_op(Op &op) { return op; } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType finalise_op(const PacketReturnType &accumulator, + const Index &) { + return accumulator; + } +}; + +template +struct OpDefiner, CoeffReturnType, Index, false> { + typedef Eigen::internal::SumReducer type; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE type get_op(Eigen::internal::MeanReducer &) { + return type(); + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType finalise_op(const CoeffReturnType &accumulator, + const Index &scale) { + ::Eigen::internal::scalar_quotient_op quotient_op; + return quotient_op(accumulator, CoeffReturnType(scale)); + } +}; + +template +struct OpDefiner, CoeffReturnType, Index, true> { + typedef typename Vectorise::PacketReturnType PacketReturnType; + typedef Eigen::internal::SumReducer type; + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE type get_op(Eigen::internal::MeanReducer &) { + return type(); + } + + static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType finalise_op(const PacketReturnType &accumulator, + const Index &scale) { + return ::Eigen::internal::pdiv(accumulator, ::Eigen::internal::pset1(CoeffReturnType(scale))); + } +}; + +template +struct SecondStepFullReducer { + typedef cl::sycl::accessor + LocalAccessor; + typedef OpDefiner OpDef; + typedef typename OpDef::type Op; + LocalAccessor scratch; + InputAccessor aI; + OutputAccessor outAcc; + Op op; + SecondStepFullReducer(LocalAccessor scratch_, InputAccessor aI_, OutputAccessor outAcc_, OpType op_) + : scratch(scratch_), aI(aI_), outAcc(outAcc_), op(OpDef::get_op(op_)) {} + + void operator()(cl::sycl::nd_item<1> itemID) const { + // Our empirical research shows that the best performance will be achieved + // when there is only one element per thread to reduce in the second step. + // in this step the second step reduction time is almost negligible. + // Hence, in the second step of reduction the input size is fixed to the + // local size, thus, there is only one element read per thread. The + // algorithm must be changed if the number of reduce per thread in the + // second step is greater than 1. Otherwise, the result will be wrong. + const Index localid = itemID.get_local_id(0); + auto aInPtr = aI + localid; + auto aOutPtr = outAcc; + CoeffReturnType *scratchptr = scratch.get_pointer(); + CoeffReturnType accumulator = *aInPtr; + + scratchptr[localid] = op.finalize(accumulator); + for (Index offset = itemID.get_local_range(0) / 2; offset > 0; offset /= 2) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (localid < offset) { + op.reduce(scratchptr[localid + offset], &accumulator); + scratchptr[localid] = op.finalize(accumulator); + } + } + if (localid == 0) *aOutPtr = op.finalize(accumulator); + } +}; + +// Full reduction first phase. In this version the vectorization is true and the reduction accept +// any generic reducerOp e.g( max, min, sum, mean, iamax, iamin, etc ). +template +class FullReductionKernelFunctor { + public: + typedef typename Evaluator::CoeffReturnType CoeffReturnType; + typedef typename Evaluator::Index Index; + typedef OpDefiner + OpDef; + + typedef typename OpDef::type Op; + typedef typename Evaluator::EvaluatorPointerType EvaluatorPointerType; + typedef typename Evaluator::PacketReturnType PacketReturnType; + typedef std::conditional_t<(Evaluator::ReducerTraits::PacketAccess & Evaluator::InputPacketAccess), + PacketReturnType, CoeffReturnType> OutType; + typedef cl::sycl::accessor + LocalAccessor; + LocalAccessor scratch; + Evaluator evaluator; + EvaluatorPointerType final_output; + Index rng; + Op op; + + FullReductionKernelFunctor(LocalAccessor scratch_, Evaluator evaluator_, EvaluatorPointerType final_output_, + Index rng_, OpType op_) + : scratch(scratch_), evaluator(evaluator_), final_output(final_output_), rng(rng_), op(OpDef::get_op(op_)) {} + + void operator()(cl::sycl::nd_item<1> itemID) const { compute_reduction(itemID); } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t compute_reduction( + const cl::sycl::nd_item<1> &itemID) const { + auto output_ptr = final_output; + Index VectorizedRange = (rng / Evaluator::PacketSize) * Evaluator::PacketSize; + Index globalid = itemID.get_global_id(0); + Index localid = itemID.get_local_id(0); + Index step = Evaluator::PacketSize * itemID.get_global_range(0); + Index start = Evaluator::PacketSize * globalid; + // vectorizable parts + PacketReturnType packetAccumulator = op.template initializePacket(); + for (Index i = start; i < VectorizedRange; i += step) { + op.template reducePacket(evaluator.impl().template packet(i), &packetAccumulator); + } + globalid += VectorizedRange; + // non vectorizable parts + for (Index i = globalid; i < rng; i += itemID.get_global_range(0)) { + op.template reducePacket( + ::Eigen::TensorSycl::internal::PacketWrapper::convert_to_packet_type( + evaluator.impl().coeff(i), op.initialize()), + &packetAccumulator); + } + scratch[localid] = packetAccumulator = + OpDef::finalise_op(op.template finalizePacket(packetAccumulator), rng); + // reduction parts // Local size is always power of 2 + EIGEN_UNROLL_LOOP + for (Index offset = local_range / 2; offset > 0; offset /= 2) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (localid < offset) { + op.template reducePacket(scratch[localid + offset], &packetAccumulator); + scratch[localid] = op.template finalizePacket(packetAccumulator); + } + } + if (localid == 0) { + output_ptr[itemID.get_group(0)] = + op.finalizeBoth(op.initialize(), op.template finalizePacket(packetAccumulator)); + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::enable_if_t compute_reduction( + const cl::sycl::nd_item<1> &itemID) const { + auto output_ptr = final_output; + Index globalid = itemID.get_global_id(0); + Index localid = itemID.get_local_id(0); + // vectorizable parts + CoeffReturnType accumulator = op.initialize(); + // non vectorizable parts + for (Index i = globalid; i < rng; i += itemID.get_global_range(0)) { + op.reduce(evaluator.impl().coeff(i), &accumulator); + } + scratch[localid] = accumulator = OpDef::finalise_op(op.finalize(accumulator), rng); + + // reduction parts. the local size is always power of 2 + EIGEN_UNROLL_LOOP + for (Index offset = local_range / 2; offset > 0; offset /= 2) { + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (localid < offset) { + op.reduce(scratch[localid + offset], &accumulator); + scratch[localid] = op.finalize(accumulator); + } + } + if (localid == 0) { + output_ptr[itemID.get_group(0)] = op.finalize(accumulator); + } + } +}; + +template +class GenericNondeterministicReducer { + public: + typedef typename Evaluator::CoeffReturnType CoeffReturnType; + typedef typename Evaluator::EvaluatorPointerType EvaluatorPointerType; + typedef typename Evaluator::Index Index; + typedef OpDefiner OpDef; + typedef typename OpDef::type Op; + template + GenericNondeterministicReducer(Scratch, Evaluator evaluator_, EvaluatorPointerType output_accessor_, OpType functor_, + Index range_, Index num_values_to_reduce_) + : evaluator(evaluator_), + output_accessor(output_accessor_), + functor(OpDef::get_op(functor_)), + range(range_), + num_values_to_reduce(num_values_to_reduce_) {} + + void operator()(cl::sycl::nd_item<1> itemID) const { + //This is to bypass the statefull condition in Eigen meanReducer + Op non_const_functor; + std::memcpy(&non_const_functor, &functor, sizeof (Op)); + auto output_accessor_ptr = output_accessor; + Index globalid = static_cast(itemID.get_global_linear_id()); + if (globalid < range) { + CoeffReturnType accum = functor.initialize(); + Eigen::internal::GenericDimReducer::reduce( + evaluator, evaluator.firstInput(globalid), non_const_functor, &accum); + output_accessor_ptr[globalid] = OpDef::finalise_op(functor.finalize(accum), num_values_to_reduce); + } + } + + private: + Evaluator evaluator; + EvaluatorPointerType output_accessor; + Op functor; + Index range; + Index num_values_to_reduce; +}; + +enum class reduction_dim { inner_most, outer_most }; +// default is preserver +template +struct PartialReductionKernel { + typedef typename Evaluator::CoeffReturnType CoeffReturnType; + typedef typename Evaluator::EvaluatorPointerType EvaluatorPointerType; + typedef typename Evaluator::Index Index; + typedef OpDefiner OpDef; + typedef typename OpDef::type Op; + typedef cl::sycl::accessor + ScratchAcc; + ScratchAcc scratch; + Evaluator evaluator; + EvaluatorPointerType output_accessor; + Op op; + const Index preserve_elements_num_groups; + const Index reduce_elements_num_groups; + const Index num_coeffs_to_preserve; + const Index num_coeffs_to_reduce; + + PartialReductionKernel(ScratchAcc scratch_, Evaluator evaluator_, EvaluatorPointerType output_accessor_, OpType op_, + const Index preserve_elements_num_groups_, const Index reduce_elements_num_groups_, + const Index num_coeffs_to_preserve_, const Index num_coeffs_to_reduce_) + : scratch(scratch_), + evaluator(evaluator_), + output_accessor(output_accessor_), + op(OpDef::get_op(op_)), + preserve_elements_num_groups(preserve_elements_num_groups_), + reduce_elements_num_groups(reduce_elements_num_groups_), + num_coeffs_to_preserve(num_coeffs_to_preserve_), + num_coeffs_to_reduce(num_coeffs_to_reduce_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void element_wise_reduce(Index globalRId, Index globalPId, + CoeffReturnType &accumulator) const { + if (globalPId >= num_coeffs_to_preserve) { + return; + } + Index global_offset = rt == reduction_dim::outer_most ? globalPId + (globalRId * num_coeffs_to_preserve) + : globalRId + (globalPId * num_coeffs_to_reduce); + Index localOffset = globalRId; + + const Index per_thread_local_stride = PannelParameters::LocalThreadSizeR * reduce_elements_num_groups; + const Index per_thread_global_stride = + rt == reduction_dim::outer_most ? num_coeffs_to_preserve * per_thread_local_stride : per_thread_local_stride; + for (Index i = globalRId; i < num_coeffs_to_reduce; i += per_thread_local_stride) { + op.reduce(evaluator.impl().coeff(global_offset), &accumulator); + localOffset += per_thread_local_stride; + global_offset += per_thread_global_stride; + } + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + const Index linearLocalThreadId = itemID.get_local_id(0); + Index pLocalThreadId = rt == reduction_dim::outer_most ? linearLocalThreadId % PannelParameters::LocalThreadSizeP + : linearLocalThreadId / PannelParameters::LocalThreadSizeR; + Index rLocalThreadId = rt == reduction_dim::outer_most ? linearLocalThreadId / PannelParameters::LocalThreadSizeP + : linearLocalThreadId % PannelParameters::LocalThreadSizeR; + const Index pGroupId = rt == reduction_dim::outer_most ? itemID.get_group(0) % preserve_elements_num_groups + : itemID.get_group(0) / reduce_elements_num_groups; + const Index rGroupId = rt == reduction_dim::outer_most ? itemID.get_group(0) / preserve_elements_num_groups + : itemID.get_group(0) % reduce_elements_num_groups; + + Index globalPId = pGroupId * PannelParameters::LocalThreadSizeP + pLocalThreadId; + const Index globalRId = rGroupId * PannelParameters::LocalThreadSizeR + rLocalThreadId; + CoeffReturnType* scratchPtr = scratch.get_pointer(); + auto outPtr = + output_accessor + (reduce_elements_num_groups > 1 ? rGroupId * num_coeffs_to_preserve : 0); + CoeffReturnType accumulator = op.initialize(); + + element_wise_reduce(globalRId, globalPId, accumulator); + + accumulator = OpDef::finalise_op(op.finalize(accumulator), num_coeffs_to_reduce); + scratchPtr[pLocalThreadId + rLocalThreadId * (PannelParameters::LocalThreadSizeP + PannelParameters::BC)] = + accumulator; + if (rt == reduction_dim::inner_most) { + pLocalThreadId = linearLocalThreadId % PannelParameters::LocalThreadSizeP; + rLocalThreadId = linearLocalThreadId / PannelParameters::LocalThreadSizeP; + globalPId = pGroupId * PannelParameters::LocalThreadSizeP + pLocalThreadId; + } + + /* Apply the reduction operation between the current local + * id and the one on the other half of the vector. */ + auto out_scratch_ptr = + scratchPtr + (pLocalThreadId + (rLocalThreadId * (PannelParameters::LocalThreadSizeP + PannelParameters::BC))); + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (rt == reduction_dim::inner_most) { + accumulator = *out_scratch_ptr; + } + // The Local LocalThreadSizeR is always power of 2 + EIGEN_UNROLL_LOOP + for (Index offset = PannelParameters::LocalThreadSizeR >> 1; offset > 0; offset >>= 1) { + if (rLocalThreadId < offset) { + op.reduce(out_scratch_ptr[(PannelParameters::LocalThreadSizeP + PannelParameters::BC) * offset], &accumulator); + // The result has already been divided for mean reducer in the + // previous reduction so no need to divide furthermore + *out_scratch_ptr = op.finalize(accumulator); + } + /* All threads collectively read from global memory into local. + * The barrier ensures all threads' IO is resolved before + * execution continues (strictly speaking, all threads within + * a single work-group - there is no co-ordination between + * work-groups, only work-items). */ + itemID.barrier(cl::sycl::access::fence_space::local_space); + } + + if (rLocalThreadId == 0 && (globalPId < num_coeffs_to_preserve)) { + outPtr[globalPId] = op.finalize(accumulator); + } + } +}; + +template +struct SecondStepPartialReduction { + typedef OpDefiner OpDef; + typedef typename OpDef::type Op; + typedef cl::sycl::accessor + ScratchAccessor; + InputAccessor input_accessor; + OutputAccessor output_accessor; + Op op; + const Index num_coeffs_to_preserve; + const Index num_coeffs_to_reduce; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE SecondStepPartialReduction(ScratchAccessor, InputAccessor input_accessor_, + OutputAccessor output_accessor_, OpType op_, + const Index num_coeffs_to_preserve_, + const Index num_coeffs_to_reduce_) + : input_accessor(input_accessor_), + output_accessor(output_accessor_), + op(OpDef::get_op(op_)), + num_coeffs_to_preserve(num_coeffs_to_preserve_), + num_coeffs_to_reduce(num_coeffs_to_reduce_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + const Index globalId = itemID.get_global_id(0); + + if (globalId >= num_coeffs_to_preserve) return; + + auto in_ptr = input_accessor + globalId; + + OutScalar accumulator = op.initialize(); +// num_coeffs_to_reduce is not bigger that 256 + for (Index i = 0; i < num_coeffs_to_reduce; i++) { + op.reduce(*in_ptr, &accumulator); + in_ptr += num_coeffs_to_preserve; + } + output_accessor[globalId] = op.finalize(accumulator); + } +}; // namespace internal + +template +struct ReductionPannel { + static EIGEN_CONSTEXPR Index LocalThreadSizeP = LTP; + static EIGEN_CONSTEXPR Index LocalThreadSizeR = LTR; + static EIGEN_CONSTEXPR bool BC = BC_; +}; + +template +struct PartialReducerLauncher { + typedef typename Self::EvaluatorPointerType EvaluatorPointerType; + typedef typename Self::CoeffReturnType CoeffReturnType; + typedef typename Self::Storage Storage; + typedef typename Self::Index Index; + typedef ReductionPannel + PannelParameters; + + typedef PartialReductionKernel SyclReducerKerneType; + + static bool run(const Self &self, const Op &reducer, const Eigen::SyclDevice &dev, EvaluatorPointerType output, + Index num_coeffs_to_reduce, Index num_coeffs_to_preserve) { + Index roundUpP = roundUp(num_coeffs_to_preserve, PannelParameters::LocalThreadSizeP); + + // getPowerOfTwo makes sure local range is power of 2 and <= + // maxSyclThreadPerBlock this will help us to avoid extra check on the + // kernel + static_assert(!((PannelParameters::LocalThreadSizeP * PannelParameters::LocalThreadSizeR) & + (PannelParameters::LocalThreadSizeP * PannelParameters::LocalThreadSizeR - 1)), + "The Local thread size must be a power of 2 for the reduction " + "operation"); + + EIGEN_CONSTEXPR Index localRange = PannelParameters::LocalThreadSizeP * PannelParameters::LocalThreadSizeR; + // In this step, we force the code not to be more than 2-step reduction: + // Our empirical research shows that if each thread reduces at least 64 + // elemnts individually, we get better performance. However, this can change + // on different platforms. In this step we force the code not to be + // morthan step reduction: Our empirical research shows that for inner_most + // dim reducer, it is better to have 8 group in a reduce dimension for sizes + // > 1024 to achieve the best performance. + const Index reductionPerThread = 64; + Index cu = dev.getPowerOfTwo(dev.getNumSyclMultiProcessors(), true); + const Index pNumGroups = roundUpP / PannelParameters::LocalThreadSizeP; + Index rGroups = (cu + pNumGroups - 1) / pNumGroups; + const Index rNumGroups = num_coeffs_to_reduce > reductionPerThread * localRange ? std::min(rGroups, localRange) : 1; + const Index globalRange = pNumGroups * rNumGroups * localRange; + + EIGEN_CONSTEXPR Index scratchSize = + PannelParameters::LocalThreadSizeR * (PannelParameters::LocalThreadSizeP + PannelParameters::BC); + auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(globalRange), cl::sycl::range<1>(localRange)); + if (rNumGroups > 1) { + CoeffReturnType *temp_pointer = static_cast( + dev.allocate_temp(num_coeffs_to_preserve * rNumGroups * sizeof(CoeffReturnType))); + EvaluatorPointerType temp_accessor = dev.get(temp_pointer); + dev.template unary_kernel_launcher( + self, temp_accessor, thread_range, scratchSize, reducer, pNumGroups, rNumGroups, num_coeffs_to_preserve, + num_coeffs_to_reduce).wait(); + typedef SecondStepPartialReduction + SecondStepPartialReductionKernel; + dev.template unary_kernel_launcher( + temp_accessor, output, + cl::sycl::nd_range<1>(cl::sycl::range<1>(pNumGroups * localRange), cl::sycl::range<1>(localRange)), Index(1), + reducer, num_coeffs_to_preserve, rNumGroups).wait(); + self.device().deallocate_temp(temp_pointer); + } else { + dev.template unary_kernel_launcher( + self, output, thread_range, scratchSize, reducer, pNumGroups, rNumGroups, num_coeffs_to_preserve, + num_coeffs_to_reduce).wait(); + } + return false; + } +}; +} // namespace internal +} // namespace TensorSycl + +namespace internal { + +template +struct FullReducer { + typedef typename Self::CoeffReturnType CoeffReturnType; + typedef typename Self::EvaluatorPointerType EvaluatorPointerType; + static EIGEN_CONSTEXPR bool HasOptimizedImplementation = true; + static EIGEN_CONSTEXPR int PacketSize = Self::PacketAccess ? Self::PacketSize : 1; + static void run(const Self &self, Op &reducer, const Eigen::SyclDevice &dev, EvaluatorPointerType data) { + typedef std::conditional_t OutType; + static_assert(!((EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1) & + (EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1 - 1)), + "The Local thread size must be a power of 2 for the reduction " + "operation"); + EIGEN_CONSTEXPR Index local_range = EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1; + + typename Self::Index inputSize = self.impl().dimensions().TotalSize(); + // In this step we force the code not to be more than 2-step reduction: + // Our empirical research shows that if each thread reduces at least 512 + // elemnts individually, we get better performance. + const Index reductionPerThread = 2048; + // const Index num_work_group = + Index reductionGroup = dev.getPowerOfTwo( + (inputSize + (reductionPerThread * local_range - 1)) / (reductionPerThread * local_range), true); + const Index num_work_group = std::min(reductionGroup, local_range); + // 1 + // ? local_range + // : 1); + const Index global_range = num_work_group * local_range; + + auto thread_range = cl::sycl::nd_range<1>(cl::sycl::range<1>(global_range), cl::sycl::range<1>(local_range)); + typedef TensorSycl::internal::FullReductionKernelFunctor reduction_kernel_t; + if (num_work_group > 1) { + CoeffReturnType *temp_pointer = + static_cast(dev.allocate_temp(num_work_group * sizeof(CoeffReturnType))); + typename Self::EvaluatorPointerType tmp_global_accessor = dev.get(temp_pointer); + dev.template unary_kernel_launcher(self, tmp_global_accessor, thread_range, + local_range, inputSize, reducer).wait(); + typedef TensorSycl::internal::SecondStepFullReducer + GenericRKernel; + dev.template unary_kernel_launcher( + tmp_global_accessor, data, + cl::sycl::nd_range<1>(cl::sycl::range<1>(num_work_group), cl::sycl::range<1>(num_work_group)), num_work_group, + reducer).wait(); + dev.deallocate_temp(temp_pointer); + } else { + dev.template unary_kernel_launcher(self, data, thread_range, local_range, inputSize, + reducer).wait(); + + } + } +}; +// vectorizable inner_most most dim preserver +// col reduction +template +struct OuterReducer { + static EIGEN_CONSTEXPR bool HasOptimizedImplementation = true; + + static bool run(const Self &self, const Op &reducer, const Eigen::SyclDevice &dev, + typename Self::EvaluatorPointerType output, typename Self::Index num_coeffs_to_reduce, + typename Self::Index num_coeffs_to_preserve) { + return ::Eigen::TensorSycl::internal::PartialReducerLauncher< + Self, Op, ::Eigen::TensorSycl::internal::reduction_dim::outer_most>::run(self, reducer, dev, output, + num_coeffs_to_reduce, + num_coeffs_to_preserve); + } +}; +// row reduction +template +struct InnerReducer { + static EIGEN_CONSTEXPR bool HasOptimizedImplementation = true; + + static bool run(const Self &self, const Op &reducer, const Eigen::SyclDevice &dev, + typename Self::EvaluatorPointerType output, typename Self::Index num_coeffs_to_reduce, + typename Self::Index num_coeffs_to_preserve) { + return ::Eigen::TensorSycl::internal::PartialReducerLauncher< + Self, Op, ::Eigen::TensorSycl::internal::reduction_dim::inner_most>::run(self, reducer, dev, output, + num_coeffs_to_reduce, + num_coeffs_to_preserve); + } +}; + +// ArmgMax uses this kernel for partial reduction// +// TODO(@mehdi.goli) come up with a better kernel +// generic partial reduction +template +struct GenericReducer { + static EIGEN_CONSTEXPR bool HasOptimizedImplementation = false; + static bool run(const Self &self, const Op &reducer, const Eigen::SyclDevice &dev, + typename Self::EvaluatorPointerType output, typename Self::Index num_values_to_reduce, + typename Self::Index num_coeffs_to_preserve) { + typename Self::Index range, GRange, tileSize; + dev.parallel_for_setup(num_coeffs_to_preserve, tileSize, range, GRange); + + dev.template unary_kernel_launcher>( + self, output, cl::sycl::nd_range<1>(cl::sycl::range<1>(GRange), cl::sycl::range<1>(tileSize)), Index(1), + reducer, range, (num_values_to_reduce != 0) ? num_values_to_reduce : static_cast(1)).wait(); + return false; + } +}; + +} // namespace internal +} // namespace Eigen + +#endif // UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_REDUCTION_SYCL_HPP diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRef.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRef.h new file mode 100644 index 0000000000000000000000000000000000000000..843cb9d6773a581251086d74e4d614e8de32ca14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorRef.h @@ -0,0 +1,376 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_REF_H +#define EIGEN_CXX11_TENSOR_TENSOR_REF_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +class TensorLazyBaseEvaluator { + public: + TensorLazyBaseEvaluator() : m_refcount(0) { } + virtual ~TensorLazyBaseEvaluator() { } + + EIGEN_DEVICE_FUNC virtual const Dimensions& dimensions() const = 0; + EIGEN_DEVICE_FUNC virtual const Scalar* data() const = 0; + + EIGEN_DEVICE_FUNC virtual const Scalar coeff(DenseIndex index) const = 0; + EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex index) = 0; + + void incrRefCount() { ++m_refcount; } + void decrRefCount() { --m_refcount; } + int refCount() const { return m_refcount; } + + private: + // No copy, no assignment; + TensorLazyBaseEvaluator(const TensorLazyBaseEvaluator& other); + TensorLazyBaseEvaluator& operator = (const TensorLazyBaseEvaluator& other); + + int m_refcount; +}; + + +template +class TensorLazyEvaluatorReadOnly : public TensorLazyBaseEvaluator::Scalar> { + public: + // typedef typename TensorEvaluator::Dimensions Dimensions; + typedef typename TensorEvaluator::Scalar Scalar; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + typedef TensorEvaluator EvalType; + + TensorLazyEvaluatorReadOnly(const Expr& expr, const Device& device) : m_impl(expr, device), m_dummy(Scalar(0)) { + m_dims = m_impl.dimensions(); + m_impl.evalSubExprsIfNeeded(NULL); + } + virtual ~TensorLazyEvaluatorReadOnly() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC virtual const Dimensions& dimensions() const { + return m_dims; + } + EIGEN_DEVICE_FUNC virtual const Scalar* data() const { + return m_impl.data(); + } + + EIGEN_DEVICE_FUNC virtual const Scalar coeff(DenseIndex index) const { + return m_impl.coeff(index); + } + EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex /*index*/) { + eigen_assert(false && "can't reference the coefficient of a rvalue"); + return m_dummy; + }; + + protected: + TensorEvaluator m_impl; + Dimensions m_dims; + Scalar m_dummy; +}; + +template +class TensorLazyEvaluatorWritable : public TensorLazyEvaluatorReadOnly { + public: + typedef TensorLazyEvaluatorReadOnly Base; + typedef typename Base::Scalar Scalar; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + TensorLazyEvaluatorWritable(const Expr& expr, const Device& device) : Base(expr, device) { + } + virtual ~TensorLazyEvaluatorWritable() { + } + + EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex index) { + return this->m_impl.coeffRef(index); + } +}; + +template +class TensorLazyEvaluator : public std::conditional_t::value), + TensorLazyEvaluatorWritable, + TensorLazyEvaluatorReadOnly > { + public: + typedef std::conditional_t::value), + TensorLazyEvaluatorWritable, + TensorLazyEvaluatorReadOnly > Base; + typedef typename Base::Scalar Scalar; + + TensorLazyEvaluator(const Expr& expr, const Device& device) : Base(expr, device) { + } + virtual ~TensorLazyEvaluator() { + } +}; + +} // namespace internal + + +/** \class TensorRef + * \ingroup CXX11_Tensor_Module + * + * \brief A reference to a tensor expression + * The expression will be evaluated lazily (as much as possible). + * + */ +template class TensorRef : public TensorBase > +{ + public: + typedef TensorRef Self; + typedef typename PlainObjectType::Base Base; + typedef typename Eigen::internal::nested::type Nested; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Index Index; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef typename Base::CoeffReturnType CoeffReturnType; + typedef Scalar* PointerType; + typedef PointerType PointerArgType; + + static constexpr Index NumIndices = PlainObjectType::NumIndices; + typedef typename PlainObjectType::Dimensions Dimensions; + + static constexpr int Layout = PlainObjectType::Layout; + enum { + IsAligned = false, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -----------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorRef() : m_evaluator(NULL) { + } + + template + EIGEN_STRONG_INLINE TensorRef(const Expression& expr) : m_evaluator(new internal::TensorLazyEvaluator(expr, DefaultDevice())) { + m_evaluator->incrRefCount(); + } + + template + EIGEN_STRONG_INLINE TensorRef& operator = (const Expression& expr) { + unrefEvaluator(); + m_evaluator = new internal::TensorLazyEvaluator(expr, DefaultDevice()); + m_evaluator->incrRefCount(); + return *this; + } + + ~TensorRef() { + unrefEvaluator(); + } + + TensorRef(const TensorRef& other) : TensorBase >(other), m_evaluator(other.m_evaluator) { + eigen_assert(m_evaluator->refCount() > 0); + m_evaluator->incrRefCount(); + } + + TensorRef& operator = (const TensorRef& other) { + if (this != &other) { + unrefEvaluator(); + m_evaluator = other.m_evaluator; + eigen_assert(m_evaluator->refCount() > 0); + m_evaluator->incrRefCount(); + } + return *this; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rank() const { return m_evaluator->dimensions().size(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index dimension(Index n) const { return m_evaluator->dimensions()[n]; } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_evaluator->dimensions(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index size() const { return m_evaluator->dimensions().TotalSize(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar* data() const { return m_evaluator->data(); } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar operator()(Index index) const + { + return m_evaluator->coeff(index); + } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar operator()(Index firstIndex, IndexTypes... otherIndices) const + { + const std::size_t num_indices = (sizeof...(otherIndices) + 1); + const array indices{{firstIndex, otherIndices...}}; + return coeff(indices); + } + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index firstIndex, IndexTypes... otherIndices) + { + const std::size_t num_indices = (sizeof...(otherIndices) + 1); + const array indices{{firstIndex, otherIndices...}}; + return coeffRef(indices); + } + + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar coeff(const array& indices) const + { + const Dimensions& dims = this->dimensions(); + Index index = 0; + if (PlainObjectType::Options & RowMajor) { + index += indices[0]; + for (size_t i = 1; i < NumIndices; ++i) { + index = index * dims[i] + indices[i]; + } + } else { + index += indices[NumIndices-1]; + for (int i = NumIndices-2; i >= 0; --i) { + index = index * dims[i] + indices[i]; + } + } + return m_evaluator->coeff(index); + } + template EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(const array& indices) + { + const Dimensions& dims = this->dimensions(); + Index index = 0; + if (PlainObjectType::Options & RowMajor) { + index += indices[0]; + for (size_t i = 1; i < NumIndices; ++i) { + index = index * dims[i] + indices[i]; + } + } else { + index += indices[NumIndices-1]; + for (int i = NumIndices-2; i >= 0; --i) { + index = index * dims[i] + indices[i]; + } + } + return m_evaluator->coeffRef(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar coeff(Index index) const + { + return m_evaluator->coeff(index); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) + { + return m_evaluator->coeffRef(index); + } + + private: + EIGEN_STRONG_INLINE void unrefEvaluator() { + if (m_evaluator) { + m_evaluator->decrRefCount(); + if (m_evaluator->refCount() == 0) { + delete m_evaluator; + } + } + } + + internal::TensorLazyBaseEvaluator* m_evaluator; +}; + + +// evaluator for rvalues +template +struct TensorEvaluator, Device> +{ + typedef typename Derived::Index Index; + typedef typename Derived::Scalar Scalar; + typedef typename Derived::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename Derived::Dimensions Dimensions; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorRef::Layout; + enum { + IsAligned = false, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const TensorRef& m, const Device&) + : m_ref(m) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_ref.dimensions(); } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { + return m_ref.coeff(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { + return m_ref.coeffRef(index); + } + + EIGEN_DEVICE_FUNC const Scalar* data() const { return m_ref.data(); } + + protected: + TensorRef m_ref; +}; + + +// evaluator for lvalues +template +struct TensorEvaluator, Device> : public TensorEvaluator, Device> +{ + typedef typename Derived::Index Index; + typedef typename Derived::Scalar Scalar; + typedef typename Derived::Scalar CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef typename Derived::Dimensions Dimensions; + + typedef TensorEvaluator, Device> Base; + + enum { + IsAligned = false, + PacketAccess = false, + BlockAccess = false, + PreferBlockAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(TensorRef& m, const Device& d) : Base(m, d) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { + return this->m_ref.coeffRef(index); + } +}; + + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_REF_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReverse.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReverse.h new file mode 100644 index 0000000000000000000000000000000000000000..ee84400e0b68a4d734d6cfb0d58b994c521e9d1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorReverse.h @@ -0,0 +1,458 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Navdeep Jaitly +// Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H +#define EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorReverse + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor reverse elements class. + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorReverseOp& type; +}; + +template +struct nested, 1, + typename eval >::type> +{ + typedef TensorReverseOp type; +}; + +} // end namespace internal + +template +class TensorReverseOp : public TensorBase, WriteAccessors> +{ + public: + typedef TensorBase, WriteAccessors>Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind + StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReverseOp( + const XprType& expr, const ReverseDimensions& reverse_dims) + : m_xpr(expr), m_reverse_dims(reverse_dims) { } + + EIGEN_DEVICE_FUNC + const ReverseDimensions& reverse() const { return m_reverse_dims; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorReverseOp) + + + protected: + typename XprType::Nested m_xpr; + const ReverseDimensions m_reverse_dims; +}; + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorReverseOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = NumDims > 0, + PreferBlockAccess = true, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + typedef internal::TensorIntDivisor IndexDivisor; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename TensorEvaluator::TensorBlock + ArgTensorBlock; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), + m_reverse(op.reverse()), + m_device(device) + { + // Reversing a scalar isn't supported yet. It would be a no-op anyway. + EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + + // Compute strides + m_dimensions = m_impl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_strides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_strides[i] = m_strides[i-1] * m_dimensions[i-1]; + if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]); + } + } else { + m_strides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_strides[i] = m_strides[i+1] * m_dimensions[i+1]; + if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]); + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index reverseIndex( + Index index) const { + eigen_assert(index < dimensions().TotalSize()); + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + Index idx = index / m_fastStrides[i]; + index -= idx * m_strides[i]; + if (m_reverse[i]) { + idx = m_dimensions[i] - idx - 1; + } + inputIndex += idx * m_strides[i] ; + } + if (m_reverse[0]) { + inputIndex += (m_dimensions[0] - index - 1); + } else { + inputIndex += index; + } + } else { + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + Index idx = index / m_fastStrides[i]; + index -= idx * m_strides[i]; + if (m_reverse[i]) { + idx = m_dimensions[i] - idx - 1; + } + inputIndex += idx * m_strides[i] ; + } + if (m_reverse[NumDims-1]) { + inputIndex += (m_dimensions[NumDims-1] - index - 1); + } else { + inputIndex += index; + } + } + return inputIndex; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff( + Index index) const { + return m_impl.coeff(reverseIndex(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + PacketReturnType packet(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + // TODO(ndjaitly): write a better packing routine that uses + // local structure. + EIGEN_ALIGN_MAX std::remove_const_t + values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + const size_t target_size = m_device.lastLevelCacheSize(); + // Block evaluation reads underlying memory in reverse order, and default + // cost model does not properly catch this in bytes stored/loaded. + return internal::TensorBlockResourceRequirements::skewed( + target_size) + .addCostPerCoeff({0, 0, 24}); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool /*root_of_expr_ast*/ = false) const { + // TODO(ezhulenev): If underlying tensor expression supports and prefers + // block evaluation we must use it. Currently we use coeff and packet + // access into the underlying tensor expression. + // static const bool useBlockAccessForArgType = + // TensorEvaluator::BlockAccess && + // TensorEvaluator::PreferBlockAccess; + + static const bool isColMajor = + static_cast(Layout) == static_cast(ColMajor); + + static const Index inner_dim_idx = isColMajor ? 0 : NumDims - 1; + const bool inner_dim_reversed = m_reverse[inner_dim_idx]; + + // Offset in the output block. + Index block_offset = 0; + + // Offset in the input Tensor. + Index input_offset = reverseIndex(desc.offset()); + + // Initialize output block iterator state. Dimension in this array are + // always in inner_most -> outer_most order (col major layout). + array it; + for (int i = 0; i < NumDims; ++i) { + const int dim = isColMajor ? i : NumDims - 1 - i; + it[i].size = desc.dimension(dim); + it[i].count = 0; + it[i].reverse = m_reverse[dim]; + + it[i].block_stride = + i == 0 ? 1 : (it[i - 1].size * it[i - 1].block_stride); + it[i].block_span = it[i].block_stride * (it[i].size - 1); + + it[i].input_stride = m_strides[dim]; + it[i].input_span = it[i].input_stride * (it[i].size - 1); + + if (it[i].reverse) { + it[i].input_stride = -1 * it[i].input_stride; + it[i].input_span = -1 * it[i].input_span; + } + } + + // If multiple inner dimensions have the same reverse flag, check if we can + // merge them into a single virtual inner dimension. + int effective_inner_dim = 0; + for (int i = 1; i < NumDims; ++i) { + if (it[i].reverse != it[effective_inner_dim].reverse) break; + if (it[i].block_stride != it[effective_inner_dim].size) break; + if (it[i].block_stride != numext::abs(it[i].input_stride)) break; + + it[i].size = it[effective_inner_dim].size * it[i].size; + + it[i].block_stride = 1; + it[i].input_stride = (inner_dim_reversed ? -1 : 1); + + it[i].block_span = it[i].block_stride * (it[i].size - 1); + it[i].input_span = it[i].input_stride * (it[i].size - 1); + + effective_inner_dim = i; + } + + eigen_assert(it[effective_inner_dim].block_stride == 1); + eigen_assert(it[effective_inner_dim].input_stride == + (inner_dim_reversed ? -1 : 1)); + + const Index inner_dim_size = it[effective_inner_dim].size; + + // Prepare storage for the materialized reverse result. + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage(desc, scratch); + CoeffReturnType* block_buffer = block_storage.data(); + + while (it[NumDims - 1].count < it[NumDims - 1].size) { + // Copy inner-most dimension data from reversed location in input. + Index dst = block_offset; + Index src = input_offset; + + // NOTE(ezhulenev): Adding vectorized path with internal::preverse showed + // worse results in benchmarks than a simple coefficient loop. + if (inner_dim_reversed) { + for (Index i = 0; i < inner_dim_size; ++i) { + block_buffer[dst] = m_impl.coeff(src); + ++dst; + --src; + } + } else { + for (Index i = 0; i < inner_dim_size; ++i) { + block_buffer[dst] = m_impl.coeff(src); + ++dst; + ++src; + } + } + + // For the 1d tensor we need to generate only one inner-most dimension. + if ((NumDims - effective_inner_dim) == 1) break; + + // Update offset. + for (Index i = effective_inner_dim + 1; i < NumDims; ++i) { + if (++it[i].count < it[i].size) { + block_offset += it[i].block_stride; + input_offset += it[i].input_stride; + break; + } + if (i != NumDims - 1) it[i].count = 0; + block_offset -= it[i].block_span; + input_offset -= it[i].input_span; + } + } + + return block_storage.AsTensorMaterializedBlock(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + double compute_cost = NumDims * (2 * TensorOpCost::AddCost() + + 2 * TensorOpCost::MulCost() + + TensorOpCost::DivCost()); + for (int i = 0; i < NumDims; ++i) { + if (m_reverse[i]) { + compute_cost += 2 * TensorOpCost::AddCost(); + } + } + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost, false /* vectorized */, PacketSize); + } + + EIGEN_DEVICE_FUNC typename Storage::Type data() const { return NULL; } + + protected: + Dimensions m_dimensions; + array m_strides; + array m_fastStrides; + TensorEvaluator m_impl; + ReverseDimensions m_reverse; + const Device EIGEN_DEVICE_REF m_device; + + private: + struct BlockIteratorState { + BlockIteratorState() + : size(0), + count(0), + reverse(false), + block_stride(0), + block_span(0), + input_stride(0), + input_span(0) {} + + Index size; + Index count; + bool reverse; + Index block_stride; + Index block_span; + Index input_stride; + Index input_span; + }; +}; + +// Eval as lvalue + +template +struct TensorEvaluator, Device> + : public TensorEvaluator, + Device> { + typedef TensorEvaluator, + Device> Base; + typedef TensorReverseOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::value; + typedef DSizes Dimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) {} + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Dimensions& dimensions() const { return this->m_dimensions; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const { + return this->m_impl.coeffRef(this->reverseIndex(index)); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + // This code is pilfered from TensorMorphing.h + EIGEN_ALIGN_MAX CoeffReturnType values[PacketSize]; + internal::pstore(values, x); + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + this->coeffRef(index+i) = values[i]; + } + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScan.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScan.h new file mode 100644 index 0000000000000000000000000000000000000000..9d9458a5204656c1011aedc4d088d4243b535bfc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScan.h @@ -0,0 +1,523 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Igor Babuschkin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_SCAN_H +#define EIGEN_CXX11_TENSOR_TENSOR_SCAN_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +struct traits > + : public traits { + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorScanOp& type; +}; + +template +struct nested, 1, + typename eval >::type> +{ + typedef TensorScanOp type; +}; +} // end namespace internal + +/** \class TensorScan + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor scan class. + */ +template +class TensorScanOp + : public TensorBase, ReadOnlyAccessors> { +public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorScanOp( + const XprType& expr, const Index& axis, bool exclusive = false, const Op& op = Op()) + : m_expr(expr), m_axis(axis), m_accumulator(op), m_exclusive(exclusive) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Index axis() const { return m_axis; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const XprType& expression() const { return m_expr; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Op accumulator() const { return m_accumulator; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + bool exclusive() const { return m_exclusive; } + +protected: + typename XprType::Nested m_expr; + const Index m_axis; + const Op m_accumulator; + const bool m_exclusive; +}; + + +namespace internal { + +template +EIGEN_STRONG_INLINE void ReduceScalar(Self& self, Index offset, + typename Self::CoeffReturnType* data) { + // Compute the scan along the axis, starting at the given offset + typename Self::CoeffReturnType accum = self.accumulator().initialize(); + if (self.stride() == 1) { + if (self.exclusive()) { + for (Index curr = offset; curr < offset + self.size(); ++curr) { + data[curr] = self.accumulator().finalize(accum); + self.accumulator().reduce(self.inner().coeff(curr), &accum); + } + } else { + for (Index curr = offset; curr < offset + self.size(); ++curr) { + self.accumulator().reduce(self.inner().coeff(curr), &accum); + data[curr] = self.accumulator().finalize(accum); + } + } + } else { + if (self.exclusive()) { + for (Index idx3 = 0; idx3 < self.size(); idx3++) { + Index curr = offset + idx3 * self.stride(); + data[curr] = self.accumulator().finalize(accum); + self.accumulator().reduce(self.inner().coeff(curr), &accum); + } + } else { + for (Index idx3 = 0; idx3 < self.size(); idx3++) { + Index curr = offset + idx3 * self.stride(); + self.accumulator().reduce(self.inner().coeff(curr), &accum); + data[curr] = self.accumulator().finalize(accum); + } + } + } +} + +template +EIGEN_STRONG_INLINE void ReducePacket(Self& self, Index offset, + typename Self::CoeffReturnType* data) { + using Scalar = typename Self::CoeffReturnType; + using Packet = typename Self::PacketReturnType; + // Compute the scan along the axis, starting at the calculated offset + Packet accum = self.accumulator().template initializePacket(); + if (self.stride() == 1) { + if (self.exclusive()) { + for (Index curr = offset; curr < offset + self.size(); ++curr) { + internal::pstoreu(data + curr, self.accumulator().finalizePacket(accum)); + self.accumulator().reducePacket(self.inner().template packet(curr), &accum); + } + } else { + for (Index curr = offset; curr < offset + self.size(); ++curr) { + self.accumulator().reducePacket(self.inner().template packet(curr), &accum); + internal::pstoreu(data + curr, self.accumulator().finalizePacket(accum)); + } + } + } else { + if (self.exclusive()) { + for (Index idx3 = 0; idx3 < self.size(); idx3++) { + const Index curr = offset + idx3 * self.stride(); + internal::pstoreu(data + curr, self.accumulator().finalizePacket(accum)); + self.accumulator().reducePacket(self.inner().template packet(curr), &accum); + } + } else { + for (Index idx3 = 0; idx3 < self.size(); idx3++) { + const Index curr = offset + idx3 * self.stride(); + self.accumulator().reducePacket(self.inner().template packet(curr), &accum); + internal::pstoreu(data + curr, self.accumulator().finalizePacket(accum)); + } + } + } +} + +template +struct ReduceBlock { + EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, + typename Self::CoeffReturnType* data) { + for (Index idx2 = 0; idx2 < self.stride(); idx2++) { + // Calculate the starting offset for the scan + Index offset = idx1 + idx2; + ReduceScalar(self, offset, data); + } + } +}; + +// Specialization for vectorized reduction. +template +struct ReduceBlock { + EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, + typename Self::CoeffReturnType* data) { + using Packet = typename Self::PacketReturnType; + const int PacketSize = internal::unpacket_traits::size; + Index idx2 = 0; + for (; idx2 + PacketSize <= self.stride(); idx2 += PacketSize) { + // Calculate the starting offset for the packet scan + Index offset = idx1 + idx2; + ReducePacket(self, offset, data); + } + for (; idx2 < self.stride(); idx2++) { + // Calculate the starting offset for the scan + Index offset = idx1 + idx2; + ReduceScalar(self, offset, data); + } + } +}; + +// Single-threaded CPU implementation of scan +template ::PacketAccess && + internal::reducer_traits::PacketAccess)> +struct ScanLauncher { + void operator()(Self& self, typename Self::CoeffReturnType* data) const { + Index total_size = internal::array_prod(self.dimensions()); + + // We fix the index along the scan axis to 0 and perform a + // scan per remaining entry. The iteration is split into two nested + // loops to avoid an integer division by keeping track of each idx1 and + // idx2. + for (Index idx1 = 0; idx1 < total_size; idx1 += self.stride() * self.size()) { + ReduceBlock block_reducer; + block_reducer(self, idx1, data); + } + } +}; + +#ifdef EIGEN_USE_THREADS + +// Adjust block_size to avoid false sharing of cachelines among +// threads. Currently set to twice the cache line size on Intel and ARM +// processors. +EIGEN_STRONG_INLINE Index AdjustBlockSize(Index item_size, Index block_size) { + EIGEN_CONSTEXPR Index kBlockAlignment = 128; + const Index items_per_cacheline = + numext::maxi(1, kBlockAlignment / item_size); + return items_per_cacheline * divup(block_size, items_per_cacheline); +} + +template +struct ReduceBlock { + EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, + typename Self::CoeffReturnType* data) { + using Scalar = typename Self::CoeffReturnType; + using Packet = typename Self::PacketReturnType; + const int PacketSize = internal::unpacket_traits::size; + Index num_scalars = self.stride(); + Index num_packets = 0; + if (self.stride() >= PacketSize) { + num_packets = self.stride() / PacketSize; + self.device().parallelFor( + num_packets, + TensorOpCost(PacketSize * self.size(), PacketSize * self.size(), + 16 * PacketSize * self.size(), true, PacketSize), + // Make the shard size large enough that two neighboring threads + // won't write to the same cacheline of `data`. + [=](Index blk_size) { + return AdjustBlockSize(PacketSize * sizeof(Scalar), blk_size); + }, + [&](Index first, Index last) { + for (Index packet = first; packet < last; ++packet) { + const Index idx2 = packet * PacketSize; + ReducePacket(self, idx1 + idx2, data); + } + }); + num_scalars -= num_packets * PacketSize; + } + self.device().parallelFor( + num_scalars, TensorOpCost(self.size(), self.size(), 16 * self.size()), + // Make the shard size large enough that two neighboring threads + // won't write to the same cacheline of `data`. + [=](Index blk_size) { + return AdjustBlockSize(sizeof(Scalar), blk_size); + }, + [&](Index first, Index last) { + for (Index scalar = first; scalar < last; ++scalar) { + const Index idx2 = num_packets * PacketSize + scalar; + ReduceScalar(self, idx1 + idx2, data); + } + }); + } +}; + +template +struct ReduceBlock { + EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, + typename Self::CoeffReturnType* data) { + using Scalar = typename Self::CoeffReturnType; + self.device().parallelFor( + self.stride(), TensorOpCost(self.size(), self.size(), 16 * self.size()), + // Make the shard size large enough that two neighboring threads + // won't write to the same cacheline of `data`. + [=](Index blk_size) { + return AdjustBlockSize(sizeof(Scalar), blk_size); + }, + [&](Index first, Index last) { + for (Index idx2 = first; idx2 < last; ++idx2) { + ReduceScalar(self, idx1 + idx2, data); + } + }); + } +}; + +// Specialization for multi-threaded execution. +template +struct ScanLauncher { + void operator()(Self& self, typename Self::CoeffReturnType* data) { + using Scalar = typename Self::CoeffReturnType; + using Packet = typename Self::PacketReturnType; + const int PacketSize = internal::unpacket_traits::size; + const Index total_size = internal::array_prod(self.dimensions()); + const Index inner_block_size = self.stride() * self.size(); + bool parallelize_by_outer_blocks = (total_size >= (self.stride() * inner_block_size)); + + if ((parallelize_by_outer_blocks && total_size <= 4096) || + (!parallelize_by_outer_blocks && self.stride() < PacketSize)) { + ScanLauncher launcher; + launcher(self, data); + return; + } + + if (parallelize_by_outer_blocks) { + // Parallelize over outer blocks. + const Index num_outer_blocks = total_size / inner_block_size; + self.device().parallelFor( + num_outer_blocks, + TensorOpCost(inner_block_size, inner_block_size, + 16 * PacketSize * inner_block_size, Vectorize, + PacketSize), + [=](Index blk_size) { + return AdjustBlockSize(inner_block_size * sizeof(Scalar), blk_size); + }, + [&](Index first, Index last) { + for (Index idx1 = first; idx1 < last; ++idx1) { + ReduceBlock block_reducer; + block_reducer(self, idx1 * inner_block_size, data); + } + }); + } else { + // Parallelize over inner packets/scalars dimensions when the reduction + // axis is not an inner dimension. + ReduceBlock block_reducer; + for (Index idx1 = 0; idx1 < total_size; + idx1 += self.stride() * self.size()) { + block_reducer(self, idx1, data); + } + } + } +}; +#endif // EIGEN_USE_THREADS + +#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC)) + +// GPU implementation of scan +// TODO(ibab) This placeholder implementation performs multiple scans in +// parallel, but it would be better to use a parallel scan algorithm and +// optimize memory access. +template +__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ScanKernel(Self self, Index total_size, typename Self::CoeffReturnType* data) { + // Compute offset as in the CPU version + Index val = threadIdx.x + blockIdx.x * blockDim.x; + Index offset = (val / self.stride()) * self.stride() * self.size() + val % self.stride(); + + if (offset + (self.size() - 1) * self.stride() < total_size) { + // Compute the scan along the axis, starting at the calculated offset + typename Self::CoeffReturnType accum = self.accumulator().initialize(); + for (Index idx = 0; idx < self.size(); idx++) { + Index curr = offset + idx * self.stride(); + if (self.exclusive()) { + data[curr] = self.accumulator().finalize(accum); + self.accumulator().reduce(self.inner().coeff(curr), &accum); + } else { + self.accumulator().reduce(self.inner().coeff(curr), &accum); + data[curr] = self.accumulator().finalize(accum); + } + } + } + __syncthreads(); + +} + +template +struct ScanLauncher { + void operator()(const Self& self, typename Self::CoeffReturnType* data) { + Index total_size = internal::array_prod(self.dimensions()); + Index num_blocks = (total_size / self.size() + 63) / 64; + Index block_size = 64; + + LAUNCH_GPU_KERNEL((ScanKernel), num_blocks, block_size, 0, self.device(), self, total_size, data); + } +}; +#endif // EIGEN_USE_GPU && (EIGEN_GPUCC) + +} // namespace internal + +// Eval as rvalue +template +struct TensorEvaluator, Device> { + + typedef TensorScanOp XprType; + typedef typename XprType::Index Index; + typedef const ArgType ChildTypeNoConst; + typedef const ArgType ChildType; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef std::remove_const_t Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + typedef TensorEvaluator, Device> Self; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = false, + PreferBlockAccess = false, + CoordAccess = false, + RawAccess = true + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), + m_device(device), + m_exclusive(op.exclusive()), + m_accumulator(op.accumulator()), + m_size(m_impl.dimensions()[op.axis()]), + m_stride(1), m_consume_dim(op.axis()), + m_output(NULL) { + + // Accumulating a scalar isn't supported. + EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + eigen_assert(op.axis() >= 0 && op.axis() < NumDims); + + // Compute stride of scan axis + const Dimensions& dims = m_impl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = 0; i < op.axis(); ++i) { + m_stride = m_stride * dims[i]; + } + } else { + // dims can only be indexed through unsigned integers, + // so let's use an unsigned type to let the compiler knows. + // This prevents stupid warnings: ""'*((void*)(& evaluator)+64)[18446744073709551615]' may be used uninitialized in this function" + unsigned int axis = internal::convert_index(op.axis()); + for (unsigned int i = NumDims - 1; i > axis; --i) { + m_stride = m_stride * dims[i]; + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { + return m_impl.dimensions(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& stride() const { + return m_stride; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& consume_dim() const { + return m_consume_dim; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& size() const { + return m_size; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Op& accumulator() const { + return m_accumulator; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool exclusive() const { + return m_exclusive; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const TensorEvaluator& inner() const { + return m_impl; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Device& device() const { + return m_device; + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { + m_impl.evalSubExprsIfNeeded(NULL); + internal::ScanLauncher launcher; + if (data) { + launcher(*this, data); + return false; + } + + const Index total_size = internal::array_prod(dimensions()); + m_output = static_cast(m_device.get((Scalar*) m_device.allocate_temp(total_size * sizeof(Scalar)))); + launcher(*this, m_output); + return true; + } + + template + EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const { + return internal::ploadt(m_output + index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const + { + return m_output; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_output[index]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool) const { + return TensorOpCost(sizeof(CoeffReturnType), 0, 0); + } + + EIGEN_STRONG_INLINE void cleanup() { + if (m_output) { + m_device.deallocate_temp(m_output); + m_output = NULL; + } + m_impl.cleanup(); + } + +protected: + TensorEvaluator m_impl; + const Device EIGEN_DEVICE_REF m_device; + const bool m_exclusive; + Op m_accumulator; + const Index m_size; + Index m_stride; + Index m_consume_dim; + EvaluatorPointerType m_output; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_SCAN_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScanSycl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScanSycl.h new file mode 100644 index 0000000000000000000000000000000000000000..155cc0fdc4e3076bb0f225da7552fbdf6f8c56cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorScanSycl.h @@ -0,0 +1,511 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Mehdi Goli Codeplay Software Ltd. +// Ralph Potter Codeplay Software Ltd. +// Luke Iwanski Codeplay Software Ltd. +// Contact: +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/***************************************************************** + * TensorScanSycl.h + * + * \brief: + * Tensor Scan Sycl implement the extend version of + * "Efficient parallel scan algorithms for GPUs." .for Tensor operations. + * The algorithm requires up to 3 stage (consequently 3 kernels) depending on + * the size of the tensor. In the first kernel (ScanKernelFunctor), each + * threads within the work-group individually reduces the allocated elements per + * thread in order to reduces the total number of blocks. In the next step all + * thread within the work-group will reduce the associated blocks into the + * temporary buffers. In the next kernel(ScanBlockKernelFunctor), the temporary + * buffer is given as an input and all the threads within a work-group scan and + * reduces the boundaries between the blocks (generated from the previous + * kernel). and write the data on the temporary buffer. If the second kernel is + * required, the third and final kernel (ScanAdjustmentKernelFunctor) will + * adjust the final result into the output buffer. + * The original algorithm for the parallel prefix sum can be found here: + * + * Sengupta, Shubhabrata, Mark Harris, and Michael Garland. "Efficient parallel + * scan algorithms for GPUs." NVIDIA, Santa Clara, CA, Tech. Rep. NVR-2008-003 + *1, no. 1 (2008): 1-17. + *****************************************************************/ + +#ifndef UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_SYCL_SYCL_HPP +#define UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_SYCL_SYCL_HPP + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace TensorSycl { +namespace internal { + +#ifndef EIGEN_SYCL_MAX_GLOBAL_RANGE +#define EIGEN_SYCL_MAX_GLOBAL_RANGE (EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1 * 4) +#endif + +template +struct ScanParameters { + // must be power of 2 + static EIGEN_CONSTEXPR index_t ScanPerThread = 8; + const index_t total_size; + const index_t non_scan_size; + const index_t scan_size; + const index_t non_scan_stride; + const index_t scan_stride; + const index_t panel_threads; + const index_t group_threads; + const index_t block_threads; + const index_t elements_per_group; + const index_t elements_per_block; + const index_t loop_range; + + ScanParameters(index_t total_size_, index_t non_scan_size_, index_t scan_size_, index_t non_scan_stride_, + index_t scan_stride_, index_t panel_threads_, index_t group_threads_, index_t block_threads_, + index_t elements_per_group_, index_t elements_per_block_, index_t loop_range_) + : total_size(total_size_), + non_scan_size(non_scan_size_), + scan_size(scan_size_), + non_scan_stride(non_scan_stride_), + scan_stride(scan_stride_), + panel_threads(panel_threads_), + group_threads(group_threads_), + block_threads(block_threads_), + elements_per_group(elements_per_group_), + elements_per_block(elements_per_block_), + loop_range(loop_range_) {} +}; + +enum class scan_step { first, second }; +template +struct ScanKernelFunctor { + typedef cl::sycl::accessor + LocalAccessor; + static EIGEN_CONSTEXPR int PacketSize = ScanParameters::ScanPerThread / 2; + + LocalAccessor scratch; + Evaluator dev_eval; + OutAccessor out_ptr; + OutAccessor tmp_ptr; + const ScanParameters scanParameters; + Op accumulator; + const bool inclusive; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ScanKernelFunctor(LocalAccessor scratch_, const Evaluator dev_eval_, + OutAccessor out_accessor_, OutAccessor temp_accessor_, + const ScanParameters scanParameters_, Op accumulator_, + const bool inclusive_) + : scratch(scratch_), + dev_eval(dev_eval_), + out_ptr(out_accessor_), + tmp_ptr(temp_accessor_), + scanParameters(scanParameters_), + accumulator(accumulator_), + inclusive(inclusive_) {} + + template + std::enable_if_t EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE + read(const Input &inpt, Index global_id) const { + return inpt.coeff(global_id); + } + + template + std::enable_if_t EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE + read(const Input &inpt, Index global_id) const { + return inpt[global_id]; + } + + template + std::enable_if_t EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + first_step_inclusive_Operation(InclusiveOp inclusive_op) const { + inclusive_op(); + } + + template + std::enable_if_t EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + first_step_inclusive_Operation(InclusiveOp) const {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + + + for (Index loop_offset = 0; loop_offset < scanParameters.loop_range; loop_offset++) { + Index data_offset = (itemID.get_global_id(0) + (itemID.get_global_range(0) * loop_offset)); + Index tmp = data_offset % scanParameters.panel_threads; + const Index panel_id = data_offset / scanParameters.panel_threads; + const Index group_id = tmp / scanParameters.group_threads; + tmp = tmp % scanParameters.group_threads; + const Index block_id = tmp / scanParameters.block_threads; + const Index local_id = tmp % scanParameters.block_threads; + // we put one element per packet in scratch_mem + const Index scratch_stride = scanParameters.elements_per_block / PacketSize; + const Index scratch_offset = (itemID.get_local_id(0) / scanParameters.block_threads) * scratch_stride; + CoeffReturnType private_scan[ScanParameters::ScanPerThread]; + CoeffReturnType inclusive_scan; + // the actual panel size is scan_size * non_scan_size. + // elements_per_panel is roundup to power of 2 for binary tree + const Index panel_offset = panel_id * scanParameters.scan_size * scanParameters.non_scan_size; + const Index group_offset = group_id * scanParameters.non_scan_stride; + // This will be effective when the size is bigger than elements_per_block + const Index block_offset = block_id * scanParameters.elements_per_block * scanParameters.scan_stride; + const Index thread_offset = (ScanParameters::ScanPerThread * local_id * scanParameters.scan_stride); + const Index global_offset = panel_offset + group_offset + block_offset + thread_offset; + Index next_elements = 0; + EIGEN_UNROLL_LOOP + for (int i = 0; i < ScanParameters::ScanPerThread; i++) { + Index global_id = global_offset + next_elements; + private_scan[i] = ((((block_id * scanParameters.elements_per_block) + + (ScanParameters::ScanPerThread * local_id) + i) < scanParameters.scan_size) && + (global_id < scanParameters.total_size)) + ? read(dev_eval, global_id) + : accumulator.initialize(); + next_elements += scanParameters.scan_stride; + } + first_step_inclusive_Operation([&]() EIGEN_DEVICE_FUNC { + if (inclusive) { + inclusive_scan = private_scan[ScanParameters::ScanPerThread - 1]; + } + }); + // This for loop must be 2 + EIGEN_UNROLL_LOOP + for (int packetIndex = 0; packetIndex < ScanParameters::ScanPerThread; packetIndex += PacketSize) { + Index private_offset = 1; + // build sum in place up the tree + EIGEN_UNROLL_LOOP + for (Index d = PacketSize >> 1; d > 0; d >>= 1) { + EIGEN_UNROLL_LOOP + for (Index l = 0; l < d; l++) { + Index ai = private_offset * (2 * l + 1) - 1 + packetIndex; + Index bi = private_offset * (2 * l + 2) - 1 + packetIndex; + CoeffReturnType accum = accumulator.initialize(); + accumulator.reduce(private_scan[ai], &accum); + accumulator.reduce(private_scan[bi], &accum); + private_scan[bi] = accumulator.finalize(accum); + } + private_offset *= 2; + } + scratch[2 * local_id + (packetIndex / PacketSize) + scratch_offset] = + private_scan[PacketSize - 1 + packetIndex]; + private_scan[PacketSize - 1 + packetIndex] = accumulator.initialize(); + // traverse down tree & build scan + EIGEN_UNROLL_LOOP + for (Index d = 1; d < PacketSize; d *= 2) { + private_offset >>= 1; + EIGEN_UNROLL_LOOP + for (Index l = 0; l < d; l++) { + Index ai = private_offset * (2 * l + 1) - 1 + packetIndex; + Index bi = private_offset * (2 * l + 2) - 1 + packetIndex; + CoeffReturnType accum = accumulator.initialize(); + accumulator.reduce(private_scan[ai], &accum); + accumulator.reduce(private_scan[bi], &accum); + private_scan[ai] = private_scan[bi]; + private_scan[bi] = accumulator.finalize(accum); + } + } + } + + Index offset = 1; + // build sum in place up the tree + for (Index d = scratch_stride >> 1; d > 0; d >>= 1) { + // Synchronise + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (local_id < d) { + Index ai = offset * (2 * local_id + 1) - 1 + scratch_offset; + Index bi = offset * (2 * local_id + 2) - 1 + scratch_offset; + CoeffReturnType accum = accumulator.initialize(); + accumulator.reduce(scratch[ai], &accum); + accumulator.reduce(scratch[bi], &accum); + scratch[bi] = accumulator.finalize(accum); + } + offset *= 2; + } + // Synchronise + itemID.barrier(cl::sycl::access::fence_space::local_space); + // next step optimisation + if (local_id == 0) { + if (((scanParameters.elements_per_group / scanParameters.elements_per_block) > 1)) { + const Index temp_id = panel_id * (scanParameters.elements_per_group / scanParameters.elements_per_block) * + scanParameters.non_scan_size + + group_id * (scanParameters.elements_per_group / scanParameters.elements_per_block) + + block_id; + tmp_ptr[temp_id] = scratch[scratch_stride - 1 + scratch_offset]; + } + // clear the last element + scratch[scratch_stride - 1 + scratch_offset] = accumulator.initialize(); + } + // traverse down tree & build scan + for (Index d = 1; d < scratch_stride; d *= 2) { + offset >>= 1; + // Synchronise + itemID.barrier(cl::sycl::access::fence_space::local_space); + if (local_id < d) { + Index ai = offset * (2 * local_id + 1) - 1 + scratch_offset; + Index bi = offset * (2 * local_id + 2) - 1 + scratch_offset; + CoeffReturnType accum = accumulator.initialize(); + accumulator.reduce(scratch[ai], &accum); + accumulator.reduce(scratch[bi], &accum); + scratch[ai] = scratch[bi]; + scratch[bi] = accumulator.finalize(accum); + } + } + // Synchronise + itemID.barrier(cl::sycl::access::fence_space::local_space); + // This for loop must be 2 + EIGEN_UNROLL_LOOP + for (int packetIndex = 0; packetIndex < ScanParameters::ScanPerThread; packetIndex += PacketSize) { + EIGEN_UNROLL_LOOP + for (Index i = 0; i < PacketSize; i++) { + CoeffReturnType accum = private_scan[packetIndex + i]; + accumulator.reduce(scratch[2 * local_id + (packetIndex / PacketSize) + scratch_offset], &accum); + private_scan[packetIndex + i] = accumulator.finalize(accum); + } + } + first_step_inclusive_Operation([&]() EIGEN_DEVICE_FUNC { + if (inclusive) { + accumulator.reduce(private_scan[ScanParameters::ScanPerThread - 1], &inclusive_scan); + private_scan[0] = accumulator.finalize(inclusive_scan); + } + }); + next_elements = 0; + // right the first set of private param + EIGEN_UNROLL_LOOP + for (Index i = 0; i < ScanParameters::ScanPerThread; i++) { + Index global_id = global_offset + next_elements; + if ((((block_id * scanParameters.elements_per_block) + (ScanParameters::ScanPerThread * local_id) + i) < + scanParameters.scan_size) && + (global_id < scanParameters.total_size)) { + Index private_id = (i * !inclusive) + (((i + 1) % ScanParameters::ScanPerThread) * (inclusive)); + out_ptr[global_id] = private_scan[private_id]; + } + next_elements += scanParameters.scan_stride; + } + } // end for loop + } +}; + +template +struct ScanAdjustmentKernelFunctor { + typedef cl::sycl::accessor + LocalAccessor; + static EIGEN_CONSTEXPR int PacketSize = ScanParameters::ScanPerThread / 2; + InAccessor in_ptr; + OutAccessor out_ptr; + const ScanParameters scanParameters; + Op accumulator; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ScanAdjustmentKernelFunctor(LocalAccessor, InAccessor in_accessor_, + OutAccessor out_accessor_, + const ScanParameters scanParameters_, + Op accumulator_) + : in_ptr(in_accessor_), + out_ptr(out_accessor_), + scanParameters(scanParameters_), + accumulator(accumulator_) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void operator()(cl::sycl::nd_item<1> itemID) const { + + for (Index loop_offset = 0; loop_offset < scanParameters.loop_range; loop_offset++) { + Index data_offset = (itemID.get_global_id(0) + (itemID.get_global_range(0) * loop_offset)); + Index tmp = data_offset % scanParameters.panel_threads; + const Index panel_id = data_offset / scanParameters.panel_threads; + const Index group_id = tmp / scanParameters.group_threads; + tmp = tmp % scanParameters.group_threads; + const Index block_id = tmp / scanParameters.block_threads; + const Index local_id = tmp % scanParameters.block_threads; + + // the actual panel size is scan_size * non_scan_size. + // elements_per_panel is roundup to power of 2 for binary tree + const Index panel_offset = panel_id * scanParameters.scan_size * scanParameters.non_scan_size; + const Index group_offset = group_id * scanParameters.non_scan_stride; + // This will be effective when the size is bigger than elements_per_block + const Index block_offset = block_id * scanParameters.elements_per_block * scanParameters.scan_stride; + const Index thread_offset = ScanParameters::ScanPerThread * local_id * scanParameters.scan_stride; + + const Index global_offset = panel_offset + group_offset + block_offset + thread_offset; + const Index block_size = scanParameters.elements_per_group / scanParameters.elements_per_block; + const Index in_id = (panel_id * block_size * scanParameters.non_scan_size) + (group_id * block_size) + block_id; + CoeffReturnType adjust_val = in_ptr[in_id]; + + Index next_elements = 0; + EIGEN_UNROLL_LOOP + for (Index i = 0; i < ScanParameters::ScanPerThread; i++) { + Index global_id = global_offset + next_elements; + if ((((block_id * scanParameters.elements_per_block) + (ScanParameters::ScanPerThread * local_id) + i) < + scanParameters.scan_size) && + (global_id < scanParameters.total_size)) { + CoeffReturnType accum = adjust_val; + accumulator.reduce(out_ptr[global_id], &accum); + out_ptr[global_id] = accumulator.finalize(accum); + } + next_elements += scanParameters.scan_stride; + } + } + } +}; + +template +struct ScanInfo { + const Index &total_size; + const Index &scan_size; + const Index &panel_size; + const Index &non_scan_size; + const Index &scan_stride; + const Index &non_scan_stride; + + Index max_elements_per_block; + Index block_size; + Index panel_threads; + Index group_threads; + Index block_threads; + Index elements_per_group; + Index elements_per_block; + Index loop_range; + Index global_range; + Index local_range; + const Eigen::SyclDevice &dev; + EIGEN_STRONG_INLINE ScanInfo(const Index &total_size_, const Index &scan_size_, const Index &panel_size_, + const Index &non_scan_size_, const Index &scan_stride_, const Index &non_scan_stride_, + const Eigen::SyclDevice &dev_) + : total_size(total_size_), + scan_size(scan_size_), + panel_size(panel_size_), + non_scan_size(non_scan_size_), + scan_stride(scan_stride_), + non_scan_stride(non_scan_stride_), + dev(dev_) { + // must be power of 2 + local_range = std::min(Index(dev.getNearestPowerOfTwoWorkGroupSize()), + Index(EIGEN_SYCL_LOCAL_THREAD_DIM0 * EIGEN_SYCL_LOCAL_THREAD_DIM1)); + + max_elements_per_block = local_range * ScanParameters::ScanPerThread; + + elements_per_group = + dev.getPowerOfTwo(Index(roundUp(Index(scan_size), ScanParameters::ScanPerThread)), true); + const Index elements_per_panel = elements_per_group * non_scan_size; + elements_per_block = std::min(Index(elements_per_group), Index(max_elements_per_block)); + panel_threads = elements_per_panel / ScanParameters::ScanPerThread; + group_threads = elements_per_group / ScanParameters::ScanPerThread; + block_threads = elements_per_block / ScanParameters::ScanPerThread; + block_size = elements_per_group / elements_per_block; +#ifdef EIGEN_SYCL_MAX_GLOBAL_RANGE + const Index max_threads = std::min(Index(panel_threads * panel_size), Index(EIGEN_SYCL_MAX_GLOBAL_RANGE)); +#else + const Index max_threads = panel_threads * panel_size; +#endif + global_range = roundUp(max_threads, local_range); + loop_range = Index( + std::ceil(double(elements_per_panel * panel_size) / (global_range * ScanParameters::ScanPerThread))); + } + inline ScanParameters get_scan_parameter() { + return ScanParameters(total_size, non_scan_size, scan_size, non_scan_stride, scan_stride, panel_threads, + group_threads, block_threads, elements_per_group, elements_per_block, loop_range); + } + inline cl::sycl::nd_range<1> get_thread_range() { + return cl::sycl::nd_range<1>(cl::sycl::range<1>(global_range), cl::sycl::range<1>(local_range)); + } +}; + +template +struct SYCLAdjustBlockOffset { + EIGEN_STRONG_INLINE static void adjust_scan_block_offset(EvaluatorPointerType in_ptr, EvaluatorPointerType out_ptr, + Reducer &accumulator, const Index total_size, + const Index scan_size, const Index panel_size, + const Index non_scan_size, const Index scan_stride, + const Index non_scan_stride, const Eigen::SyclDevice &dev) { + auto scan_info = + ScanInfo(total_size, scan_size, panel_size, non_scan_size, scan_stride, non_scan_stride, dev); + + typedef ScanAdjustmentKernelFunctor + AdjustFuctor; + dev.template unary_kernel_launcher(in_ptr, out_ptr, scan_info.get_thread_range(), + scan_info.max_elements_per_block, + scan_info.get_scan_parameter(), accumulator).wait(); + } +}; + +template +struct ScanLauncher_impl { + template + EIGEN_STRONG_INLINE static void scan_block(Input in_ptr, EvaluatorPointerType out_ptr, Reducer &accumulator, + const Index total_size, const Index scan_size, const Index panel_size, + const Index non_scan_size, const Index scan_stride, + const Index non_scan_stride, const bool inclusive, + const Eigen::SyclDevice &dev) { + auto scan_info = + ScanInfo(total_size, scan_size, panel_size, non_scan_size, scan_stride, non_scan_stride, dev); + const Index temp_pointer_size = scan_info.block_size * non_scan_size * panel_size; + const Index scratch_size = scan_info.max_elements_per_block / (ScanParameters::ScanPerThread / 2); + CoeffReturnType *temp_pointer = + static_cast(dev.allocate_temp(temp_pointer_size * sizeof(CoeffReturnType))); + EvaluatorPointerType tmp_global_accessor = dev.get(temp_pointer); + + typedef ScanKernelFunctor ScanFunctor; + dev.template binary_kernel_launcher( + in_ptr, out_ptr, tmp_global_accessor, scan_info.get_thread_range(), scratch_size, + scan_info.get_scan_parameter(), accumulator, inclusive).wait(); + + if (scan_info.block_size > 1) { + ScanLauncher_impl::scan_block( + tmp_global_accessor, tmp_global_accessor, accumulator, temp_pointer_size, scan_info.block_size, panel_size, + non_scan_size, Index(1), scan_info.block_size, false, dev); + + SYCLAdjustBlockOffset::adjust_scan_block_offset( + tmp_global_accessor, out_ptr, accumulator, total_size, scan_size, panel_size, non_scan_size, scan_stride, + non_scan_stride, dev); + } + dev.deallocate_temp(temp_pointer); + } +}; + +} // namespace internal +} // namespace TensorSycl +namespace internal { +template +struct ScanLauncher { + typedef typename Self::Index Index; + typedef typename Self::CoeffReturnType CoeffReturnType; + typedef typename Self::Storage Storage; + typedef typename Self::EvaluatorPointerType EvaluatorPointerType; + void operator()(Self &self, EvaluatorPointerType data) const { + const Index total_size = internal::array_prod(self.dimensions()); + const Index scan_size = self.size(); + const Index scan_stride = self.stride(); + // this is the scan op (can be sum or ...) + auto accumulator = self.accumulator(); + auto inclusive = !self.exclusive(); + auto consume_dim = self.consume_dim(); + auto dev = self.device(); + + auto dims = self.inner().dimensions(); + + Index non_scan_size = 1; + Index panel_size = 1; + if (static_cast(Self::Layout) == static_cast(ColMajor)) { + for (int i = 0; i < consume_dim; i++) { + non_scan_size *= dims[i]; + } + for (int i = consume_dim + 1; i < Self::NumDims; i++) { + panel_size *= dims[i]; + } + } else { + for (int i = Self::NumDims - 1; i > consume_dim; i--) { + non_scan_size *= dims[i]; + } + for (int i = consume_dim - 1; i >= 0; i--) { + panel_size *= dims[i]; + } + } + const Index non_scan_stride = (scan_stride > 1) ? 1 : scan_size; + auto eval_impl = self.inner(); + TensorSycl::internal::ScanLauncher_impl::scan_block( + eval_impl, data, accumulator, total_size, scan_size, panel_size, non_scan_size, scan_stride, non_scan_stride, + inclusive, dev); + } +}; +} // namespace internal +} // namespace Eigen + +#endif // UNSUPPORTED_EIGEN_CXX11_SRC_TENSOR_TENSOR_SYCL_SYCL_HPP diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorShuffling.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorShuffling.h new file mode 100644 index 0000000000000000000000000000000000000000..78f9f92cf006828a05859c0418b87ff05460b3e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorShuffling.h @@ -0,0 +1,464 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_SHUFFLING_H +#define EIGEN_CXX11_TENSOR_TENSOR_SHUFFLING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorShuffling + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor shuffling class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorShufflingOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorShufflingOp type; +}; + +} // end namespace internal + + + +template +class TensorShufflingOp : public TensorBase > +{ + public: + typedef TensorBase > Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorShufflingOp(const XprType& expr, const Shuffle& shfl) + : m_xpr(expr), m_shuffle(shfl) {} + + EIGEN_DEVICE_FUNC + const Shuffle& shufflePermutation() const { return m_shuffle; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorShufflingOp) + + + protected: + typename XprType::Nested m_xpr; + const Shuffle m_shuffle; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Self; + typedef TensorShufflingOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = TensorEvaluator::RawAccess, + PreferBlockAccess = true, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + typedef internal::TensorBlockScratchAllocator TensorBlockScratch; + + typedef typename internal::TensorMaterializedBlock + TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_device(device), + m_impl(op.expression(), device) + { + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + const Shuffle& shuffle = op.shufflePermutation(); + m_is_identity = true; + for (int i = 0; i < NumDims; ++i) { + m_shuffle[i] = static_cast(shuffle[i]); + m_dimensions[i] = input_dims[shuffle[i]]; + m_inverseShuffle[shuffle[i]] = i; + if (m_is_identity && shuffle[i] != i) { + m_is_identity = false; + } + } + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_unshuffledInputStrides[0] = 1; + m_outputStrides[0] = 1; + + for (int i = 1; i < NumDims; ++i) { + m_unshuffledInputStrides[i] = + m_unshuffledInputStrides[i - 1] * input_dims[i - 1]; + m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor( + m_outputStrides[i] > 0 ? m_outputStrides[i] : Index(1)); + } + } else { + m_unshuffledInputStrides[NumDims - 1] = 1; + m_outputStrides[NumDims - 1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_unshuffledInputStrides[i] = + m_unshuffledInputStrides[i + 1] * input_dims[i + 1]; + m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1]; + m_fastOutputStrides[i] = internal::TensorIntDivisor( + m_outputStrides[i] > 0 ? m_outputStrides[i] : Index(1)); + } + } + + for (int i = 0; i < NumDims; ++i) { + m_inputStrides[i] = m_unshuffledInputStrides[shuffle[i]]; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + +#ifdef EIGEN_USE_THREADS + template + EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync( + EvaluatorPointerType, EvalSubExprsCallback done) { + m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); + } +#endif // EIGEN_USE_THREADS + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + if (m_is_identity) { + return m_impl.coeff(index); + } else { + return m_impl.coeff(srcCoeff(index)); + } + } + + template + struct PacketLoader { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + static PacketReturnType Run(const Self& self, Index index) { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = self.coeff(index + i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + }; + + template + struct PacketLoader { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + static PacketReturnType Run(const Self& self, Index index) { + if (self.m_is_identity) { + return self.m_impl.template packet(index); + } else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = self.coeff(index + i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + }; + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index + PacketSize - 1 < dimensions().TotalSize()); + return PacketLoader::PacketAccess>::Run(*this, index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + internal::TensorBlockResourceRequirements getResourceRequirements() const { + static const int inner_dim = + Layout == static_cast(ColMajor) ? 0 : NumDims - 1; + + const size_t target_size = m_device.firstLevelCacheSize(); + const bool inner_dim_shuffled = m_shuffle[inner_dim] != inner_dim; + + // Shuffled inner dimensions leads to a random memory access, which is not + // captured by default cost model bytes loaded/stored. We add this cost + // explicitly. The number of cycles picked based on the benchmarks. + // TODO(ezhulenev): This number was picked based on a very questionable + // benchmarks, add benchmarks that are representative of real workloads. + using BlockRequirements = internal::TensorBlockResourceRequirements; + if (inner_dim_shuffled) { + return BlockRequirements::uniform(target_size) + .addCostPerCoeff({0, 0, NumDims * 28}); + } else { + return BlockRequirements::skewed(target_size); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock + block(TensorBlockDesc& desc, TensorBlockScratch& scratch, + bool root_of_expr_ast = false) const { + eigen_assert(m_impl.data() != NULL); + + typedef internal::TensorBlockIO + TensorBlockIO; + typedef typename TensorBlockIO::Dst TensorBlockIODst; + typedef typename TensorBlockIO::Src TensorBlockIOSrc; + + const typename TensorBlock::Storage block_storage = + TensorBlock::prepareStorage( + desc, scratch, /*allow_strided_storage=*/root_of_expr_ast); + + typename TensorBlockIO::Dimensions input_strides(m_unshuffledInputStrides); + TensorBlockIOSrc src(input_strides, m_impl.data(), srcCoeff(desc.offset())); + + TensorBlockIODst dst(block_storage.dimensions(), block_storage.strides(), + block_storage.data()); + + typename TensorBlockIO::DimensionsMap dst_to_src_dim_map(m_shuffle); + TensorBlockIO::Copy(dst, src, dst_to_src_dim_map); + + return block_storage.AsTensorMaterializedBlock(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + const double compute_cost = m_is_identity ? TensorOpCost::AddCost() : + NumDims * (2 * TensorOpCost::AddCost() + + 2 * TensorOpCost::MulCost() + + TensorOpCost::DivCost()); + return m_impl.costPerCoeff(vectorized) + + TensorOpCost(0, 0, compute_cost, m_is_identity /* vectorized */, PacketSize); + } + + EIGEN_DEVICE_FUNC typename Storage::Type data() const { return NULL; } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index GetBlockOutputIndex( + Index input_index, + const DSizes& input_block_strides, + const DSizes& output_block_strides, + const DSizes, NumDims>& fast_input_block_strides) const { + Index output_index = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = input_index / fast_input_block_strides[i]; + output_index += idx * output_block_strides[m_inverseShuffle[i]]; + input_index -= idx * input_block_strides[i]; + } + return output_index + input_index * + output_block_strides[m_inverseShuffle[0]]; + } else { + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = input_index / fast_input_block_strides[i]; + output_index += idx * output_block_strides[m_inverseShuffle[i]]; + input_index -= idx * input_block_strides[i]; + } + return output_index + input_index * + output_block_strides[m_inverseShuffle[NumDims - 1]]; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const { + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += idx * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + return inputIndex + index * m_inputStrides[0]; + } else { + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_fastOutputStrides[i]; + inputIndex += idx * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + return inputIndex + index * m_inputStrides[NumDims - 1]; + } + } + + Dimensions m_dimensions; + bool m_is_identity; + array m_shuffle; + array m_inverseShuffle; // TODO(ezhulenev): Make it int type. + array m_outputStrides; + array, NumDims> m_fastOutputStrides; + array m_inputStrides; + array m_unshuffledInputStrides; + + const Device EIGEN_DEVICE_REF m_device; + TensorEvaluator m_impl; +}; + + +// Eval as lvalue +template +struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorEvaluator, Device> Base; + + typedef TensorShufflingOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + static constexpr int Layout = TensorEvaluator::Layout; + + enum { + IsAligned = false, + PacketAccess = (PacketType::size > 1), + BlockAccess = TensorEvaluator::RawAccess, + PreferBlockAccess = true, + RawAccess = false + }; + + typedef std::remove_const_t ScalarNoConst; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockDescriptor TensorBlockDesc; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const + { + return this->m_impl.coeffRef(this->srcCoeff(index)); + } + + template EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + internal::pstore(values, x); + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + this->coeffRef(index+i) = values[i]; + } + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock( + const TensorBlockDesc& desc, const TensorBlock& block) { + eigen_assert(this->m_impl.data() != NULL); + + typedef internal::TensorBlockIO + TensorBlockIO; + typedef typename TensorBlockIO::Dst TensorBlockIODst; + typedef typename TensorBlockIO::Src TensorBlockIOSrc; + + const Scalar* block_buffer = block.data(); + + // TODO(ezhulenev): TensorBlockIO should be able to read from any Eigen + // expression with coefficient and packet access as `src`. + void* mem = NULL; + if (block_buffer == NULL) { + mem = this->m_device.allocate(desc.size() * sizeof(Scalar)); + ScalarNoConst* buf = static_cast(mem); + + typedef internal::TensorBlockAssignment< + ScalarNoConst, NumDims, typename TensorBlock::XprType, Index> + TensorBlockAssignment; + + TensorBlockAssignment::Run( + TensorBlockAssignment::target( + desc.dimensions(), internal::strides(desc.dimensions()), + buf), + block.expr()); + + block_buffer = buf; + } + + // Read from block. + TensorBlockIOSrc src(internal::strides(desc.dimensions()), + block_buffer); + + // Write to the output buffer. + typename TensorBlockIO::Dimensions output_strides( + this->m_unshuffledInputStrides); + typename TensorBlockIO::Dimensions output_dimensions; + for (int i = 0; i < NumDims; ++i) { + output_dimensions[this->m_shuffle[i]] = desc.dimension(i); + } + TensorBlockIODst dst(output_dimensions, output_strides, this->m_impl.data(), + this->srcCoeff(desc.offset())); + + // Reorder dimensions according to the shuffle. + typename TensorBlockIO::DimensionsMap dst_to_src_dim_map; + for (int i = 0; i < NumDims; ++i) { + dst_to_src_dim_map[i] = static_cast(this->m_inverseShuffle[i]); + } + TensorBlockIO::Copy(dst, src, dst_to_src_dim_map); + + // Deallocate temporary buffer used for the block materialization. + if (mem != NULL) this->m_device.deallocate(mem); + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_SHUFFLING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStorage.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStorage.h new file mode 100644 index 0000000000000000000000000000000000000000..f9bb8f6c83081e02b7024c31a5ad7c27be89bdde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStorage.h @@ -0,0 +1,156 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// Copyright (C) 2014-2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSORSTORAGE_H +#define EIGEN_CXX11_TENSOR_TENSORSTORAGE_H + +#ifdef EIGEN_TENSOR_STORAGE_CTOR_PLUGIN + #define EIGEN_INTERNAL_TENSOR_STORAGE_CTOR_PLUGIN EIGEN_TENSOR_STORAGE_CTOR_PLUGIN; +#else + #define EIGEN_INTERNAL_TENSOR_STORAGE_CTOR_PLUGIN +#endif + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \internal + * + * \class TensorStorage + * \ingroup CXX11_Tensor_Module + * + * \brief Stores the data of a tensor + * + * This class stores the data of fixed-size, dynamic-size or mixed tensors + * in a way as compact as possible. + * + * \sa Tensor + */ +template class TensorStorage; + + +// Pure fixed-size storage +template +class TensorStorage +{ + private: + static constexpr std::size_t Size = FixedDimensions::total_size; + + // Allocate an array of size at least one to prevent compiler warnings. + static constexpr std::size_t MinSize = max_n_1::size; + EIGEN_ALIGN_MAX T m_data[MinSize]; + + public: + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE TensorStorage() { + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE T *data() { return m_data; } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const T *data() const { return m_data; } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const FixedDimensions dimensions() const { return FixedDimensions(); } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE DenseIndex size() const { return Size; } +}; + + +// pure dynamic +template +class TensorStorage, Options_> +{ + public: + typedef IndexType Index; + typedef DSizes Dimensions; + typedef TensorStorage, Options_> Self; + + EIGEN_DEVICE_FUNC TensorStorage() : m_data(0), m_dimensions() { + if (NumIndices_ == 0) { + m_data = internal::conditional_aligned_new_auto(1); + } + } + EIGEN_DEVICE_FUNC TensorStorage(internal::constructor_without_unaligned_array_assert) + : m_data(0), m_dimensions(internal::template repeat(0)) {} + EIGEN_DEVICE_FUNC TensorStorage(Index size, const array& dimensions) + : m_data(internal::conditional_aligned_new_auto(size)), m_dimensions(dimensions) + { EIGEN_INTERNAL_TENSOR_STORAGE_CTOR_PLUGIN } + + template + EIGEN_DEVICE_FUNC TensorStorage(DenseIndex... indices) : m_dimensions(indices...) { + m_data = internal::conditional_aligned_new_auto(internal::array_prod(m_dimensions)); + } + + EIGEN_DEVICE_FUNC TensorStorage(const Self& other) + : m_data(internal::conditional_aligned_new_auto(internal::array_prod(other.m_dimensions))) + , m_dimensions(other.m_dimensions) + { + internal::smart_copy(other.m_data, other.m_data+internal::array_prod(other.m_dimensions), m_data); + } + EIGEN_DEVICE_FUNC Self& operator=(const Self& other) + { + if (this != &other) { + Self tmp(other); + this->swap(tmp); + } + return *this; + } + + EIGEN_DEVICE_FUNC TensorStorage(Self&& other) : TensorStorage() + { + *this = std::move(other); + } + + EIGEN_DEVICE_FUNC Self& operator=(Self&& other) + { + numext::swap(m_data, other.m_data); + numext::swap(m_dimensions, other.m_dimensions); + return *this; + } + + EIGEN_DEVICE_FUNC ~TensorStorage() { internal::conditional_aligned_delete_auto(m_data, internal::array_prod(m_dimensions)); } + EIGEN_DEVICE_FUNC void swap(Self& other) + { numext::swap(m_data,other.m_data); numext::swap(m_dimensions,other.m_dimensions); } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const {return m_dimensions;} + + EIGEN_DEVICE_FUNC void resize(Index size, const array& nbDimensions) + { + const Index currentSz = internal::array_prod(m_dimensions); + if(size != currentSz) + { + internal::conditional_aligned_delete_auto(m_data, currentSz); + if (size) + m_data = internal::conditional_aligned_new_auto(size); + else if (NumIndices_ == 0) { + m_data = internal::conditional_aligned_new_auto(1); + } + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + } + m_dimensions = nbDimensions; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T *data() { return m_data; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const T *data() const { return m_data; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_dimensions.TotalSize(); } + + private: + T *m_data; + Dimensions m_dimensions; +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSORSTORAGE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStriding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStriding.h new file mode 100644 index 0000000000000000000000000000000000000000..1b9a0f16a5770ad8fcbf770b14c6c013b5dbce57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorStriding.h @@ -0,0 +1,342 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_STRIDING_H +#define EIGEN_CXX11_TENSOR_TENSOR_STRIDING_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorStriding + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor striding class. + * + * + */ +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorStridingOpEIGEN_DEVICE_REF type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorStridingOp type; +}; + +} // end namespace internal + + + +template +class TensorStridingOp : public TensorBase > +{ + public: + typedef TensorBase > Base; + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorStridingOp(const XprType& expr, const Strides& dims) + : m_xpr(expr), m_dims(dims) {} + + EIGEN_DEVICE_FUNC + const Strides& strides() const { return m_dims; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorStridingOp) + + protected: + typename XprType::Nested m_xpr; + const Strides m_dims; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorStridingOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = /*TensorEvaluator::IsAligned*/false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device) + { + m_dimensions = m_impl.dimensions(); + for (int i = 0; i < NumDims; ++i) { + m_dimensions[i] =Eigen::numext::ceil(static_cast(m_dimensions[i]) / op.strides()[i]); + } + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + if (static_cast(Layout) == static_cast(ColMajor)) { + m_outputStrides[0] = 1; + m_inputStrides[0] = 1; + for (int i = 1; i < NumDims; ++i) { + m_outputStrides[i] = m_outputStrides[i-1] * m_dimensions[i-1]; + m_inputStrides[i] = m_inputStrides[i-1] * input_dims[i-1]; + m_inputStrides[i-1] *= op.strides()[i-1]; + } + m_inputStrides[NumDims-1] *= op.strides()[NumDims-1]; + } else { // RowMajor + m_outputStrides[NumDims-1] = 1; + m_inputStrides[NumDims-1] = 1; + for (int i = NumDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i+1] * m_dimensions[i+1]; + m_inputStrides[i] = m_inputStrides[i+1] * input_dims[i+1]; + m_inputStrides[i+1] *= op.strides()[i+1]; + } + m_inputStrides[0] *= op.strides()[0]; + } + } + + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType/*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + return m_impl.coeff(srcCoeff(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + EIGEN_STATIC_ASSERT((PacketSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + Index inputIndices[] = {0, 0}; + Index indices[] = {index, index + PacketSize - 1}; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx0 = indices[0] / m_outputStrides[i]; + const Index idx1 = indices[1] / m_outputStrides[i]; + inputIndices[0] += idx0 * m_inputStrides[i]; + inputIndices[1] += idx1 * m_inputStrides[i]; + indices[0] -= idx0 * m_outputStrides[i]; + indices[1] -= idx1 * m_outputStrides[i]; + } + inputIndices[0] += indices[0] * m_inputStrides[0]; + inputIndices[1] += indices[1] * m_inputStrides[0]; + } else { // RowMajor + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx0 = indices[0] / m_outputStrides[i]; + const Index idx1 = indices[1] / m_outputStrides[i]; + inputIndices[0] += idx0 * m_inputStrides[i]; + inputIndices[1] += idx1 * m_inputStrides[i]; + indices[0] -= idx0 * m_outputStrides[i]; + indices[1] -= idx1 * m_outputStrides[i]; + } + inputIndices[0] += indices[0] * m_inputStrides[NumDims-1]; + inputIndices[1] += indices[1] * m_inputStrides[NumDims-1]; + } + if (inputIndices[1] - inputIndices[0] == PacketSize - 1) { + PacketReturnType rslt = m_impl.template packet(inputIndices[0]); + return rslt; + } + else { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + values[0] = m_impl.coeff(inputIndices[0]); + values[PacketSize-1] = m_impl.coeff(inputIndices[1]); + EIGEN_UNROLL_LOOP + for (int i = 1; i < PacketSize-1; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const { + double compute_cost = (NumDims - 1) * (TensorOpCost::AddCost() + + TensorOpCost::MulCost() + + TensorOpCost::DivCost()) + + TensorOpCost::MulCost(); + if (vectorized) { + compute_cost *= 2; // packet() computes two indices + } + const int innerDim = (static_cast(Layout) == static_cast(ColMajor)) ? 0 : (NumDims - 1); + return m_impl.costPerCoeff(vectorized && m_inputStrides[innerDim] == 1) + + // Computation is not vectorized per se, but it is done once per packet. + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC typename Storage::Type data() const { return NULL; } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const + { + Index inputIndex = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + inputIndex += idx * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + inputIndex += index * m_inputStrides[0]; + } else { // RowMajor + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx = index / m_outputStrides[i]; + inputIndex += idx * m_inputStrides[i]; + index -= idx * m_outputStrides[i]; + } + inputIndex += index * m_inputStrides[NumDims-1]; + } + return inputIndex; + } + + Dimensions m_dimensions; + array m_outputStrides; + array m_inputStrides; + TensorEvaluator m_impl; +}; + +// Eval as lvalue +template +struct TensorEvaluator, Device> + : public TensorEvaluator, Device> +{ + typedef TensorStridingOp XprType; + typedef TensorEvaluator Base; + // typedef typename XprType::Index Index; + static constexpr int NumDims = internal::array_size::Dimensions>::value; + // typedef DSizes Dimensions; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = /*TensorEvaluator::IsAligned*/false, + PacketAccess = TensorEvaluator::PacketAccess, + PreferBlockAccess = false, + CoordAccess = false, // to be implemented + RawAccess = false + }; + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : Base(op, device) { } + + typedef typename XprType::Index Index; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const + { + return this->m_impl.coeffRef(this->srcCoeff(index)); + } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketReturnType& x) const + { + EIGEN_STATIC_ASSERT((PacketSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE) + eigen_assert(index+PacketSize-1 < this->dimensions().TotalSize()); + + Index inputIndices[] = {0, 0}; + Index indices[] = {index, index + PacketSize - 1}; + if (static_cast(Layout) == static_cast(ColMajor)) { + EIGEN_UNROLL_LOOP + for (int i = NumDims - 1; i > 0; --i) { + const Index idx0 = indices[0] / this->m_outputStrides[i]; + const Index idx1 = indices[1] / this->m_outputStrides[i]; + inputIndices[0] += idx0 * this->m_inputStrides[i]; + inputIndices[1] += idx1 * this->m_inputStrides[i]; + indices[0] -= idx0 * this->m_outputStrides[i]; + indices[1] -= idx1 * this->m_outputStrides[i]; + } + inputIndices[0] += indices[0] * this->m_inputStrides[0]; + inputIndices[1] += indices[1] * this->m_inputStrides[0]; + } else { // RowMajor + EIGEN_UNROLL_LOOP + for (int i = 0; i < NumDims - 1; ++i) { + const Index idx0 = indices[0] / this->m_outputStrides[i]; + const Index idx1 = indices[1] / this->m_outputStrides[i]; + inputIndices[0] += idx0 * this->m_inputStrides[i]; + inputIndices[1] += idx1 * this->m_inputStrides[i]; + indices[0] -= idx0 * this->m_outputStrides[i]; + indices[1] -= idx1 * this->m_outputStrides[i]; + } + inputIndices[0] += indices[0] * this->m_inputStrides[NumDims-1]; + inputIndices[1] += indices[1] * this->m_inputStrides[NumDims-1]; + } + if (inputIndices[1] - inputIndices[0] == PacketSize - 1) { + this->m_impl.template writePacket(inputIndices[0], x); + } + else { + EIGEN_ALIGN_MAX Scalar values[PacketSize]; + internal::pstore(values, x); + this->m_impl.coeffRef(inputIndices[0]) = values[0]; + this->m_impl.coeffRef(inputIndices[1]) = values[PacketSize-1]; + EIGEN_UNROLL_LOOP + for (int i = 1; i < PacketSize-1; ++i) { + this->coeffRef(index+i) = values[i]; + } + } + } +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_STRIDING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTrace.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTrace.h new file mode 100644 index 0000000000000000000000000000000000000000..55e8360d5c1d4416fb3401bbba60ffceccdf5151 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTrace.h @@ -0,0 +1,297 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2017 Gagan Goel +// Copyright (C) 2017 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_TRACE_H +#define EIGEN_CXX11_TENSOR_TENSOR_TRACE_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorTrace + * \ingroup CXX11_Tensor_Module + * + * \brief Tensor Trace class. + * + * + */ + +namespace internal { +template +struct traits > : public traits +{ + typedef typename XprType::Scalar Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions - array_size::value; + static constexpr int Layout = XprTraits::Layout; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorTraceOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorTraceOp type; +}; + +} // end namespace internal + + +template +class TensorTraceOp : public TensorBase > +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorTraceOp(const XprType& expr, const Dims& dims) + : m_xpr(expr), m_dims(dims) { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Dims& dims() const { return m_dims; } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const internal::remove_all_t& expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const Dims m_dims; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorTraceOp XprType; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + static constexpr int NumReducedDims = internal::array_size::value; + static constexpr int NumOutputDims = NumInputDims - NumReducedDims; + typedef typename XprType::Index Index; + typedef DSizes Dimensions; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = internal::unpacket_traits::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) + : m_impl(op.expression(), device), m_traceDim(1), m_device(device) + { + + EIGEN_STATIC_ASSERT((NumOutputDims >= 0), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT((NumReducedDims >= 2) || ((NumReducedDims == 0) && (NumInputDims == 0)), YOU_MADE_A_PROGRAMMING_MISTAKE); + + for (int i = 0; i < NumInputDims; ++i) { + m_reduced[i] = false; + } + + const Dims& op_dims = op.dims(); + for (int i = 0; i < NumReducedDims; ++i) { + eigen_assert(op_dims[i] >= 0); + eigen_assert(op_dims[i] < NumInputDims); + m_reduced[op_dims[i]] = true; + } + + // All the dimensions should be distinct to compute the trace + int num_distinct_reduce_dims = 0; + for (int i = 0; i < NumInputDims; ++i) { + if (m_reduced[i]) { + ++num_distinct_reduce_dims; + } + } + + EIGEN_ONLY_USED_FOR_DEBUG(num_distinct_reduce_dims); + eigen_assert(num_distinct_reduce_dims == NumReducedDims); + + // Compute the dimensions of the result. + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + + int output_index = 0; + int reduced_index = 0; + for (int i = 0; i < NumInputDims; ++i) { + if (m_reduced[i]) { + m_reducedDims[reduced_index] = input_dims[i]; + if (reduced_index > 0) { + // All the trace dimensions must have the same size + eigen_assert(m_reducedDims[0] == m_reducedDims[reduced_index]); + } + ++reduced_index; + } + else { + m_dimensions[output_index] = input_dims[i]; + ++output_index; + } + } + + if (NumReducedDims != 0) { + m_traceDim = m_reducedDims[0]; + } + + // Compute the output strides + if (NumOutputDims > 0) { + if (static_cast(Layout) == static_cast(ColMajor)) { + m_outputStrides[0] = 1; + for (int i = 1; i < NumOutputDims; ++i) { + m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1]; + } + } + else { + m_outputStrides.back() = 1; + for (int i = NumOutputDims - 2; i >= 0; --i) { + m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1]; + } + } + } + + // Compute the input strides + if (NumInputDims > 0) { + array input_strides; + if (static_cast(Layout) == static_cast(ColMajor)) { + input_strides[0] = 1; + for (int i = 1; i < NumInputDims; ++i) { + input_strides[i] = input_strides[i - 1] * input_dims[i - 1]; + } + } + else { + input_strides.back() = 1; + for (int i = NumInputDims - 2; i >= 0; --i) { + input_strides[i] = input_strides[i + 1] * input_dims[i + 1]; + } + } + + output_index = 0; + reduced_index = 0; + for (int i = 0; i < NumInputDims; ++i) { + if(m_reduced[i]) { + m_reducedStrides[reduced_index] = input_strides[i]; + ++reduced_index; + } + else { + m_preservedStrides[output_index] = input_strides[i]; + ++output_index; + } + } + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { + return m_dimensions; + } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + // Initialize the result + CoeffReturnType result = internal::cast(0); + Index index_stride = 0; + for (int i = 0; i < NumReducedDims; ++i) { + index_stride += m_reducedStrides[i]; + } + + // If trace is requested along all dimensions, starting index would be 0 + Index cur_index = 0; + if (NumOutputDims != 0) + cur_index = firstInput(index); + for (Index i = 0; i < m_traceDim; ++i) { + result += m_impl.coeff(cur_index); + cur_index += index_stride; + } + + return result; + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const { + eigen_assert(index + PacketSize - 1 < dimensions().TotalSize()); + + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index + i); + } + PacketReturnType result = internal::ploadt(values); + return result; + } + + protected: + // Given the output index, finds the first index in the input tensor used to compute the trace + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index firstInput(Index index) const { + Index startInput = 0; + if (static_cast(Layout) == static_cast(ColMajor)) { + for (int i = NumOutputDims - 1; i > 0; --i) { + const Index idx = index / m_outputStrides[i]; + startInput += idx * m_preservedStrides[i]; + index -= idx * m_outputStrides[i]; + } + startInput += index * m_preservedStrides[0]; + } + else { + for (int i = 0; i < NumOutputDims - 1; ++i) { + const Index idx = index / m_outputStrides[i]; + startInput += idx * m_preservedStrides[i]; + index -= idx * m_outputStrides[i]; + } + startInput += index * m_preservedStrides[NumOutputDims - 1]; + } + return startInput; + } + + Dimensions m_dimensions; + TensorEvaluator m_impl; + // Initialize the size of the trace dimension + Index m_traceDim; + const Device EIGEN_DEVICE_REF m_device; + array m_reduced; + array m_reducedDims; + array m_outputStrides; + array m_reducedStrides; + array m_preservedStrides; +}; + + +} // End namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_TRACE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTraits.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTraits.h new file mode 100644 index 0000000000000000000000000000000000000000..8c705ecf6d342ad4eeded1505aefad80d700fead --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorTraits.h @@ -0,0 +1,266 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_TRAITS_H +#define EIGEN_CXX11_TENSOR_TENSOR_TRAITS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + + +template +class compute_tensor_flags +{ + enum { + is_dynamic_size_storage = 1, + + is_aligned = + ( + ((Options&DontAlign)==0) && ( +#if EIGEN_MAX_STATIC_ALIGN_BYTES>0 + (!is_dynamic_size_storage) +#else + 0 +#endif + | +#if EIGEN_MAX_ALIGN_BYTES>0 + is_dynamic_size_storage +#else + 0 +#endif + ) + ), + packet_access_bit = packet_traits::Vectorizable && is_aligned ? PacketAccessBit : 0 + }; + + public: + enum { ret = packet_access_bit }; +}; + + +template +struct traits > +{ + typedef Scalar_ Scalar; + typedef Dense StorageKind; + typedef IndexType_ Index; + static constexpr int NumDimensions = NumIndices_; + static constexpr int Layout = Options_ & RowMajor ? RowMajor : ColMajor; + enum { + Options = Options_, + Flags = compute_tensor_flags::ret | (is_const::value ? 0 : LvalueBit) + }; + template struct MakePointer { + typedef T* Type; + }; + typedef typename MakePointer::Type PointerType; +}; + + +template +struct traits > +{ + typedef Scalar_ Scalar; + typedef Dense StorageKind; + typedef IndexType_ Index; + static constexpr int NumDimensions = array_size::value; + static constexpr int Layout = Options_ & RowMajor ? RowMajor : ColMajor; + enum { + Options = Options_, + Flags = compute_tensor_flags::ret | (is_const::value ? 0: LvalueBit) + }; + template struct MakePointer { + typedef T* Type; + }; + typedef typename MakePointer::Type PointerType; +}; + + +template class MakePointer_> +struct traits > + : public traits +{ + typedef traits BaseTraits; + typedef typename BaseTraits::Scalar Scalar; + typedef typename BaseTraits::StorageKind StorageKind; + typedef typename BaseTraits::Index Index; + static constexpr int NumDimensions = BaseTraits::NumDimensions; + static constexpr int Layout = BaseTraits::Layout; + enum { + Options = Options_, + Flags = BaseTraits::Flags + }; + template struct MakePointer { + // Intermediate typedef to workaround MSVC issue. + typedef MakePointer_ MakePointerT; + typedef typename MakePointerT::Type Type; + }; + typedef typename MakePointer::Type PointerType; +}; + +template +struct traits > + : public traits +{ + typedef traits BaseTraits; + typedef typename BaseTraits::Scalar Scalar; + typedef typename BaseTraits::StorageKind StorageKind; + typedef typename BaseTraits::Index Index; + static constexpr int NumDimensions = BaseTraits::NumDimensions; + static constexpr int Layout = BaseTraits::Layout; + enum { + Options = BaseTraits::Options, + Flags = BaseTraits::Flags + }; + typedef typename BaseTraits::PointerType PointerType; +}; + + +template +struct eval, Eigen::Dense> +{ + typedef const TensorEIGEN_DEVICE_REF type; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorEIGEN_DEVICE_REF type; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorFixedSizeEIGEN_DEVICE_REF type; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorFixedSizeEIGEN_DEVICE_REF type; +}; + +template class MakePointer> +struct eval, Eigen::Dense> +{ + typedef const TensorMapEIGEN_DEVICE_REF type; +}; + +template class MakePointer> +struct eval, Eigen::Dense> +{ + typedef const TensorMapEIGEN_DEVICE_REF type; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorRefEIGEN_DEVICE_REF type; +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorRefEIGEN_DEVICE_REF type; +}; + +// TODO nested<> does not exist anymore in Eigen/Core, and it thus has to be removed in favor of ref_selector. +template struct nested +{ + typedef typename ref_selector::type type; +}; + +template +struct nested > +{ + typedef const TensorEIGEN_DEVICE_REF type; +}; + +template +struct nested > +{ + typedef const TensorEIGEN_DEVICE_REF type; +}; + +template +struct nested > +{ + typedef const TensorFixedSizeEIGEN_DEVICE_REF type; +}; + +template +struct nested > +{ + typedef const TensorFixedSizeEIGEN_DEVICE_REF type; +}; + + +template +struct nested > +{ + typedef const TensorRefEIGEN_DEVICE_REF type; +}; + +template +struct nested > +{ + typedef const TensorRefEIGEN_DEVICE_REF type; +}; + +} // end namespace internal + +// Convolutional layers take in an input tensor of shape (D, R, C, B), or (D, C, +// R, B), and convolve it with a set of filters, which can also be presented as +// a tensor (D, K, K, M), where M is the number of filters, K is the filter +// size, and each 3-dimensional tensor of size (D, K, K) is a filter. For +// simplicity we assume that we always use square filters (which is usually the +// case in images), hence the two Ks in the tensor dimension. It also takes in +// a few additional parameters: +// Stride (S): The convolution stride is the offset between locations where we +// apply the filters. A larger stride means that the output will be +// spatially smaller. +// Padding (P): The padding we apply to the input tensor along the R and C +// dimensions. This is usually used to make sure that the spatial +// dimensions of the output matches our intention. +// +// Two types of padding are often used: +// SAME: The pad value is computed so that the output will have size +// R/S and C/S. +// VALID: no padding is carried out. +// When we do padding, the padded values at the padded locations are usually +// zero. +// +// The output dimensions for convolution, when given all the parameters above, +// are as follows: +// When Padding = SAME: the output size is (B, R', C', M), where +// R' = ceil(float(R) / float(S)) +// C' = ceil(float(C) / float(S)) +// where ceil is the ceiling function. The input tensor is padded with 0 as +// needed. The number of padded rows and columns are computed as: +// Pr = ((R' - 1) * S + K - R) / 2 +// Pc = ((C' - 1) * S + K - C) / 2 +// when the stride is 1, we have the simplified case R'=R, C'=C, Pr=Pc=(K-1)/2. +// This is where SAME comes from - the output has the same size as the input has. +// When Padding = VALID: the output size is computed as +// R' = ceil(float(R - K + 1) / float(S)) +// C' = ceil(float(C - K + 1) / float(S)) +// and the number of padded rows and columns are computed in the same way as in +// the SAME case. +// When the stride is 1, we have the simplified case R'=R-K+1, C'=C-K+1, Pr=0, +// Pc=0. +enum PaddingType { + PADDING_VALID = 1, + PADDING_SAME = 2 +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_TRAITS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorUInt128.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorUInt128.h new file mode 100644 index 0000000000000000000000000000000000000000..37be364d7976fb8463ab6934ed4731a27192cf85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorUInt128.h @@ -0,0 +1,251 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_UINT128_H +#define EIGEN_CXX11_TENSOR_TENSOR_UINT128_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + + +template +struct static_val { + static const uint64_t value = n; + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE operator uint64_t() const { return n; } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static_val() { } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static_val(const T& v) { + EIGEN_UNUSED_VARIABLE(v); + eigen_assert(v == n); + } +}; + + +template +struct TensorUInt128 +{ + HIGH high; + LOW low; + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + TensorUInt128(const TensorUInt128& other) : high(other.high), low(other.low) { + EIGEN_STATIC_ASSERT(sizeof(OTHER_HIGH) <= sizeof(HIGH), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT(sizeof(OTHER_LOW) <= sizeof(LOW), YOU_MADE_A_PROGRAMMING_MISTAKE); + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + TensorUInt128& operator = (const TensorUInt128& other) { + EIGEN_STATIC_ASSERT(sizeof(OTHER_HIGH) <= sizeof(HIGH), YOU_MADE_A_PROGRAMMING_MISTAKE); + EIGEN_STATIC_ASSERT(sizeof(OTHER_LOW) <= sizeof(LOW), YOU_MADE_A_PROGRAMMING_MISTAKE); + high = other.high; + low = other.low; + return *this; + } + + template + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + explicit TensorUInt128(const T& x) : high(0), low(x) { + eigen_assert((static_cast>(x) <= NumTraits::highest())); + eigen_assert(x >= 0); + } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE + TensorUInt128(HIGH y, LOW x) : high(y), low(x) { } + + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE operator LOW() const { + return low; + } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE LOW lower() const { + return low; + } + EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE HIGH upper() const { + return high; + } +}; + + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +bool operator == (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + return (lhs.high == rhs.high) && (lhs.low == rhs.low); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +bool operator != (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + return (lhs.high != rhs.high) || (lhs.low != rhs.low); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +bool operator >= (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + if (lhs.high != rhs.high) { + return lhs.high > rhs.high; + } + return lhs.low >= rhs.low; +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +bool operator < (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + if (lhs.high != rhs.high) { + return lhs.high < rhs.high; + } + return lhs.low < rhs.low; +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +TensorUInt128 operator + (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + TensorUInt128 result(lhs.high + rhs.high, lhs.low + rhs.low); + if (result.low < rhs.low) { + result.high += 1; + } + return result; +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +TensorUInt128 operator - (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + TensorUInt128 result(lhs.high - rhs.high, lhs.low - rhs.low); + if (result.low > lhs.low) { + result.high -= 1; + } + return result; +} + + +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +TensorUInt128 operator * (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + // Split each 128-bit integer into 4 32-bit integers, and then do the + // multiplications by hand as follow: + // lhs a b c d + // rhs e f g h + // ----------- + // ah bh ch dh + // bg cg dg + // cf df + // de + // The result is stored in 2 64bit integers, high and low. + + const uint64_t LOW = 0x00000000FFFFFFFFLL; + const uint64_t HIGH = 0xFFFFFFFF00000000LL; + + uint64_t d = lhs.low & LOW; + uint64_t c = (lhs.low & HIGH) >> 32LL; + uint64_t b = lhs.high & LOW; + uint64_t a = (lhs.high & HIGH) >> 32LL; + + uint64_t h = rhs.low & LOW; + uint64_t g = (rhs.low & HIGH) >> 32LL; + uint64_t f = rhs.high & LOW; + uint64_t e = (rhs.high & HIGH) >> 32LL; + + // Compute the low 32 bits of low + uint64_t acc = d * h; + uint64_t low = acc & LOW; + // Compute the high 32 bits of low. Add a carry every time we wrap around + acc >>= 32LL; + uint64_t carry = 0; + uint64_t acc2 = acc + c * h; + if (acc2 < acc) { + carry++; + } + acc = acc2 + d * g; + if (acc < acc2) { + carry++; + } + low |= (acc << 32LL); + + // Carry forward the high bits of acc to initiate the computation of the + // low 32 bits of high + acc2 = (acc >> 32LL) | (carry << 32LL); + carry = 0; + + acc = acc2 + b * h; + if (acc < acc2) { + carry++; + } + acc2 = acc + c * g; + if (acc2 < acc) { + carry++; + } + acc = acc2 + d * f; + if (acc < acc2) { + carry++; + } + uint64_t high = acc & LOW; + + // Start to compute the high 32 bits of high. + acc2 = (acc >> 32LL) | (carry << 32LL); + + acc = acc2 + a * h; + acc2 = acc + b * g; + acc = acc2 + c * f; + acc2 = acc + d * e; + high |= (acc2 << 32LL); + + return TensorUInt128(high, low); +} + +template +static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +TensorUInt128 operator / (const TensorUInt128& lhs, const TensorUInt128& rhs) +{ + if (rhs == TensorUInt128, static_val<1> >(1)) { + return TensorUInt128(lhs.high, lhs.low); + } else if (lhs < rhs) { + return TensorUInt128(0); + } else { + // calculate the biggest power of 2 times rhs that's less than or equal to lhs + TensorUInt128 power2(1); + TensorUInt128 d(rhs); + TensorUInt128 tmp(lhs - d); + while (lhs >= d) { + tmp = tmp - d; + d = d + d; + power2 = power2 + power2; + } + + tmp = TensorUInt128(lhs.high, lhs.low); + TensorUInt128 result(0); + while (power2 != TensorUInt128, static_val<0> >(0)) { + if (tmp >= d) { + tmp = tmp - d; + result = result + power2; + } + // Shift right + power2 = TensorUInt128(power2.high >> 1, (power2.low >> 1) | (power2.high << 63)); + d = TensorUInt128(d.high >> 1, (d.low >> 1) | (d.high << 63)); + } + + return result; + } +} + + +} // namespace internal +} // namespace Eigen + + +#endif // EIGEN_CXX11_TENSOR_TENSOR_UINT128_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorVolumePatch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorVolumePatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ac2ad6113d532434baea795acd62e461e23b33ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/Tensor/TensorVolumePatch.h @@ -0,0 +1,624 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. + +#ifndef EIGEN_CXX11_TENSOR_TENSOR_VOLUME_PATCH_H +#define EIGEN_CXX11_TENSOR_TENSOR_VOLUME_PATCH_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \class TensorVolumePatch + * \ingroup CXX11_Tensor_Module + * + * \brief Patch extraction specialized for processing of volumetric data. + * This assumes that the input has a least 4 dimensions ordered as follows: + * - channels + * - planes + * - rows + * - columns + * - (optional) additional dimensions such as time or batch size. + * Calling the volume patch code with patch_planes, patch_rows, and patch_cols + * is equivalent to calling the regular patch extraction code with parameters + * d, patch_planes, patch_rows, patch_cols, and 1 for all the additional + * dimensions. + */ +namespace internal { + +template +struct traits > : public traits +{ + typedef std::remove_const_t Scalar; + typedef traits XprTraits; + typedef typename XprTraits::StorageKind StorageKind; + typedef typename XprTraits::Index Index; + typedef typename XprType::Nested Nested; + typedef std::remove_reference_t Nested_; + static constexpr int NumDimensions = XprTraits::NumDimensions + 1; + static constexpr int Layout = XprTraits::Layout; + typedef typename XprTraits::PointerType PointerType; + +}; + +template +struct eval, Eigen::Dense> +{ + typedef const TensorVolumePatchOp& type; +}; + +template +struct nested, 1, typename eval >::type> +{ + typedef TensorVolumePatchOp type; +}; + +} // end namespace internal + +template +class TensorVolumePatchOp : public TensorBase, ReadOnlyAccessors> +{ + public: + typedef typename Eigen::internal::traits::Scalar Scalar; + typedef typename Eigen::NumTraits::Real RealScalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename Eigen::internal::nested::type Nested; + typedef typename Eigen::internal::traits::StorageKind StorageKind; + typedef typename Eigen::internal::traits::Index Index; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorVolumePatchOp(const XprType& expr, DenseIndex patch_planes, DenseIndex patch_rows, DenseIndex patch_cols, + DenseIndex plane_strides, DenseIndex row_strides, DenseIndex col_strides, + DenseIndex in_plane_strides, DenseIndex in_row_strides, DenseIndex in_col_strides, + DenseIndex plane_inflate_strides, DenseIndex row_inflate_strides, DenseIndex col_inflate_strides, + PaddingType padding_type, Scalar padding_value) + : m_xpr(expr), m_patch_planes(patch_planes), m_patch_rows(patch_rows), m_patch_cols(patch_cols), + m_plane_strides(plane_strides), m_row_strides(row_strides), m_col_strides(col_strides), + m_in_plane_strides(in_plane_strides), m_in_row_strides(in_row_strides), m_in_col_strides(in_col_strides), + m_plane_inflate_strides(plane_inflate_strides), m_row_inflate_strides(row_inflate_strides), m_col_inflate_strides(col_inflate_strides), + m_padding_explicit(false), m_padding_top_z(0), m_padding_bottom_z(0), m_padding_top(0), m_padding_bottom(0), m_padding_left(0), m_padding_right(0), + m_padding_type(padding_type), m_padding_value(padding_value) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorVolumePatchOp(const XprType& expr, DenseIndex patch_planes, DenseIndex patch_rows, DenseIndex patch_cols, + DenseIndex plane_strides, DenseIndex row_strides, DenseIndex col_strides, + DenseIndex in_plane_strides, DenseIndex in_row_strides, DenseIndex in_col_strides, + DenseIndex plane_inflate_strides, DenseIndex row_inflate_strides, DenseIndex col_inflate_strides, + DenseIndex padding_top_z, DenseIndex padding_bottom_z, + DenseIndex padding_top, DenseIndex padding_bottom, + DenseIndex padding_left, DenseIndex padding_right, + Scalar padding_value) + : m_xpr(expr), m_patch_planes(patch_planes), m_patch_rows(patch_rows), m_patch_cols(patch_cols), + m_plane_strides(plane_strides), m_row_strides(row_strides), m_col_strides(col_strides), + m_in_plane_strides(in_plane_strides), m_in_row_strides(in_row_strides), m_in_col_strides(in_col_strides), + m_plane_inflate_strides(plane_inflate_strides), m_row_inflate_strides(row_inflate_strides), m_col_inflate_strides(col_inflate_strides), + m_padding_explicit(true), m_padding_top_z(padding_top_z), m_padding_bottom_z(padding_bottom_z), m_padding_top(padding_top), m_padding_bottom(padding_bottom), + m_padding_left(padding_left), m_padding_right(padding_right), + m_padding_type(PADDING_VALID), m_padding_value(padding_value) {} + + EIGEN_DEVICE_FUNC + DenseIndex patch_planes() const { return m_patch_planes; } + EIGEN_DEVICE_FUNC + DenseIndex patch_rows() const { return m_patch_rows; } + EIGEN_DEVICE_FUNC + DenseIndex patch_cols() const { return m_patch_cols; } + EIGEN_DEVICE_FUNC + DenseIndex plane_strides() const { return m_plane_strides; } + EIGEN_DEVICE_FUNC + DenseIndex row_strides() const { return m_row_strides; } + EIGEN_DEVICE_FUNC + DenseIndex col_strides() const { return m_col_strides; } + EIGEN_DEVICE_FUNC + DenseIndex in_plane_strides() const { return m_in_plane_strides; } + EIGEN_DEVICE_FUNC + DenseIndex in_row_strides() const { return m_in_row_strides; } + EIGEN_DEVICE_FUNC + DenseIndex in_col_strides() const { return m_in_col_strides; } + EIGEN_DEVICE_FUNC + DenseIndex plane_inflate_strides() const { return m_plane_inflate_strides; } + EIGEN_DEVICE_FUNC + DenseIndex row_inflate_strides() const { return m_row_inflate_strides; } + EIGEN_DEVICE_FUNC + DenseIndex col_inflate_strides() const { return m_col_inflate_strides; } + EIGEN_DEVICE_FUNC + bool padding_explicit() const { return m_padding_explicit; } + EIGEN_DEVICE_FUNC + DenseIndex padding_top_z() const { return m_padding_top_z; } + EIGEN_DEVICE_FUNC + DenseIndex padding_bottom_z() const { return m_padding_bottom_z; } + EIGEN_DEVICE_FUNC + DenseIndex padding_top() const { return m_padding_top; } + EIGEN_DEVICE_FUNC + DenseIndex padding_bottom() const { return m_padding_bottom; } + EIGEN_DEVICE_FUNC + DenseIndex padding_left() const { return m_padding_left; } + EIGEN_DEVICE_FUNC + DenseIndex padding_right() const { return m_padding_right; } + EIGEN_DEVICE_FUNC + PaddingType padding_type() const { return m_padding_type; } + EIGEN_DEVICE_FUNC + Scalar padding_value() const { return m_padding_value; } + + EIGEN_DEVICE_FUNC + const internal::remove_all_t& + expression() const { return m_xpr; } + + protected: + typename XprType::Nested m_xpr; + const DenseIndex m_patch_planes; + const DenseIndex m_patch_rows; + const DenseIndex m_patch_cols; + const DenseIndex m_plane_strides; + const DenseIndex m_row_strides; + const DenseIndex m_col_strides; + const DenseIndex m_in_plane_strides; + const DenseIndex m_in_row_strides; + const DenseIndex m_in_col_strides; + const DenseIndex m_plane_inflate_strides; + const DenseIndex m_row_inflate_strides; + const DenseIndex m_col_inflate_strides; + const bool m_padding_explicit; + const DenseIndex m_padding_top_z; + const DenseIndex m_padding_bottom_z; + const DenseIndex m_padding_top; + const DenseIndex m_padding_bottom; + const DenseIndex m_padding_left; + const DenseIndex m_padding_right; + const PaddingType m_padding_type; + const Scalar m_padding_value; +}; + + +// Eval as rvalue +template +struct TensorEvaluator, Device> +{ + typedef TensorVolumePatchOp XprType; + typedef typename XprType::Index Index; + static constexpr int NumInputDims = internal::array_size::Dimensions>::value; + static constexpr int NumDims = NumInputDims + 1; + typedef DSizes Dimensions; + typedef std::remove_const_t Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename PacketType::type PacketReturnType; + static constexpr int PacketSize = PacketType::size; + typedef StorageMemory Storage; + typedef typename Storage::Type EvaluatorPointerType; + + static constexpr int Layout = TensorEvaluator::Layout; + enum { + IsAligned = false, + PacketAccess = TensorEvaluator::PacketAccess, + BlockAccess = false, + PreferBlockAccess = TensorEvaluator::PreferBlockAccess, + CoordAccess = false, + RawAccess = false + }; + + //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===// + typedef internal::TensorBlockNotImplemented TensorBlock; + //===--------------------------------------------------------------------===// + + EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : + m_impl(op.expression(), device) + { + EIGEN_STATIC_ASSERT((NumDims >= 5), YOU_MADE_A_PROGRAMMING_MISTAKE); + + m_paddingValue = op.padding_value(); + + const typename TensorEvaluator::Dimensions& input_dims = m_impl.dimensions(); + + // Cache a few variables. + if (static_cast(Layout) == static_cast(ColMajor)) { + m_inputDepth = input_dims[0]; + m_inputPlanes = input_dims[1]; + m_inputRows = input_dims[2]; + m_inputCols = input_dims[3]; + } else { + m_inputDepth = input_dims[NumInputDims-1]; + m_inputPlanes = input_dims[NumInputDims-2]; + m_inputRows = input_dims[NumInputDims-3]; + m_inputCols = input_dims[NumInputDims-4]; + } + + m_plane_strides = op.plane_strides(); + m_row_strides = op.row_strides(); + m_col_strides = op.col_strides(); + + // Input strides and effective input/patch size + m_in_plane_strides = op.in_plane_strides(); + m_in_row_strides = op.in_row_strides(); + m_in_col_strides = op.in_col_strides(); + m_plane_inflate_strides = op.plane_inflate_strides(); + m_row_inflate_strides = op.row_inflate_strides(); + m_col_inflate_strides = op.col_inflate_strides(); + + // The "effective" spatial size after inflating data with zeros. + m_input_planes_eff = (m_inputPlanes - 1) * m_plane_inflate_strides + 1; + m_input_rows_eff = (m_inputRows - 1) * m_row_inflate_strides + 1; + m_input_cols_eff = (m_inputCols - 1) * m_col_inflate_strides + 1; + m_patch_planes_eff = op.patch_planes() + (op.patch_planes() - 1) * (m_in_plane_strides - 1); + m_patch_rows_eff = op.patch_rows() + (op.patch_rows() - 1) * (m_in_row_strides - 1); + m_patch_cols_eff = op.patch_cols() + (op.patch_cols() - 1) * (m_in_col_strides - 1); + + if (op.padding_explicit()) { + m_outputPlanes = numext::ceil((m_input_planes_eff + op.padding_top_z() + op.padding_bottom_z() - m_patch_planes_eff + 1.f) / static_cast(m_plane_strides)); + m_outputRows = numext::ceil((m_input_rows_eff + op.padding_top() + op.padding_bottom() - m_patch_rows_eff + 1.f) / static_cast(m_row_strides)); + m_outputCols = numext::ceil((m_input_cols_eff + op.padding_left() + op.padding_right() - m_patch_cols_eff + 1.f) / static_cast(m_col_strides)); + m_planePaddingTop = op.padding_top_z(); + m_rowPaddingTop = op.padding_top(); + m_colPaddingLeft = op.padding_left(); + } else { + // Computing padding from the type + switch (op.padding_type()) { + case PADDING_VALID: + m_outputPlanes = numext::ceil((m_input_planes_eff - m_patch_planes_eff + 1.f) / static_cast(m_plane_strides)); + m_outputRows = numext::ceil((m_input_rows_eff - m_patch_rows_eff + 1.f) / static_cast(m_row_strides)); + m_outputCols = numext::ceil((m_input_cols_eff - m_patch_cols_eff + 1.f) / static_cast(m_col_strides)); + m_planePaddingTop = 0; + m_rowPaddingTop = 0; + m_colPaddingLeft = 0; + break; + case PADDING_SAME: { + m_outputPlanes = numext::ceil(m_input_planes_eff / static_cast(m_plane_strides)); + m_outputRows = numext::ceil(m_input_rows_eff / static_cast(m_row_strides)); + m_outputCols = numext::ceil(m_input_cols_eff / static_cast(m_col_strides)); + const Index dz = (m_outputPlanes - 1) * m_plane_strides + m_patch_planes_eff - m_input_planes_eff; + const Index dy = (m_outputRows - 1) * m_row_strides + m_patch_rows_eff - m_input_rows_eff; + const Index dx = (m_outputCols - 1) * m_col_strides + m_patch_cols_eff - m_input_cols_eff; + m_planePaddingTop = dz / 2; + m_rowPaddingTop = dy / 2; + m_colPaddingLeft = dx / 2; + break; + } + default: + eigen_assert(false && "unexpected padding"); + } + } + eigen_assert(m_outputRows > 0); + eigen_assert(m_outputCols > 0); + eigen_assert(m_outputPlanes > 0); + + // Dimensions for result of extraction. + if (static_cast(Layout) == static_cast(ColMajor)) { + // ColMajor + // 0: depth + // 1: patch_planes + // 2: patch_rows + // 3: patch_cols + // 4: number of patches + // 5 and beyond: anything else (such as batch). + m_dimensions[0] = input_dims[0]; + m_dimensions[1] = op.patch_planes(); + m_dimensions[2] = op.patch_rows(); + m_dimensions[3] = op.patch_cols(); + m_dimensions[4] = m_outputPlanes * m_outputRows * m_outputCols; + for (int i = 5; i < NumDims; ++i) { + m_dimensions[i] = input_dims[i-1]; + } + } else { + // RowMajor + // NumDims-1: depth + // NumDims-2: patch_planes + // NumDims-3: patch_rows + // NumDims-4: patch_cols + // NumDims-5: number of patches + // NumDims-6 and beyond: anything else (such as batch). + m_dimensions[NumDims-1] = input_dims[NumInputDims-1]; + m_dimensions[NumDims-2] = op.patch_planes(); + m_dimensions[NumDims-3] = op.patch_rows(); + m_dimensions[NumDims-4] = op.patch_cols(); + m_dimensions[NumDims-5] = m_outputPlanes * m_outputRows * m_outputCols; + for (int i = NumDims-6; i >= 0; --i) { + m_dimensions[i] = input_dims[i]; + } + } + + // Strides for the output tensor. + if (static_cast(Layout) == static_cast(ColMajor)) { + m_rowStride = m_dimensions[1]; + m_colStride = m_dimensions[2] * m_rowStride; + m_patchStride = m_colStride * m_dimensions[3] * m_dimensions[0]; + m_otherStride = m_patchStride * m_dimensions[4]; + } else { + m_rowStride = m_dimensions[NumDims-2]; + m_colStride = m_dimensions[NumDims-3] * m_rowStride; + m_patchStride = m_colStride * m_dimensions[NumDims-4] * m_dimensions[NumDims-1]; + m_otherStride = m_patchStride * m_dimensions[NumDims-5]; + } + + // Strides for navigating through the input tensor. + m_planeInputStride = m_inputDepth; + m_rowInputStride = m_inputDepth * m_inputPlanes; + m_colInputStride = m_inputDepth * m_inputRows * m_inputPlanes; + m_otherInputStride = m_inputDepth * m_inputRows * m_inputCols * m_inputPlanes; + + m_outputPlanesRows = m_outputPlanes * m_outputRows; + + // Fast representations of different variables. + m_fastOtherStride = internal::TensorIntDivisor(m_otherStride); + + m_fastPatchStride = internal::TensorIntDivisor(m_patchStride); + m_fastColStride = internal::TensorIntDivisor(m_colStride); + m_fastRowStride = internal::TensorIntDivisor(m_rowStride); + m_fastInputRowStride = internal::TensorIntDivisor(m_row_inflate_strides); + m_fastInputColStride = internal::TensorIntDivisor(m_col_inflate_strides); + m_fastInputPlaneStride = internal::TensorIntDivisor(m_plane_inflate_strides); + m_fastInputColsEff = internal::TensorIntDivisor(m_input_cols_eff); + m_fastOutputPlanes = internal::TensorIntDivisor(m_outputPlanes); + m_fastOutputPlanesRows = internal::TensorIntDivisor(m_outputPlanesRows); + + if (static_cast(Layout) == static_cast(ColMajor)) { + m_fastOutputDepth = internal::TensorIntDivisor(m_dimensions[0]); + } else { + m_fastOutputDepth = internal::TensorIntDivisor(m_dimensions[NumDims-1]); + } + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; } + + EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) { + m_impl.evalSubExprsIfNeeded(NULL); + return true; + } + + EIGEN_STRONG_INLINE void cleanup() { + m_impl.cleanup(); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const + { + // Patch index corresponding to the passed in index. + const Index patchIndex = index / m_fastPatchStride; + + // Spatial offset within the patch. This has to be translated into 3D + // coordinates within the patch. + const Index patchOffset = (index - patchIndex * m_patchStride) / m_fastOutputDepth; + + // Batch, etc. + const Index otherIndex = (NumDims == 5) ? 0 : index / m_fastOtherStride; + const Index patch3DIndex = (NumDims == 5) ? patchIndex : (index - otherIndex * m_otherStride) / m_fastPatchStride; + + // Calculate column index in the input original tensor. + const Index colIndex = patch3DIndex / m_fastOutputPlanesRows; + const Index colOffset = patchOffset / m_fastColStride; + const Index inputCol = colIndex * m_col_strides + colOffset * m_in_col_strides - m_colPaddingLeft; + const Index origInputCol = (m_col_inflate_strides == 1) ? inputCol : ((inputCol >= 0) ? (inputCol / m_fastInputColStride) : 0); + if (inputCol < 0 || inputCol >= m_input_cols_eff || + ((m_col_inflate_strides != 1) && (inputCol != origInputCol * m_col_inflate_strides))) { + return Scalar(m_paddingValue); + } + + // Calculate row index in the original input tensor. + const Index rowIndex = (patch3DIndex - colIndex * m_outputPlanesRows) / m_fastOutputPlanes; + const Index rowOffset = (patchOffset - colOffset * m_colStride) / m_fastRowStride; + const Index inputRow = rowIndex * m_row_strides + rowOffset * m_in_row_strides - m_rowPaddingTop; + const Index origInputRow = (m_row_inflate_strides == 1) ? inputRow : ((inputRow >= 0) ? (inputRow / m_fastInputRowStride) : 0); + if (inputRow < 0 || inputRow >= m_input_rows_eff || + ((m_row_inflate_strides != 1) && (inputRow != origInputRow * m_row_inflate_strides))) { + return Scalar(m_paddingValue); + } + + // Calculate plane index in the original input tensor. + const Index planeIndex = (patch3DIndex - m_outputPlanes * (colIndex * m_outputRows + rowIndex)); + const Index planeOffset = patchOffset - colOffset * m_colStride - rowOffset * m_rowStride; + const Index inputPlane = planeIndex * m_plane_strides + planeOffset * m_in_plane_strides - m_planePaddingTop; + const Index origInputPlane = (m_plane_inflate_strides == 1) ? inputPlane : ((inputPlane >= 0) ? (inputPlane / m_fastInputPlaneStride) : 0); + if (inputPlane < 0 || inputPlane >= m_input_planes_eff || + ((m_plane_inflate_strides != 1) && (inputPlane != origInputPlane * m_plane_inflate_strides))) { + return Scalar(m_paddingValue); + } + + const int depth_index = static_cast(Layout) == static_cast(ColMajor) ? 0 : NumDims - 1; + const Index depth = index - (index / m_fastOutputDepth) * m_dimensions[depth_index]; + + const Index inputIndex = depth + + origInputRow * m_rowInputStride + + origInputCol * m_colInputStride + + origInputPlane * m_planeInputStride + + otherIndex * m_otherInputStride; + + return m_impl.coeff(inputIndex); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + eigen_assert(index+PacketSize-1 < dimensions().TotalSize()); + + if (m_in_row_strides != 1 || m_in_col_strides != 1 || m_row_inflate_strides != 1 || m_col_inflate_strides != 1 || + m_in_plane_strides != 1 || m_plane_inflate_strides != 1) { + return packetWithPossibleZero(index); + } + + const Index indices[2] = {index, index + PacketSize - 1}; + const Index patchIndex = indices[0] / m_fastPatchStride; + if (patchIndex != indices[1] / m_fastPatchStride) { + return packetWithPossibleZero(index); + } + const Index otherIndex = (NumDims == 5) ? 0 : indices[0] / m_fastOtherStride; + eigen_assert(otherIndex == indices[1] / m_fastOtherStride); + + // Find the offset of the element wrt the location of the first element. + const Index patchOffsets[2] = {(indices[0] - patchIndex * m_patchStride) / m_fastOutputDepth, + (indices[1] - patchIndex * m_patchStride) / m_fastOutputDepth}; + + const Index patch3DIndex = (NumDims == 5) ? patchIndex : (indices[0] - otherIndex * m_otherStride) / m_fastPatchStride; + eigen_assert(patch3DIndex == (indices[1] - otherIndex * m_otherStride) / m_fastPatchStride); + + const Index colIndex = patch3DIndex / m_fastOutputPlanesRows; + const Index colOffsets[2] = { + patchOffsets[0] / m_fastColStride, + patchOffsets[1] / m_fastColStride}; + + // Calculate col indices in the original input tensor. + const Index inputCols[2] = { + colIndex * m_col_strides + colOffsets[0] - m_colPaddingLeft, + colIndex * m_col_strides + colOffsets[1] - m_colPaddingLeft}; + if (inputCols[1] < 0 || inputCols[0] >= m_inputCols) { + return internal::pset1(Scalar(m_paddingValue)); + } + + if (inputCols[0] != inputCols[1]) { + return packetWithPossibleZero(index); + } + + const Index rowIndex = (patch3DIndex - colIndex * m_outputPlanesRows) / m_fastOutputPlanes; + const Index rowOffsets[2] = { + (patchOffsets[0] - colOffsets[0] * m_colStride) / m_fastRowStride, + (patchOffsets[1] - colOffsets[1] * m_colStride) / m_fastRowStride}; + eigen_assert(rowOffsets[0] <= rowOffsets[1]); + // Calculate col indices in the original input tensor. + const Index inputRows[2] = { + rowIndex * m_row_strides + rowOffsets[0] - m_rowPaddingTop, + rowIndex * m_row_strides + rowOffsets[1] - m_rowPaddingTop}; + + if (inputRows[1] < 0 || inputRows[0] >= m_inputRows) { + return internal::pset1(Scalar(m_paddingValue)); + } + + if (inputRows[0] != inputRows[1]) { + return packetWithPossibleZero(index); + } + + const Index planeIndex = (patch3DIndex - m_outputPlanes * (colIndex * m_outputRows + rowIndex)); + const Index planeOffsets[2] = { + patchOffsets[0] - colOffsets[0] * m_colStride - rowOffsets[0] * m_rowStride, + patchOffsets[1] - colOffsets[1] * m_colStride - rowOffsets[1] * m_rowStride}; + eigen_assert(planeOffsets[0] <= planeOffsets[1]); + const Index inputPlanes[2] = { + planeIndex * m_plane_strides + planeOffsets[0] - m_planePaddingTop, + planeIndex * m_plane_strides + planeOffsets[1] - m_planePaddingTop}; + + if (inputPlanes[1] < 0 || inputPlanes[0] >= m_inputPlanes) { + return internal::pset1(Scalar(m_paddingValue)); + } + + if (inputPlanes[0] >= 0 && inputPlanes[1] < m_inputPlanes) { + // no padding + const int depth_index = static_cast(Layout) == static_cast(ColMajor) ? 0 : NumDims - 1; + const Index depth = index - (index / m_fastOutputDepth) * m_dimensions[depth_index]; + const Index inputIndex = depth + + inputRows[0] * m_rowInputStride + + inputCols[0] * m_colInputStride + + m_planeInputStride * inputPlanes[0] + + otherIndex * m_otherInputStride; + return m_impl.template packet(inputIndex); + } + + return packetWithPossibleZero(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost + costPerCoeff(bool vectorized) const { + const double compute_cost = + 10 * TensorOpCost::DivCost() + 21 * TensorOpCost::MulCost() + + 8 * TensorOpCost::AddCost(); + return TensorOpCost(0, 0, compute_cost, vectorized, PacketSize); + } + + EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return NULL; } + + const TensorEvaluator& impl() const { return m_impl; } + + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index planePaddingTop() const { return m_planePaddingTop; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowPaddingTop() const { return m_rowPaddingTop; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colPaddingLeft() const { return m_colPaddingLeft; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outputPlanes() const { return m_outputPlanes; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outputRows() const { return m_outputRows; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index outputCols() const { return m_outputCols; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userPlaneStride() const { return m_plane_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userRowStride() const { return m_row_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userColStride() const { return m_col_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userInPlaneStride() const { return m_in_plane_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userInRowStride() const { return m_in_row_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index userInColStride() const { return m_in_col_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index planeInflateStride() const { return m_plane_inflate_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowInflateStride() const { return m_row_inflate_strides; } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colInflateStride() const { return m_col_inflate_strides; } + + protected: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetWithPossibleZero(Index index) const + { + EIGEN_ALIGN_MAX std::remove_const_t values[PacketSize]; + EIGEN_UNROLL_LOOP + for (int i = 0; i < PacketSize; ++i) { + values[i] = coeff(index+i); + } + PacketReturnType rslt = internal::pload(values); + return rslt; + } + + Dimensions m_dimensions; + + // Parameters passed to the constructor. + Index m_plane_strides; + Index m_row_strides; + Index m_col_strides; + + Index m_outputPlanes; + Index m_outputRows; + Index m_outputCols; + + Index m_planePaddingTop; + Index m_rowPaddingTop; + Index m_colPaddingLeft; + + Index m_in_plane_strides; + Index m_in_row_strides; + Index m_in_col_strides; + + Index m_plane_inflate_strides; + Index m_row_inflate_strides; + Index m_col_inflate_strides; + + // Cached input size. + Index m_inputDepth; + Index m_inputPlanes; + Index m_inputRows; + Index m_inputCols; + + // Other cached variables. + Index m_outputPlanesRows; + + // Effective input/patch post-inflation size. + Index m_input_planes_eff; + Index m_input_rows_eff; + Index m_input_cols_eff; + Index m_patch_planes_eff; + Index m_patch_rows_eff; + Index m_patch_cols_eff; + + // Strides for the output tensor. + Index m_otherStride; + Index m_patchStride; + Index m_rowStride; + Index m_colStride; + + // Strides for the input tensor. + Index m_planeInputStride; + Index m_rowInputStride; + Index m_colInputStride; + Index m_otherInputStride; + + internal::TensorIntDivisor m_fastOtherStride; + internal::TensorIntDivisor m_fastPatchStride; + internal::TensorIntDivisor m_fastColStride; + internal::TensorIntDivisor m_fastRowStride; + internal::TensorIntDivisor m_fastInputPlaneStride; + internal::TensorIntDivisor m_fastInputRowStride; + internal::TensorIntDivisor m_fastInputColStride; + internal::TensorIntDivisor m_fastInputColsEff; + internal::TensorIntDivisor m_fastOutputPlanesRows; + internal::TensorIntDivisor m_fastOutputPlanes; + internal::TensorIntDivisor m_fastOutputDepth; + + Scalar m_paddingValue; + + TensorEvaluator m_impl; + + +}; + + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSOR_TENSOR_VOLUME_PATCH_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/DynamicSymmetry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/DynamicSymmetry.h new file mode 100644 index 0000000000000000000000000000000000000000..200f5882ea372db06102e92450fc7b26c34b94c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/DynamicSymmetry.h @@ -0,0 +1,295 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSORSYMMETRY_DYNAMICSYMMETRY_H +#define EIGEN_CXX11_TENSORSYMMETRY_DYNAMICSYMMETRY_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +class DynamicSGroup +{ + public: + inline explicit DynamicSGroup() : m_numIndices(1), m_elements(), m_generators(), m_globalFlags(0) { m_elements.push_back(ge(Generator(0, 0, 0))); } + inline DynamicSGroup(const DynamicSGroup& o) : m_numIndices(o.m_numIndices), m_elements(o.m_elements), m_generators(o.m_generators), m_globalFlags(o.m_globalFlags) { } + inline DynamicSGroup(DynamicSGroup&& o) : m_numIndices(o.m_numIndices), m_elements(), m_generators(o.m_generators), m_globalFlags(o.m_globalFlags) { std::swap(m_elements, o.m_elements); } + inline DynamicSGroup& operator=(const DynamicSGroup& o) { m_numIndices = o.m_numIndices; m_elements = o.m_elements; m_generators = o.m_generators; m_globalFlags = o.m_globalFlags; return *this; } + inline DynamicSGroup& operator=(DynamicSGroup&& o) { m_numIndices = o.m_numIndices; std::swap(m_elements, o.m_elements); m_generators = o.m_generators; m_globalFlags = o.m_globalFlags; return *this; } + + void add(int one, int two, int flags = 0); + + template + inline void add(Gen_) { add(Gen_::One, Gen_::Two, Gen_::Flags); } + inline void addSymmetry(int one, int two) { add(one, two, 0); } + inline void addAntiSymmetry(int one, int two) { add(one, two, NegationFlag); } + inline void addHermiticity(int one, int two) { add(one, two, ConjugationFlag); } + inline void addAntiHermiticity(int one, int two) { add(one, two, NegationFlag | ConjugationFlag); } + + template + inline RV apply(const std::array& idx, RV initial, Args&&... args) const + { + eigen_assert(N >= m_numIndices && "Can only apply symmetry group to objects that have at least the required amount of indices."); + for (std::size_t i = 0; i < size(); i++) + initial = Op::run(h_permute(i, idx, typename internal::gen_numeric_list::type()), m_elements[i].flags, initial, std::forward(args)...); + return initial; + } + + template + inline RV apply(const std::vector& idx, RV initial, Args&&... args) const + { + eigen_assert(idx.size() >= m_numIndices && "Can only apply symmetry group to objects that have at least the required amount of indices."); + for (std::size_t i = 0; i < size(); i++) + initial = Op::run(h_permute(i, idx), m_elements[i].flags, initial, std::forward(args)...); + return initial; + } + + inline int globalFlags() const { return m_globalFlags; } + inline std::size_t size() const { return m_elements.size(); } + + template + inline internal::tensor_symmetry_value_setter operator()(Tensor_& tensor, typename Tensor_::Index firstIndex, IndexTypes... otherIndices) const + { + static_assert(sizeof...(otherIndices) + 1 == Tensor_::NumIndices, "Number of indices used to access a tensor coefficient must be equal to the rank of the tensor."); + return operator()(tensor, std::array{{firstIndex, otherIndices...}}); + } + + template + inline internal::tensor_symmetry_value_setter operator()(Tensor_& tensor, std::array const& indices) const + { + return internal::tensor_symmetry_value_setter(tensor, *this, indices); + } + private: + struct GroupElement { + std::vector representation; + int flags; + bool isId() const + { + for (std::size_t i = 0; i < representation.size(); i++) + if (i != (size_t)representation[i]) + return false; + return true; + } + }; + struct Generator { + int one; + int two; + int flags; + constexpr inline Generator(int one_, int two_, int flags_) : one(one_), two(two_), flags(flags_) {} + }; + + std::size_t m_numIndices; + std::vector m_elements; + std::vector m_generators; + int m_globalFlags; + + template + inline std::array h_permute(std::size_t which, const std::array& idx, internal::numeric_list) const + { + return std::array{{ idx[n >= m_numIndices ? n : m_elements[which].representation[n]]... }}; + } + + template + inline std::vector h_permute(std::size_t which, std::vector idx) const + { + std::vector result; + result.reserve(idx.size()); + for (auto k : m_elements[which].representation) + result.push_back(idx[k]); + for (std::size_t i = m_numIndices; i < idx.size(); i++) + result.push_back(idx[i]); + return result; + } + + inline GroupElement ge(Generator const& g) const + { + GroupElement result; + result.representation.reserve(m_numIndices); + result.flags = g.flags; + for (std::size_t k = 0; k < m_numIndices; k++) { + if (k == (std::size_t)g.one) + result.representation.push_back(g.two); + else if (k == (std::size_t)g.two) + result.representation.push_back(g.one); + else + result.representation.push_back(int(k)); + } + return result; + } + + GroupElement mul(GroupElement, GroupElement) const; + inline GroupElement mul(Generator g1, GroupElement g2) const + { + return mul(ge(g1), g2); + } + + inline GroupElement mul(GroupElement g1, Generator g2) const + { + return mul(g1, ge(g2)); + } + + inline GroupElement mul(Generator g1, Generator g2) const + { + return mul(ge(g1), ge(g2)); + } + + inline int findElement(GroupElement e) const + { + for (auto ee : m_elements) { + if (ee.representation == e.representation) + return ee.flags ^ e.flags; + } + return -1; + } + + void updateGlobalFlags(int flagDiffOfSameGenerator); +}; + +// dynamic symmetry group that auto-adds the template parameters in the constructor +template +class DynamicSGroupFromTemplateArgs : public DynamicSGroup +{ + public: + inline DynamicSGroupFromTemplateArgs() : DynamicSGroup() + { + add_all(internal::type_list()); + } + inline DynamicSGroupFromTemplateArgs(DynamicSGroupFromTemplateArgs const& other) : DynamicSGroup(other) { } + inline DynamicSGroupFromTemplateArgs(DynamicSGroupFromTemplateArgs&& other) : DynamicSGroup(other) { } + inline DynamicSGroupFromTemplateArgs& operator=(const DynamicSGroupFromTemplateArgs& o) { DynamicSGroup::operator=(o); return *this; } + inline DynamicSGroupFromTemplateArgs& operator=(DynamicSGroupFromTemplateArgs&& o) { DynamicSGroup::operator=(o); return *this; } + + private: + template + inline void add_all(internal::type_list) + { + add(Gen1()); + add_all(internal::type_list()); + } + + inline void add_all(internal::type_list<>) + { + } +}; + +inline DynamicSGroup::GroupElement DynamicSGroup::mul(GroupElement g1, GroupElement g2) const +{ + eigen_internal_assert(g1.representation.size() == m_numIndices); + eigen_internal_assert(g2.representation.size() == m_numIndices); + + GroupElement result; + result.representation.reserve(m_numIndices); + for (std::size_t i = 0; i < m_numIndices; i++) { + int v = g2.representation[g1.representation[i]]; + eigen_assert(v >= 0); + result.representation.push_back(v); + } + result.flags = g1.flags ^ g2.flags; + return result; +} + +inline void DynamicSGroup::add(int one, int two, int flags) +{ + eigen_assert(one >= 0); + eigen_assert(two >= 0); + eigen_assert(one != two); + + if ((std::size_t)one >= m_numIndices || (std::size_t)two >= m_numIndices) { + std::size_t newNumIndices = (one > two) ? one : two + 1; + for (auto& gelem : m_elements) { + gelem.representation.reserve(newNumIndices); + for (std::size_t i = m_numIndices; i < newNumIndices; i++) + gelem.representation.push_back(i); + } + m_numIndices = newNumIndices; + } + + Generator g{one, two, flags}; + GroupElement e = ge(g); + + /* special case for first generator */ + if (m_elements.size() == 1) { + while (!e.isId()) { + m_elements.push_back(e); + e = mul(e, g); + } + + if (e.flags > 0) + updateGlobalFlags(e.flags); + + // only add in case we didn't have identity + if (m_elements.size() > 1) + m_generators.push_back(g); + return; + } + + int p = findElement(e); + if (p >= 0) { + updateGlobalFlags(p); + return; + } + + std::size_t coset_order = m_elements.size(); + m_elements.push_back(e); + for (std::size_t i = 1; i < coset_order; i++) + m_elements.push_back(mul(m_elements[i], e)); + m_generators.push_back(g); + + std::size_t coset_rep = coset_order; + do { + for (auto g : m_generators) { + e = mul(m_elements[coset_rep], g); + p = findElement(e); + if (p < 0) { + // element not yet in group + m_elements.push_back(e); + for (std::size_t i = 1; i < coset_order; i++) + m_elements.push_back(mul(m_elements[i], e)); + } else if (p > 0) { + updateGlobalFlags(p); + } + } + coset_rep += coset_order; + } while (coset_rep < m_elements.size()); +} + +inline void DynamicSGroup::updateGlobalFlags(int flagDiffOfSameGenerator) +{ + switch (flagDiffOfSameGenerator) { + case 0: + default: + // nothing happened + break; + case NegationFlag: + // every element is it's own negative => whole tensor is zero + m_globalFlags |= GlobalZeroFlag; + break; + case ConjugationFlag: + // every element is it's own conjugate => whole tensor is real + m_globalFlags |= GlobalRealFlag; + break; + case (NegationFlag | ConjugationFlag): + // every element is it's own negative conjugate => whole tensor is imaginary + m_globalFlags |= GlobalImagFlag; + break; + /* NOTE: + * since GlobalZeroFlag == GlobalRealFlag | GlobalImagFlag, if one generator + * causes the tensor to be real and the next one to be imaginary, this will + * trivially give the correct result + */ + } +} + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSORSYMMETRY_DYNAMICSYMMETRY_H + +/* + * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; + */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..b0affe68c1f9ce066c0a6725c7dcd683005066f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_CXX11_TENSORSYMMETRY_MODULE_H +#error "Please include unsupported/Eigen/CXX11/TensorSymmetry instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/StaticSymmetry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/StaticSymmetry.h new file mode 100644 index 0000000000000000000000000000000000000000..e87403a3c9bb93da4775a1301450aa455d8ffac1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/StaticSymmetry.h @@ -0,0 +1,238 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSORSYMMETRY_STATICSYMMETRY_H +#define EIGEN_CXX11_TENSORSYMMETRY_STATICSYMMETRY_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template struct tensor_static_symgroup_permutate; + +template +struct tensor_static_symgroup_permutate> +{ + constexpr static std::size_t N = sizeof...(nn); + + template + constexpr static inline std::array run(const std::array& indices) + { + return {{indices[nn]...}}; + } +}; + +template +struct tensor_static_symgroup_element +{ + typedef indices_ indices; + constexpr static int flags = flags_; +}; + +template +struct tensor_static_symgroup_element_ctor +{ + typedef tensor_static_symgroup_element< + typename gen_numeric_list_swapped_pair::type, + Gen::Flags + > type; +}; + +template +struct tensor_static_symgroup_identity_ctor +{ + typedef tensor_static_symgroup_element< + typename gen_numeric_list::type, + 0 + > type; +}; + +template +struct tensor_static_symgroup_multiply_helper +{ + template + constexpr static inline numeric_list::value...> helper(numeric_list) { + return numeric_list::value...>(); + } +}; + +template +struct tensor_static_symgroup_multiply +{ + private: + typedef typename A::indices iia; + typedef typename B::indices iib; + constexpr static int ffa = A::flags; + constexpr static int ffb = B::flags; + + public: + static_assert(iia::count == iib::count, "Cannot multiply symmetry elements with different number of indices."); + + typedef tensor_static_symgroup_element< + decltype(tensor_static_symgroup_multiply_helper::helper(iia())), + ffa ^ ffb + > type; +}; + +template +struct tensor_static_symgroup_equality +{ + typedef typename A::indices iia; + typedef typename B::indices iib; + constexpr static int ffa = A::flags; + constexpr static int ffb = B::flags; + static_assert(iia::count == iib::count, "Cannot compare symmetry elements with different number of indices."); + + constexpr static bool value = is_same::value; + + private: + /* this should be zero if they are identical, or else the tensor + * will be forced to be pure real, pure imaginary or even pure zero + */ + constexpr static int flags_cmp_ = ffa ^ ffb; + + /* either they are not equal, then we don't care whether the flags + * match, or they are equal, and then we have to check + */ + constexpr static bool is_zero = value && flags_cmp_ == NegationFlag; + constexpr static bool is_real = value && flags_cmp_ == ConjugationFlag; + constexpr static bool is_imag = value && flags_cmp_ == (NegationFlag | ConjugationFlag); + + public: + constexpr static int global_flags = + (is_real ? GlobalRealFlag : 0) | + (is_imag ? GlobalImagFlag : 0) | + (is_zero ? GlobalZeroFlag : 0); +}; + +template +struct tensor_static_symgroup +{ + typedef StaticSGroup type; + constexpr static std::size_t size = type::static_size; +}; + +template +constexpr static inline std::array tensor_static_symgroup_index_permute(std::array idx, internal::numeric_list, internal::numeric_list) +{ + return {{ idx[ii]..., idx[jj]... }}; +} + +template +static inline std::vector tensor_static_symgroup_index_permute(std::vector idx, internal::numeric_list) +{ + std::vector result{{ idx[ii]... }}; + std::size_t target_size = idx.size(); + for (std::size_t i = result.size(); i < target_size; i++) + result.push_back(idx[i]); + return result; +} + +template struct tensor_static_symgroup_do_apply; + +template +struct tensor_static_symgroup_do_apply> +{ + template + static inline RV run(const std::array& idx, RV initial, Args&&... args) + { + static_assert(NumIndices >= SGNumIndices, "Can only apply symmetry group to objects that have at least the required amount of indices."); + typedef typename internal::gen_numeric_list::type remaining_indices; + initial = Op::run(tensor_static_symgroup_index_permute(idx, typename first::indices(), remaining_indices()), first::flags, initial, std::forward(args)...); + return tensor_static_symgroup_do_apply>::template run(idx, initial, args...); + } + + template + static inline RV run(const std::vector& idx, RV initial, Args&&... args) + { + eigen_assert(idx.size() >= SGNumIndices && "Can only apply symmetry group to objects that have at least the required amount of indices."); + initial = Op::run(tensor_static_symgroup_index_permute(idx, typename first::indices()), first::flags, initial, std::forward(args)...); + return tensor_static_symgroup_do_apply>::template run(idx, initial, args...); + } +}; + +template +struct tensor_static_symgroup_do_apply> +{ + template + static inline RV run(const std::array&, RV initial, Args&&...) + { + // do nothing + return initial; + } + + template + static inline RV run(const std::vector&, RV initial, Args&&...) + { + // do nothing + return initial; + } +}; + +} // end namespace internal + +template +class StaticSGroup +{ + constexpr static std::size_t NumIndices = internal::tensor_symmetry_num_indices::value; + typedef internal::group_theory::enumerate_group_elements< + internal::tensor_static_symgroup_multiply, + internal::tensor_static_symgroup_equality, + typename internal::tensor_static_symgroup_identity_ctor::type, + internal::type_list::type...> + > group_elements; + typedef typename group_elements::type ge; + public: + constexpr inline StaticSGroup() {} + constexpr inline StaticSGroup(const StaticSGroup&) {} + constexpr inline StaticSGroup(StaticSGroup&&) {} + + template + static inline RV apply(const std::array& idx, RV initial, Args&&... args) + { + return internal::tensor_static_symgroup_do_apply::template run(idx, initial, args...); + } + + template + static inline RV apply(const std::vector& idx, RV initial, Args&&... args) + { + eigen_assert(idx.size() == NumIndices); + return internal::tensor_static_symgroup_do_apply::template run(idx, initial, args...); + } + + constexpr static std::size_t static_size = ge::count; + + constexpr static inline std::size_t size() { + return ge::count; + } + constexpr static inline int globalFlags() { return group_elements::global_flags; } + + template + inline internal::tensor_symmetry_value_setter> operator()(Tensor_& tensor, typename Tensor_::Index firstIndex, IndexTypes... otherIndices) const + { + static_assert(sizeof...(otherIndices) + 1 == Tensor_::NumIndices, "Number of indices used to access a tensor coefficient must be equal to the rank of the tensor."); + return operator()(tensor, std::array{{firstIndex, otherIndices...}}); + } + + template + inline internal::tensor_symmetry_value_setter> operator()(Tensor_& tensor, std::array const& indices) const + { + return internal::tensor_symmetry_value_setter>(tensor, *this, indices); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSORSYMMETRY_STATICSYMMETRY_H + +/* + * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; + */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/Symmetry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/Symmetry.h new file mode 100644 index 0000000000000000000000000000000000000000..a95f79c4fd348bf9e16bc9fdf5dfe50f87cd00b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/Symmetry.h @@ -0,0 +1,340 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSORSYMMETRY_SYMMETRY_H +#define EIGEN_CXX11_TENSORSYMMETRY_SYMMETRY_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +enum { + NegationFlag = 0x01, + ConjugationFlag = 0x02 +}; + +enum { + GlobalRealFlag = 0x01, + GlobalImagFlag = 0x02, + GlobalZeroFlag = 0x03 +}; + +namespace internal { + +template struct tensor_symmetry_pre_analysis; +template struct tensor_static_symgroup; +template struct tensor_static_symgroup_if; +template struct tensor_symmetry_calculate_flags; +template struct tensor_symmetry_assign_value; +template struct tensor_symmetry_num_indices; + +} // end namespace internal + +template +struct Symmetry +{ + static_assert(One_ != Two_, "Symmetries must cover distinct indices."); + constexpr static int One = One_; + constexpr static int Two = Two_; + constexpr static int Flags = 0; +}; + +template +struct AntiSymmetry +{ + static_assert(One_ != Two_, "Symmetries must cover distinct indices."); + constexpr static int One = One_; + constexpr static int Two = Two_; + constexpr static int Flags = NegationFlag; +}; + +template +struct Hermiticity +{ + static_assert(One_ != Two_, "Symmetries must cover distinct indices."); + constexpr static int One = One_; + constexpr static int Two = Two_; + constexpr static int Flags = ConjugationFlag; +}; + +template +struct AntiHermiticity +{ + static_assert(One_ != Two_, "Symmetries must cover distinct indices."); + constexpr static int One = One_; + constexpr static int Two = Two_; + constexpr static int Flags = ConjugationFlag | NegationFlag; +}; + +/** \class DynamicSGroup + * \ingroup TensorSymmetry_Module + * + * \brief Dynamic symmetry group + * + * The %DynamicSGroup class represents a symmetry group that need not be known at + * compile time. It is useful if one wants to support arbitrary run-time defineable + * symmetries for tensors, but it is also instantiated if a symmetry group is defined + * at compile time that would be either too large for the compiler to reasonably + * generate (using templates to calculate this at compile time is very inefficient) + * or that the compiler could generate the group but that it wouldn't make sense to + * unroll the loop for setting coefficients anymore. + */ +class DynamicSGroup; + +/** \internal + * + * \class DynamicSGroupFromTemplateArgs + * \ingroup TensorSymmetry_Module + * + * \brief Dynamic symmetry group, initialized from template arguments + * + * This class is a child class of DynamicSGroup. It uses the template arguments + * specified to initialize itself. + */ +template +class DynamicSGroupFromTemplateArgs; + +/** \class StaticSGroup + * \ingroup TensorSymmetry_Module + * + * \brief Static symmetry group + * + * This class represents a symmetry group that is known and resolved completely + * at compile time. Ideally, no run-time penalty is incurred compared to the + * manual unrolling of the symmetry. + * + * CAUTION: + * + * Do not use this class directly for large symmetry groups. The compiler + * may run into a limit, or segfault or in the very least will take a very, + * very, very long time to compile the code. Use the SGroup class instead + * if you want a static group. That class contains logic that will + * automatically select the DynamicSGroup class instead if the symmetry + * group becomes too large. (In that case, unrolling may not even be + * beneficial.) + */ +template +class StaticSGroup; + +/** \class SGroup + * \ingroup TensorSymmetry_Module + * + * \brief Symmetry group, initialized from template arguments + * + * This class represents a symmetry group whose generators are already + * known at compile time. It may or may not be resolved at compile time, + * depending on the estimated size of the group. + * + * \sa StaticSGroup + * \sa DynamicSGroup + */ +template +class SGroup : public internal::tensor_symmetry_pre_analysis::value, Gen...>::root_type +{ + public: + constexpr static std::size_t NumIndices = internal::tensor_symmetry_num_indices::value; + typedef typename internal::tensor_symmetry_pre_analysis::root_type Base; + + // make standard constructors + assignment operators public + inline SGroup() : Base() { } + inline SGroup(const SGroup& other) : Base(other) { } + inline SGroup(SGroup&& other) : Base(other) { } + inline SGroup& operator=(const SGroup& other) { Base::operator=(other); return *this; } + inline SGroup& operator=(SGroup&& other) { Base::operator=(other); return *this; } + + // all else is defined in the base class +}; + +namespace internal { + +template struct tensor_symmetry_num_indices +{ + constexpr static std::size_t value = 1; +}; + +template struct tensor_symmetry_num_indices, Sym...> +{ +private: + constexpr static std::size_t One = static_cast(One_); + constexpr static std::size_t Two = static_cast(Two_); + constexpr static std::size_t Three = tensor_symmetry_num_indices::value; + + // don't use std::max, since it's not constexpr until C++14... + constexpr static std::size_t maxOneTwoPlusOne = ((One > Two) ? One : Two) + 1; +public: + constexpr static std::size_t value = (maxOneTwoPlusOne > Three) ? maxOneTwoPlusOne : Three; +}; + +template struct tensor_symmetry_num_indices, Sym...> + : public tensor_symmetry_num_indices, Sym...> {}; +template struct tensor_symmetry_num_indices, Sym...> + : public tensor_symmetry_num_indices, Sym...> {}; +template struct tensor_symmetry_num_indices, Sym...> + : public tensor_symmetry_num_indices, Sym...> {}; + +/** \internal + * + * \class tensor_symmetry_pre_analysis + * \ingroup TensorSymmetry_Module + * + * \brief Pre-select whether to use a static or dynamic symmetry group + * + * When a symmetry group could in principle be determined at compile time, + * this template implements the logic whether to actually do that or whether + * to rather defer that to runtime. + * + * The logic is as follows: + *
+ *
No generators (trivial symmetry):
+ *
Use a trivial static group. Ideally, this has no performance impact + * compared to not using symmetry at all. In practice, this might not + * be the case.
+ *
More than 4 generators:
+ *
Calculate the group at run time, it is likely far too large for the + * compiler to be able to properly generate it in a realistic time.
+ *
Up to and including 4 generators:
+ *
Actually enumerate all group elements, but then check how many there + * are. If there are more than 16, it is unlikely that unrolling the + * loop (as is done in the static compile-time case) is sensible, so + * use a dynamic group instead. If there are at most 16 elements, actually + * use that static group. Note that the largest group with 4 generators + * still compiles with reasonable resources.
+ *
+ * + * Note: Example compile time performance with g++-4.6 on an Intenl Core i5-3470 + * with 16 GiB RAM (all generators non-redundant and the subgroups don't + * factorize): + * + * # Generators -O0 -ggdb -O2 + * ------------------------------------------------------------------- + * 1 0.5 s / 250 MiB 0.45s / 230 MiB + * 2 0.5 s / 260 MiB 0.5 s / 250 MiB + * 3 0.65s / 310 MiB 0.62s / 310 MiB + * 4 2.2 s / 860 MiB 1.7 s / 770 MiB + * 5 130 s / 13000 MiB 120 s / 11000 MiB + * + * It is clear that everything is still very efficient up to 4 generators, then + * the memory and CPU requirements become unreasonable. Thus we only instantiate + * the template group theory logic if the number of generators supplied is 4 or + * lower, otherwise this will be forced to be done during runtime, where the + * algorithm is reasonably fast. + */ +template +struct tensor_symmetry_pre_analysis +{ + typedef StaticSGroup<> root_type; +}; + +template +struct tensor_symmetry_pre_analysis +{ + constexpr static std::size_t max_static_generators = 4; + constexpr static std::size_t max_static_elements = 16; + typedef tensor_static_symgroup_if<(sizeof...(Gens_) + 1 <= max_static_generators), NumIndices, Gen_, Gens_...> helper; + constexpr static std::size_t possible_size = helper::size; + + typedef std::conditional_t< + possible_size == 0 || possible_size >= max_static_elements, + DynamicSGroupFromTemplateArgs, + typename helper::type + > root_type; +}; + +template +struct tensor_static_symgroup_if +{ + constexpr static std::size_t size = 0; + typedef void type; +}; + +template +struct tensor_static_symgroup_if : tensor_static_symgroup {}; + +template +struct tensor_symmetry_assign_value +{ + typedef typename Tensor_::Index Index; + typedef typename Tensor_::Scalar Scalar; + constexpr static std::size_t NumIndices = Tensor_::NumIndices; + + static inline int run(const std::array& transformed_indices, int transformation_flags, int dummy, Tensor_& tensor, const Scalar& value_) + { + Scalar value(value_); + if (transformation_flags & ConjugationFlag) + value = numext::conj(value); + if (transformation_flags & NegationFlag) + value = -value; + tensor.coeffRef(transformed_indices) = value; + return dummy; + } +}; + +template +struct tensor_symmetry_calculate_flags +{ + typedef typename Tensor_::Index Index; + constexpr static std::size_t NumIndices = Tensor_::NumIndices; + + static inline int run(const std::array& transformed_indices, int transform_flags, int current_flags, const std::array& orig_indices) + { + if (transformed_indices == orig_indices) { + if (transform_flags & (ConjugationFlag | NegationFlag)) + return current_flags | GlobalImagFlag; // anti-hermitian diagonal + else if (transform_flags & ConjugationFlag) + return current_flags | GlobalRealFlag; // hermitian diagonal + else if (transform_flags & NegationFlag) + return current_flags | GlobalZeroFlag; // anti-symmetric diagonal + } + return current_flags; + } +}; + +template +class tensor_symmetry_value_setter +{ + public: + typedef typename Tensor_::Index Index; + typedef typename Tensor_::Scalar Scalar; + constexpr static std::size_t NumIndices = Tensor_::NumIndices; + + inline tensor_symmetry_value_setter(Tensor_& tensor, Symmetry_ const& symmetry, std::array const& indices) + : m_tensor(tensor), m_symmetry(symmetry), m_indices(indices) { } + + inline tensor_symmetry_value_setter& operator=(Scalar const& value) + { + doAssign(value); + return *this; + } + private: + Tensor_& m_tensor; + Symmetry_ m_symmetry; + std::array m_indices; + + inline void doAssign(Scalar const& value) + { + #ifdef EIGEN_TENSOR_SYMMETRY_CHECK_VALUES + int value_flags = m_symmetry.template apply, int>(m_indices, m_symmetry.globalFlags(), m_indices); + if (value_flags & GlobalRealFlag) + eigen_assert(numext::imag(value) == 0); + if (value_flags & GlobalImagFlag) + eigen_assert(numext::real(value) == 0); + #endif + m_symmetry.template apply, int>(m_indices, 0, m_tensor, value); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSORSYMMETRY_SYMMETRY_H + +/* + * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; + */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h new file mode 100644 index 0000000000000000000000000000000000000000..c27d1ed8f91131cb01c3c282bb4f6e716d2f1573 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h @@ -0,0 +1,671 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11_TENSORSYMMETRY_TEMPLATEGROUPTHEORY_H +#define EIGEN_CXX11_TENSORSYMMETRY_TEMPLATEGROUPTHEORY_H + +#include "../InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +namespace group_theory { + +/** \internal + * \file CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h + * This file contains C++ templates that implement group theory algorithms. + * + * The algorithms allow for a compile-time analysis of finite groups. + * + * Currently only Dimino's algorithm is implemented, which returns a list + * of all elements in a group given a set of (possibly redundant) generators. + * (One could also do that with the so-called orbital algorithm, but that + * is much more expensive and usually has no advantages.) + */ + +/********************************************************************** + * "Ok kid, here is where it gets complicated." + * - Amelia Pond in the "Doctor Who" episode + * "The Big Bang" + * + * Dimino's algorithm + * ================== + * + * The following is Dimino's algorithm in sequential form: + * + * Input: identity element, list of generators, equality check, + * multiplication operation + * Output: list of group elements + * + * 1. add identity element + * 2. remove identities from list of generators + * 3. add all powers of first generator that aren't the + * identity element + * 4. go through all remaining generators: + * a. if generator is already in the list of elements + * -> do nothing + * b. otherwise + * i. remember current # of elements + * (i.e. the size of the current subgroup) + * ii. add all current elements (which includes + * the identity) each multiplied from right + * with the current generator to the group + * iii. add all remaining cosets that are generated + * by products of the new generator with itself + * and all other generators seen so far + * + * In functional form, this is implemented as a long set of recursive + * templates that have a complicated relationship. + * + * The main interface for Dimino's algorithm is the template + * enumerate_group_elements. All lists are implemented as variadic + * type_list and numeric_list + * templates. + * + * 'Calling' templates is usually done via typedefs. + * + * This algorithm is an extended version of the basic version. The + * extension consists in the fact that each group element has a set + * of flags associated with it. Multiplication of two group elements + * with each other results in a group element whose flags are the + * XOR of the flags of the previous elements. Each time the algorithm + * notices that a group element it just calculated is already in the + * list of current elements, the flags of both will be compared and + * added to the so-called 'global flags' of the group. + * + * The rationale behind this extension is that this allows not only + * for the description of symmetries between tensor indices, but + * also allows for the description of hermiticity, antisymmetry and + * antihermiticity. Negation and conjugation each are specific bit + * in the flags value and if two different ways to reach a group + * element lead to two different flags, this poses a constraint on + * the allowed values of the resulting tensor. For example, if a + * group element is reach both with and without the conjugation + * flags, it is clear that the resulting tensor has to be real. + * + * Note that this flag mechanism is quite generic and may have other + * uses beyond tensor properties. + * + * IMPORTANT: + * This algorithm assumes the group to be finite. If you try to + * run it with a group that's infinite, the algorithm will only + * terminate once you hit a compiler limit (max template depth). + * Also note that trying to use this implementation to create a + * very large group will probably either make you hit the same + * limit, cause the compiler to segfault or at the very least + * take a *really* long time (hours, days, weeks - sic!) to + * compile. It is not recommended to plug in more than 4 + * generators, unless they are independent of each other. + */ + +/** \internal + * + * \class strip_identities + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Cleanse a list of group elements of the identity element + * + * This template is used to make a first pass through all initial + * generators of Dimino's algorithm and remove the identity + * elements. + * + * \sa enumerate_group_elements + */ +template class Equality, typename id, typename L> struct strip_identities; + +template< + template class Equality, + typename id, + typename t, + typename... ts +> +struct strip_identities> +{ + typedef std::conditional_t< + Equality::value, + typename strip_identities>::type, + typename concat, typename strip_identities>::type>::type + > type; + constexpr static int global_flags = Equality::global_flags | strip_identities>::global_flags; +}; + +template< + template class Equality, + typename id + EIGEN_TPL_PP_SPEC_HACK_DEFC(typename, ts) +> +struct strip_identities> +{ + typedef type_list<> type; + constexpr static int global_flags = 0; +}; + +/** \internal + * + * \class dimino_first_step_elements_helper + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Recursive template that adds powers of the first generator to the list of group elements + * + * This template calls itself recursively to add powers of the first + * generator to the list of group elements. It stops if it reaches + * the identity element again. + * + * \sa enumerate_group_elements, dimino_first_step_elements + */ +template< + template class Multiply, + template class Equality, + typename id, + typename g, + typename current_element, + typename elements, + bool dont_add_current_element // = false +> +struct dimino_first_step_elements_helper +#ifndef EIGEN_PARSED_BY_DOXYGEN + : // recursive inheritance is too difficult for Doxygen + public dimino_first_step_elements_helper< + Multiply, + Equality, + id, + g, + typename Multiply::type, + typename concat>::type, + Equality::type, id>::value + > {}; + +template< + template class Multiply, + template class Equality, + typename id, + typename g, + typename current_element, + typename elements +> +struct dimino_first_step_elements_helper +#endif // EIGEN_PARSED_BY_DOXYGEN +{ + typedef elements type; + constexpr static int global_flags = Equality::global_flags; +}; + +/** \internal + * + * \class dimino_first_step_elements + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Add all powers of the first generator to the list of group elements + * + * This template takes the first non-identity generator and generates the initial + * list of elements which consists of all powers of that generator. For a group + * with just one generated, it would be enumerated after this. + * + * \sa enumerate_group_elements + */ +template< + template class Multiply, + template class Equality, + typename id, + typename generators +> +struct dimino_first_step_elements +{ + typedef typename get<0, generators>::type first_generator; + typedef typename skip<1, generators>::type next_generators; + typedef type_list generators_done; + + typedef dimino_first_step_elements_helper< + Multiply, + Equality, + id, + first_generator, + first_generator, + type_list, + false + > helper; + typedef typename helper::type type; + constexpr static int global_flags = helper::global_flags; +}; + +/** \internal + * + * \class dimino_get_coset_elements + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Generate all elements of a specific coset + * + * This template generates all the elements of a specific coset by + * multiplying all elements in the given subgroup with the new + * coset representative. Note that the first element of the + * subgroup is always the identity element, so the first element of + * the result of this template is going to be the coset + * representative itself. + * + * Note that this template accepts an additional boolean parameter + * that specifies whether to actually generate the coset (true) or + * just return an empty list (false). + * + * \sa enumerate_group_elements, dimino_add_cosets_for_rep + */ +template< + template class Multiply, + typename sub_group_elements, + typename new_coset_rep, + bool generate_coset // = true +> +struct dimino_get_coset_elements +{ + typedef typename apply_op_from_right::type type; +}; + +template< + template class Multiply, + typename sub_group_elements, + typename new_coset_rep +> +struct dimino_get_coset_elements +{ + typedef type_list<> type; +}; + +/** \internal + * + * \class dimino_add_cosets_for_rep + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Recursive template for adding coset spaces + * + * This template multiplies the coset representative with a generator + * from the list of previous generators. If the new element is not in + * the group already, it adds the corresponding coset. Finally it + * proceeds to call itself with the next generator from the list. + * + * \sa enumerate_group_elements, dimino_add_all_coset_spaces + */ +template< + template class Multiply, + template class Equality, + typename id, + typename sub_group_elements, + typename elements, + typename generators, + typename rep_element, + int sub_group_size +> +struct dimino_add_cosets_for_rep; + +template< + template class Multiply, + template class Equality, + typename id, + typename sub_group_elements, + typename elements, + typename g, + typename... gs, + typename rep_element, + int sub_group_size +> +struct dimino_add_cosets_for_rep, rep_element, sub_group_size> +{ + typedef typename Multiply::type new_coset_rep; + typedef contained_in_list_gf _cil; + constexpr static bool add_coset = !_cil::value; + + typedef typename dimino_get_coset_elements< + Multiply, + sub_group_elements, + new_coset_rep, + add_coset + >::type coset_elements; + + typedef dimino_add_cosets_for_rep< + Multiply, + Equality, + id, + sub_group_elements, + typename concat::type, + type_list, + rep_element, + sub_group_size + > _helper; + + typedef typename _helper::type type; + constexpr static int global_flags = _cil::global_flags | _helper::global_flags; + + /* Note that we don't have to update global flags here, since + * we will only add these elements if they are not part of + * the group already. But that only happens if the coset rep + * is not already in the group, so the check for the coset rep + * will catch this. + */ +}; + +template< + template class Multiply, + template class Equality, + typename id, + typename sub_group_elements, + typename elements + EIGEN_TPL_PP_SPEC_HACK_DEFC(typename, empty), + typename rep_element, + int sub_group_size +> +struct dimino_add_cosets_for_rep, rep_element, sub_group_size> +{ + typedef elements type; + constexpr static int global_flags = 0; +}; + +/** \internal + * + * \class dimino_add_all_coset_spaces + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Recursive template for adding all coset spaces for a new generator + * + * This template tries to go through the list of generators (with + * the help of the dimino_add_cosets_for_rep template) as long as + * it still finds elements that are not part of the group and add + * the corresponding cosets. + * + * \sa enumerate_group_elements, dimino_add_cosets_for_rep + */ +template< + template class Multiply, + template class Equality, + typename id, + typename sub_group_elements, + typename elements, + typename generators, + int sub_group_size, + int rep_pos, + bool stop_condition // = false +> +struct dimino_add_all_coset_spaces +{ + typedef typename get::type rep_element; + typedef dimino_add_cosets_for_rep< + Multiply, + Equality, + id, + sub_group_elements, + elements, + generators, + rep_element, + sub_group_elements::count + > _ac4r; + typedef typename _ac4r::type new_elements; + + constexpr static int new_rep_pos = rep_pos + sub_group_elements::count; + constexpr static bool new_stop_condition = new_rep_pos >= new_elements::count; + + typedef dimino_add_all_coset_spaces< + Multiply, + Equality, + id, + sub_group_elements, + new_elements, + generators, + sub_group_size, + new_rep_pos, + new_stop_condition + > _helper; + + typedef typename _helper::type type; + constexpr static int global_flags = _helper::global_flags | _ac4r::global_flags; +}; + +template< + template class Multiply, + template class Equality, + typename id, + typename sub_group_elements, + typename elements, + typename generators, + int sub_group_size, + int rep_pos +> +struct dimino_add_all_coset_spaces +{ + typedef elements type; + constexpr static int global_flags = 0; +}; + +/** \internal + * + * \class dimino_add_generator + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Enlarge the group by adding a new generator. + * + * It accepts a boolean parameter that determines if the generator is redundant, + * i.e. was already seen in the group. In that case, it reduces to a no-op. + * + * \sa enumerate_group_elements, dimino_add_all_coset_spaces + */ +template< + template class Multiply, + template class Equality, + typename id, + typename elements, + typename generators_done, + typename current_generator, + bool redundant // = false +> +struct dimino_add_generator +{ + /* this template is only called if the generator is not redundant + * => all elements of the group multiplied with the new generator + * are going to be new elements of the most trivial coset space + */ + typedef typename apply_op_from_right::type multiplied_elements; + typedef typename concat::type new_elements; + + constexpr static int rep_pos = elements::count; + + typedef dimino_add_all_coset_spaces< + Multiply, + Equality, + id, + elements, // elements of previous subgroup + new_elements, + typename concat>::type, + elements::count, // size of previous subgroup + rep_pos, + false // don't stop (because rep_pos >= new_elements::count is always false at this point) + > _helper; + typedef typename _helper::type type; + constexpr static int global_flags = _helper::global_flags; +}; + +template< + template class Multiply, + template class Equality, + typename id, + typename elements, + typename generators_done, + typename current_generator +> +struct dimino_add_generator +{ + // redundant case + typedef elements type; + constexpr static int global_flags = 0; +}; + +/** \internal + * + * \class dimino_add_remaining_generators + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Recursive template that adds all remaining generators to a group + * + * Loop through the list of generators that remain and successively + * add them to the group. + * + * \sa enumerate_group_elements, dimino_add_generator + */ +template< + template class Multiply, + template class Equality, + typename id, + typename generators_done, + typename remaining_generators, + typename elements +> +struct dimino_add_remaining_generators +{ + typedef typename get<0, remaining_generators>::type first_generator; + typedef typename skip<1, remaining_generators>::type next_generators; + + typedef contained_in_list_gf _cil; + + typedef dimino_add_generator< + Multiply, + Equality, + id, + elements, + generators_done, + first_generator, + _cil::value + > _helper; + + typedef typename _helper::type new_elements; + + typedef dimino_add_remaining_generators< + Multiply, + Equality, + id, + typename concat>::type, + next_generators, + new_elements + > _next_iter; + + typedef typename _next_iter::type type; + constexpr static int global_flags = + _cil::global_flags | + _helper::global_flags | + _next_iter::global_flags; +}; + +template< + template class Multiply, + template class Equality, + typename id, + typename generators_done, + typename elements +> +struct dimino_add_remaining_generators, elements> +{ + typedef elements type; + constexpr static int global_flags = 0; +}; + +/** \internal + * + * \class enumerate_group_elements_noid + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Helper template that implements group element enumeration + * + * This is a helper template that implements the actual enumeration + * of group elements. This has been split so that the list of + * generators can be cleansed of the identity element before + * performing the actual operation. + * + * \sa enumerate_group_elements + */ +template< + template class Multiply, + template class Equality, + typename id, + typename generators, + int initial_global_flags = 0 +> +struct enumerate_group_elements_noid +{ + typedef dimino_first_step_elements first_step; + typedef typename first_step::type first_step_elements; + + typedef dimino_add_remaining_generators< + Multiply, + Equality, + id, + typename first_step::generators_done, + typename first_step::next_generators, // remaining_generators + typename first_step::type // first_step elements + > _helper; + + typedef typename _helper::type type; + constexpr static int global_flags = + initial_global_flags | + first_step::global_flags | + _helper::global_flags; +}; + +// in case when no generators are specified +template< + template class Multiply, + template class Equality, + typename id, + int initial_global_flags +> +struct enumerate_group_elements_noid, initial_global_flags> +{ + typedef type_list type; + constexpr static int global_flags = initial_global_flags; +}; + +/** \internal + * + * \class enumerate_group_elements + * \ingroup CXX11_TensorSymmetry_Module + * + * \brief Enumerate all elements in a finite group + * + * This template enumerates all elements in a finite group. It accepts + * the following template parameters: + * + * \tparam Multiply The multiplication operation that multiplies two group elements + * with each other. + * \tparam Equality The equality check operation that checks if two group elements + * are equal to another. + * \tparam id The identity element + * \tparam Generators_ A list of (possibly redundant) generators of the group + */ +template< + template class Multiply, + template class Equality, + typename id, + typename Generators_ +> +struct enumerate_group_elements + : public enumerate_group_elements_noid< + Multiply, + Equality, + id, + typename strip_identities::type, + strip_identities::global_flags + > +{ +}; + +} // end namespace group_theory + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CXX11_TENSORSYMMETRY_TEMPLATEGROUPTHEORY_H + +/* + * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; + */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Meta.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Meta.h new file mode 100644 index 0000000000000000000000000000000000000000..5eb646af6d9b2f7f673e4e4c50fc00b5bc718dd2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Meta.h @@ -0,0 +1,18 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11META_H +#define EIGEN_CXX11META_H + +#include +#include "../../../../../Eigen/src/Core/util/EmulateArray.h" + +#include "CXX11Workarounds.h" + +#endif // EIGEN_CXX11META_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Workarounds.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Workarounds.h new file mode 100644 index 0000000000000000000000000000000000000000..386e390dca56a30f2579e5ab108db02c39a122cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/CXX11/src/util/CXX11Workarounds.h @@ -0,0 +1,76 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Christian Seiler +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CXX11WORKAROUNDS_H +#define EIGEN_CXX11WORKAROUNDS_H + +/* COMPATIBILITY CHECKS + * (so users of compilers that are too old get some realistic error messages) + */ +#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER < 1310) +#error Intel Compiler only supports required C++ features since version 13.1. +// note that most stuff in principle works with 13.0 but when combining +// some features, at some point 13.0 will just fail with an internal assertion +#elif defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6)) +// G++ < 4.6 by default will continue processing the source files - even if we use #error to make +// it error out. For this reason, we use the pragma to make sure G++ aborts at the first error +// it sees. Unfortunately, that is still not our #error directive, but at least the output is +// short enough the user has a chance to see that the compiler version is not sufficient for +// the funky template mojo we use. +#pragma GCC diagnostic error "-Wfatal-errors" +#error GNU C++ Compiler (g++) only supports required C++ features since version 4.6. +#endif + +namespace Eigen { + +namespace internal { + +/* std::get is only constexpr in C++14, not yet in C++11 + */ + + +template constexpr inline T& array_get(std::vector& a) { return a[I_]; } +template constexpr inline T&& array_get(std::vector&& a) { return a[I_]; } +template constexpr inline T const& array_get(std::vector const& a) { return a[I_]; } + +/* Suppose you have a template of the form + * template struct X; + * And you want to specialize it in such a way: + * template struct X> { ::: }; + * template<> struct X> { ::: }; + * This will work in Intel's compiler 13.0, but only to some extent in g++ 4.6, since + * g++ can only match templates called with parameter packs if the number of template + * arguments is not a fixed size (so inside the first specialization, referencing + * X> will fail in g++). On the other hand, g++ will accept the following: + * template struct X> { ::: }: + * as an additional (!) specialization, which will then only match the empty case. + * But Intel's compiler 13.0 won't accept that, it will only accept the empty syntax, + * so we have to create a workaround for this. + */ +#if defined(__GNUC__) && !defined(__INTEL_COMPILER) +#define EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n) mt... n +#define EIGEN_TPL_PP_SPEC_HACK_DEFC(mt, n) , EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n) +#define EIGEN_TPL_PP_SPEC_HACK_USE(n) n... +#define EIGEN_TPL_PP_SPEC_HACK_USEC(n) , n... +#else +#define EIGEN_TPL_PP_SPEC_HACK_DEF(mt, n) +#define EIGEN_TPL_PP_SPEC_HACK_DEFC(mt, n) +#define EIGEN_TPL_PP_SPEC_HACK_USE(n) +#define EIGEN_TPL_PP_SPEC_HACK_USEC(n) +#endif + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_CXX11WORKAROUNDS_H + +/* + * kate: space-indent on; indent-width 2; mixedindent off; indent-mode cstyle; + */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/EulerAngles b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/EulerAngles new file mode 100644 index 0000000000000000000000000000000000000000..3e4c74bf290cea63ce8797d5cf87d6a44f16b3e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/EulerAngles @@ -0,0 +1,45 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Tal Hadad +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EULERANGLES_MODULE_H +#define EIGEN_EULERANGLES_MODULE_H + + +#include "../../Eigen/Core" +#include "../../Eigen/Geometry" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +namespace Eigen { + +/** + * \defgroup EulerAngles_Module EulerAngles module + * \brief This module provides generic euler angles rotation. + * + * Euler angles are a way to represent 3D rotation. + * + * In order to use this module in your code, include this header: + * \code + * #include + * \endcode + * + * See \ref EulerAngles for more information. + * + */ + +} + +// IWYU pragma: begin_exports +#include "src/EulerAngles/EulerSystem.h" +#include "src/EulerAngles/EulerAngles.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_EULERANGLES_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/FFT b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/FFT new file mode 100644 index 0000000000000000000000000000000000000000..0b4ce1a866d1994c6775a31c1046a9a9d4dd4669 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/FFT @@ -0,0 +1,439 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Mark Borgerding mark a borgerding net +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_FFT_MODULE_H +#define EIGEN_FFT_MODULE_H + +#include +#include +#include +#include "../../Eigen/Core" + + +/** + * \defgroup FFT_Module Fast Fourier Transform module + * + * \code + * #include + * \endcode + * + * This module provides Fast Fourier transformation, with a configurable backend + * implementation. + * + * The default implementation is based on kissfft. It is a small, free, and + * reasonably efficient default. + * + * There are currently four implementation backend: + * + * - kissfft(https://github.com/mborgerding/kissfft) : Simple and not so fast, BSD-3-Clause. + * It is a mixed-radix Fast Fourier Transform based up on the principle, "Keep It Simple, Stupid." + * Notice that:kissfft fails to handle "atypically-sized" inputs(i.e., sizes with large factors),a workaround is using fftw or pocketfft. + * - fftw (http://www.fftw.org) : faster, GPL -- incompatible with Eigen in LGPL form, bigger code size. + * - MKL (https://www.intel.com/content/www/us/en/developer/tools/oneapi/onemkl-download.html) : fastest, free -- may be incompatible with Eigen in GPL form. + * - pocketfft (https://gitlab.mpcdf.mpg.de/mtr/pocketfft) : faster than kissfft, BSD 3-clause. + * It is a heavily modified implementation of FFTPack, with the following advantages: + * 1.strictly C++11 compliant + * 2.more accurate twiddle factor computation + * 3.very fast plan generation + * 4.worst case complexity for transform sizes with large prime factors is N*log(N), because Bluestein's algorithm is used for these cases + * + * \section FFTDesign Design + * + * The following design decisions were made concerning scaling and + * half-spectrum for real FFT. + * + * The intent is to facilitate generic programming and ease migrating code + * from Matlab/octave. + * We think the default behavior of Eigen/FFT should favor correctness and + * generality over speed. Of course, the caller should be able to "opt-out" from this + * behavior and get the speed increase if they want it. + * + * 1) %Scaling: + * Other libraries (FFTW,IMKL,KISSFFT) do not perform scaling, so there + * is a constant gain incurred after the forward&inverse transforms , so + * IFFT(FFT(x)) = Kx; this is done to avoid a vector-by-value multiply. + * The downside is that algorithms that worked correctly in Matlab/octave + * don't behave the same way once implemented in C++. + * + * How Eigen/FFT differs: invertible scaling is performed so IFFT( FFT(x) ) = x. + * + * 2) Real FFT half-spectrum + * Other libraries use only half the frequency spectrum (plus one extra + * sample for the Nyquist bin) for a real FFT, the other half is the + * conjugate-symmetric of the first half. This saves them a copy and some + * memory. The downside is the caller needs to have special logic for the + * number of bins in complex vs real. + * + * How Eigen/FFT differs: The full spectrum is returned from the forward + * transform. This facilitates generic template programming by obviating + * separate specializations for real vs complex. On the inverse + * transform, only half the spectrum is actually used if the output type is real. + */ + + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports + +#ifdef EIGEN_FFTW_DEFAULT +// FFTW: faster, GPL -- incompatible with Eigen in LGPL form, bigger code size +# include +# include "src/FFT/ei_fftw_impl.h" + namespace Eigen { + //template typedef struct internal::fftw_impl default_fft_impl; this does not work + template struct default_fft_impl : public internal::fftw_impl {}; + } +#elif defined EIGEN_MKL_DEFAULT +// intel Math Kernel Library: fastest, free -- may be incompatible with Eigen in GPL form +# include "src/FFT/ei_imklfft_impl.h" + namespace Eigen { + template struct default_fft_impl : public internal::imklfft::imklfft_impl {}; + } +#elif defined EIGEN_POCKETFFT_DEFAULT +// internal::pocketfft_impl: a heavily modified implementation of FFTPack, with many advantages. +# include +# include"src/FFT/ei_pocketfft_impl.h" + namespace Eigen { + template + struct default_fft_impl : public internal::pocketfft_impl {}; + } +#else +// internal::kissfft_impl: small, free, reasonably efficient default, derived from kissfft +# include "src/FFT/ei_kissfft_impl.h" + namespace Eigen { + template + struct default_fft_impl : public internal::kissfft_impl {}; + } +#endif + +// IWYU pragma: end_exports + +namespace Eigen { + + +// +template struct fft_fwd_proxy; +template struct fft_inv_proxy; + +namespace internal { +template +struct traits< fft_fwd_proxy > +{ + typedef typename T_SrcMat::PlainObject ReturnType; +}; +template +struct traits< fft_inv_proxy > +{ + typedef typename T_SrcMat::PlainObject ReturnType; +}; +} + +template +struct fft_fwd_proxy + : public ReturnByValue > +{ + typedef DenseIndex Index; + + fft_fwd_proxy(const T_SrcMat& src,T_FftIfc & fft, Index nfft) : m_src(src),m_ifc(fft), m_nfft(nfft) {} + + template void evalTo(T_DestMat& dst) const; + + Index rows() const { return m_src.rows(); } + Index cols() const { return m_src.cols(); } +protected: + const T_SrcMat & m_src; + T_FftIfc & m_ifc; + Index m_nfft; +}; + +template +struct fft_inv_proxy + : public ReturnByValue > +{ + typedef DenseIndex Index; + + fft_inv_proxy(const T_SrcMat& src,T_FftIfc & fft, Index nfft) : m_src(src),m_ifc(fft), m_nfft(nfft) {} + + template void evalTo(T_DestMat& dst) const; + + Index rows() const { return m_src.rows(); } + Index cols() const { return m_src.cols(); } +protected: + const T_SrcMat & m_src; + T_FftIfc & m_ifc; + Index m_nfft; +}; + + +template > +class FFT +{ + public: + typedef T_Impl impl_type; + typedef DenseIndex Index; + typedef typename impl_type::Scalar Scalar; + typedef typename impl_type::Complex Complex; + + using Flag = int; + static constexpr Flag Default = 0; + static constexpr Flag Unscaled = 1; + static constexpr Flag HalfSpectrum = 2; + static constexpr Flag Speedy = 32767; + + FFT( const impl_type & impl=impl_type() , Flag flags=Default ) :m_impl(impl),m_flag(flags) + { + eigen_assert((flags == Default || flags == Unscaled || flags == HalfSpectrum || flags == Speedy) && "invalid flags argument"); + } + + inline + bool HasFlag(Flag f) const { return (m_flag & (int)f) == f;} + + inline + void SetFlag(Flag f) { m_flag |= (int)f;} + + inline + void ClearFlag(Flag f) { m_flag &= (~(int)f);} + + inline + void fwd( Complex * dst, const Scalar * src, Index nfft) + { + m_impl.fwd(dst,src,static_cast(nfft)); + if ( HasFlag(HalfSpectrum) == false) + ReflectSpectrum(dst,nfft); + } + + inline + void fwd( Complex * dst, const Complex * src, Index nfft) + { + m_impl.fwd(dst,src,static_cast(nfft)); + } + +#if defined EIGEN_FFTW_DEFAULT || defined EIGEN_POCKETFFT_DEFAULT || defined EIGEN_MKL_DEFAULT + inline + void fwd2(Complex * dst, const Complex * src, int n0,int n1) + { + m_impl.fwd2(dst,src,n0,n1); + } +#endif + + template + inline + void fwd( std::vector & dst, const std::vector & src) + { + if ( NumTraits::IsComplex == 0 && HasFlag(HalfSpectrum) ) + dst.resize( (src.size()>>1)+1); // half the bins + Nyquist bin + else + dst.resize(src.size()); + fwd(&dst[0],&src[0],src.size()); + } + + template + inline + void fwd( MatrixBase & dst, const MatrixBase & src, Index nfft=-1) + { + typedef typename ComplexDerived::Scalar dst_type; + typedef typename InputDerived::Scalar src_type; + EIGEN_STATIC_ASSERT_VECTOR_ONLY(InputDerived) + EIGEN_STATIC_ASSERT_VECTOR_ONLY(ComplexDerived) + EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ComplexDerived,InputDerived) // size at compile-time + EIGEN_STATIC_ASSERT((internal::is_same::value), + YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) + EIGEN_STATIC_ASSERT(int(InputDerived::Flags)&int(ComplexDerived::Flags)&DirectAccessBit, + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_WITH_DIRECT_MEMORY_ACCESS_SUCH_AS_MAP_OR_PLAIN_MATRICES) + + if (nfft<1) + nfft = src.size(); + + if ( NumTraits< src_type >::IsComplex == 0 && HasFlag(HalfSpectrum) ) + dst.derived().resize( (nfft>>1)+1); + else + dst.derived().resize(nfft); + + if ( src.innerStride() != 1 || src.size() < nfft ) { + Matrix tmp; + if (src.size() + inline + fft_fwd_proxy< MatrixBase, FFT > + fwd( const MatrixBase & src, Index nfft=-1) + { + return fft_fwd_proxy< MatrixBase ,FFT >( src, *this,nfft ); + } + + template + inline + fft_inv_proxy< MatrixBase, FFT > + inv( const MatrixBase & src, Index nfft=-1) + { + return fft_inv_proxy< MatrixBase ,FFT >( src, *this,nfft ); + } + + inline + void inv( Complex * dst, const Complex * src, Index nfft) + { + m_impl.inv( dst,src,static_cast(nfft) ); + if ( HasFlag( Unscaled ) == false) + scale(dst,Scalar(1./nfft),nfft); // scale the time series + } + + inline + void inv( Scalar * dst, const Complex * src, Index nfft) + { + m_impl.inv( dst,src,static_cast(nfft) ); + if ( HasFlag( Unscaled ) == false) + scale(dst,Scalar(1./nfft),nfft); // scale the time series + } + + template + inline + void inv( MatrixBase & dst, const MatrixBase & src, Index nfft=-1) + { + typedef typename ComplexDerived::Scalar src_type; + typedef typename ComplexDerived::RealScalar real_type; + typedef typename OutputDerived::Scalar dst_type; + const bool realfft= (NumTraits::IsComplex == 0); + EIGEN_STATIC_ASSERT_VECTOR_ONLY(OutputDerived) + EIGEN_STATIC_ASSERT_VECTOR_ONLY(ComplexDerived) + EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(ComplexDerived,OutputDerived) // size at compile-time + EIGEN_STATIC_ASSERT((internal::is_same::value), + YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) + EIGEN_STATIC_ASSERT(int(OutputDerived::Flags)&int(ComplexDerived::Flags)&DirectAccessBit, + THIS_METHOD_IS_ONLY_FOR_EXPRESSIONS_WITH_DIRECT_MEMORY_ACCESS_SUCH_AS_MAP_OR_PLAIN_MATRICES) + + if (nfft<1) { //automatic FFT size determination + if ( realfft && HasFlag(HalfSpectrum) ) + nfft = 2*(src.size()-1); //assume even fft size + else + nfft = src.size(); + } + dst.derived().resize( nfft ); + + // check for nfft that does not fit the input data size + Index resize_input= ( realfft && HasFlag(HalfSpectrum) ) + ? ( (nfft/2+1) - src.size() ) + : ( nfft - src.size() ); + + if ( src.innerStride() != 1 || resize_input ) { + // if the vector is strided, then we need to copy it to a packed temporary + Matrix tmp; + if ( resize_input ) { + size_t ncopy = (std::min)(src.size(),src.size() + resize_input); + tmp.setZero(src.size() + resize_input); + if ( realfft && HasFlag(HalfSpectrum) ) { + // pad at the Nyquist bin + tmp.head(ncopy) = src.head(ncopy); + tmp(ncopy-1) = real(tmp(ncopy-1)); // enforce real-only Nyquist bin + }else{ + size_t nhead,ntail; + nhead = 1+ncopy/2-1; // range [0:pi) + ntail = ncopy/2-1; // range (-pi:0) + tmp.head(nhead) = src.head(nhead); + tmp.tail(ntail) = src.tail(ntail); + if (resize_input<0) { //shrinking -- create the Nyquist bin as the average of the two bins that fold into it + tmp(nhead) = ( src(nfft/2) + src( src.size() - nfft/2 ) )*real_type(.5); + }else{ // expanding -- split the old Nyquist bin into two halves + tmp(nhead) = src(nhead) * real_type(.5); + tmp(tmp.size()-nhead) = tmp(nhead); + } + } + }else{ + tmp = src; + } + inv( &dst[0],&tmp[0], nfft); + }else{ + inv( &dst[0],&src[0], nfft); + } + } + + template + inline + void inv( std::vector & dst, const std::vector & src,Index nfft=-1) + { + if (nfft<1) + nfft = ( NumTraits::IsComplex == 0 && HasFlag(HalfSpectrum) ) ? 2*(src.size()-1) : src.size(); + dst.resize( nfft ); + inv( &dst[0],&src[0],nfft); + } + + +#if defined EIGEN_FFTW_DEFAULT || defined EIGEN_POCKETFFT_DEFAULT || defined EIGEN_MKL_DEFAULT + inline + void inv2(Complex * dst, const Complex * src, int n0,int n1) + { + m_impl.inv2(dst,src,n0,n1); + if ( HasFlag( Unscaled ) == false) + scale(dst,1./(n0*n1),n0*n1); + } +#endif + + + inline + impl_type & impl() {return m_impl;} + private: + + template + inline + void scale(T_Data * x,Scalar s,Index nx) + { +#if 1 + for (int k=0;k::Map(x,nx) *= s; + else + Matrix::MapAligned(x,nx) *= s; + //Matrix::Map(x,nx) * s; +#endif + } + + inline + void ReflectSpectrum(Complex * freq, Index nfft) + { + // create the implicit right-half spectrum (conjugate-mirror of the left-half) + Index nhbins=(nfft>>1)+1; + for (Index k=nhbins;k < nfft; ++k ) + freq[k] = conj(freq[nfft-k]); + } + + impl_type m_impl; + int m_flag; +}; + +template +template inline +void fft_fwd_proxy::evalTo(T_DestMat& dst) const +{ + m_ifc.fwd( dst, m_src, m_nfft); +} + +template +template inline +void fft_inv_proxy::evalTo(T_DestMat& dst) const +{ + m_ifc.inv( dst, m_src, m_nfft); +} + +} + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/IterativeSolvers b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/IterativeSolvers new file mode 100644 index 0000000000000000000000000000000000000000..5800e097af217a5efac8568824b74793558345cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/IterativeSolvers @@ -0,0 +1,94 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ITERATIVE_SOLVERS_MODULE_H +#define EIGEN_ITERATIVE_SOLVERS_MODULE_H + +#include "../../Eigen/Sparse" +#include "../../Eigen/Jacobi" +#include "../../Eigen/Householder" + + +/** + * \defgroup IterativeLinearSolvers_Module Iterative Solvers module + * This module aims to provide various iterative linear and non linear solver algorithms. + * It currently provides: + * - a Householder GMRES implementation + * - an IDR(s) implementation + * - a BiCGSTAB(L) implementation + * - a DGMRES implementation + * - a MINRES implementation + * - a IDRSTABL implementation + * + * Choosing the best solver for solving \c A \c x = \c b depends a lot on the preconditioner chosen as well as the properties of \c A. The following flowchart might help you. + * \dot width=50% + * digraph g { +* node [ fontname=Arial, fontsize=11]; +* edge [ fontname=Helvetica, fontsize=10 ]; +* A1[label="hermitian",shape="box"]; +* A2[label="positive definite",shape="box"]; +* CG[shape="plaintext"]; +* A3[label="ill conditioned",shape="box"]; +* A4[label="good preconditioner",shape="box"]; +* A5[label="flexible preconditioner",shape="box"]; +* A6[label="strongly indefinite",shape="box"]; +* A8[label="large imaginary eigenvalue",shape="box"]; +* A7[label="large imaginary eigenvalue",shape="box"]; +* +* SYMMLQ[shape="plaintext"]; +* MINRES[shape="plaintext"]; +* GCR[shape="plaintext"]; +* GMRES[shape="plaintext"]; +* IDRSTABL[shape="plaintext"]; +* IDRS[shape="plaintext"]; +* BICGSTABL[shape="plaintext"]; +* BICGSTAB[shape="plaintext"]; +* +* A1 -> A2 [label="yes"]; +* A2 -> CG [label="yes"]; +* A2 -> A3 [label="no"]; +* A3 -> SYMMLQ [label="yes"]; +* A3 -> MINRES [label="no"]; +* +* A1 -> A4 [label="no"]; +* A4 -> A5 [label="yes"]; +* A5 -> GCR [label="yes"]; +* A5 -> GMRES [label="no"]; +* +* A4 -> A6 [label="no"]; +* A6 -> A8 [label="yes"]; +* A6 -> A7 [label="no"]; +* A7 -> BICGSTABL [label="yes"]; +* A7 -> BICGSTAB [label="no"]; +* A8 -> IDRSTABL [label="yes"]; +* A8 -> IDRS [label="no"]; +* } + * \enddot + * \code + * #include + * \endcode + */ + + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "src/IterativeSolvers/IncompleteLU.h" +#include "src/IterativeSolvers/GMRES.h" +#include "src/IterativeSolvers/DGMRES.h" +#include "src/IterativeSolvers/MINRES.h" +#include "src/IterativeSolvers/IDRS.h" +#include "src/IterativeSolvers/BiCGSTABL.h" +#include "src/IterativeSolvers/IDRSTABL.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + + +#endif // EIGEN_ITERATIVE_SOLVERS_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/KroneckerProduct b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/KroneckerProduct new file mode 100644 index 0000000000000000000000000000000000000000..0dcb995dea09ea9e810cdc5e4e51ff6855fd6e6b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/KroneckerProduct @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_KRONECKER_PRODUCT_MODULE_H +#define EIGEN_KRONECKER_PRODUCT_MODULE_H + +#include "../../Eigen/Core" +#include "../../Eigen/SparseCore" + +namespace Eigen { + +/** + * \defgroup KroneckerProduct_Module KroneckerProduct module + * + * This module contains an experimental Kronecker product implementation. + * + * \code + * #include + * \endcode + */ + +} // namespace Eigen + +// IWYU pragma: begin_exports +#include "src/KroneckerProduct/KroneckerTensorProduct.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_KRONECKER_PRODUCT_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/LevenbergMarquardt b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/LevenbergMarquardt new file mode 100644 index 0000000000000000000000000000000000000000..96d1e67ad703046fec6e038d124d8ff28104af5c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/LevenbergMarquardt @@ -0,0 +1,49 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LEVENBERGMARQUARDT_MODULE_H +#define EIGEN_LEVENBERGMARQUARDT_MODULE_H + +// #include + +#include "../../Eigen/Core" +#include "../../Eigen/Jacobi" +#include "../../Eigen/QR" +#include "NumericalDiff" + +#include "../../Eigen/SparseQR" + +/** + * \defgroup LevenbergMarquardt_Module Levenberg-Marquardt module + * + * \code + * #include + * \endcode + * + * + */ + +#include "../../Eigen/SparseCore" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#ifndef EIGEN_PARSED_BY_DOXYGEN +#include "src/LevenbergMarquardt/LMqrsolv.h" +#include "src/LevenbergMarquardt/LMcovar.h" +#include "src/LevenbergMarquardt/LMpar.h" +#endif + +#include "src/LevenbergMarquardt/LevenbergMarquardt.h" +#include "src/LevenbergMarquardt/LMonestep.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_LEVENBERGMARQUARDT_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MPRealSupport b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MPRealSupport new file mode 100644 index 0000000000000000000000000000000000000000..c4ea4ec5f6d80f7c97670371e3b3cb64fee2106b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MPRealSupport @@ -0,0 +1,213 @@ +// This file is part of a joint effort between Eigen, a lightweight C++ template library +// for linear algebra, and MPFR C++, a C++ interface to MPFR library (http://www.holoborodko.com/pavel/) +// +// Copyright (C) 2010-2012 Pavel Holoborodko +// Copyright (C) 2010 Konstantin Holoborodko +// Copyright (C) 2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MPREALSUPPORT_MODULE_H +#define EIGEN_MPREALSUPPORT_MODULE_H + +#include "../../Eigen/Core" +#include + +namespace Eigen { + +/** + * \defgroup MPRealSupport_Module MPFRC++ Support module + * \code + * #include + * \endcode + * + * This module provides support for multi precision floating point numbers + * via the MPFR C++ + * library which itself is built upon MPFR/GMP. + * + * \warning MPFR C++ is licensed under the GPL. + * + * You can find a copy of MPFR C++ that is known to be compatible in the unsupported/test/mpreal folder. + * + * Here is an example: + * +\code +#include +#include +#include +using namespace mpfr; +using namespace Eigen; +int main() +{ + // set precision to 256 bits (double has only 53 bits) + mpreal::set_default_prec(256); + // Declare matrix and vector types with multi-precision scalar type + typedef Matrix MatrixXmp; + typedef Matrix VectorXmp; + + MatrixXmp A = MatrixXmp::Random(100,100); + VectorXmp b = VectorXmp::Random(100); + + // Solve Ax=b using LU + VectorXmp x = A.lu().solve(b); + std::cout << "relative error: " << (A*x - b).norm() / b.norm() << std::endl; + return 0; +} +\endcode + * + */ + + template<> struct NumTraits + : GenericNumTraits + { + enum { + IsInteger = 0, + IsSigned = 1, + IsComplex = 0, + RequireInitialization = 1, + ReadCost = HugeCost, + AddCost = HugeCost, + MulCost = HugeCost + }; + + typedef mpfr::mpreal Real; + typedef mpfr::mpreal NonInteger; + + static inline Real highest (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::maxval(Precision); } + static inline Real lowest (long Precision = mpfr::mpreal::get_default_prec()) { return -mpfr::maxval(Precision); } + + // Constants + static inline Real Pi (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::const_pi(Precision); } + static inline Real Euler (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::const_euler(Precision); } + static inline Real Log2 (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::const_log2(Precision); } + static inline Real Catalan (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::const_catalan(Precision); } + + static inline Real epsilon (long Precision = mpfr::mpreal::get_default_prec()) { return mpfr::machine_epsilon(Precision); } + static inline Real epsilon (const Real& x) { return mpfr::machine_epsilon(x); } + +#ifdef MPREAL_HAVE_DYNAMIC_STD_NUMERIC_LIMITS + static inline int digits10 (long Precision = mpfr::mpreal::get_default_prec()) { return std::numeric_limits::digits10(Precision); } + static inline int digits10 (const Real& x) { return std::numeric_limits::digits10(x); } + + static inline int digits () { return std::numeric_limits::digits(); } + static inline int digits (const Real& x) { return std::numeric_limits::digits(x); } +#endif + + static inline Real dummy_precision() + { + mpfr_prec_t weak_prec = ((mpfr::mpreal::get_default_prec()-1) * 90) / 100; + return mpfr::machine_epsilon(weak_prec); + } + }; + + namespace internal { + + template<> inline mpfr::mpreal random() + { + return mpfr::random(); + } + + template<> inline mpfr::mpreal random(const mpfr::mpreal& a, const mpfr::mpreal& b) + { + return a + (b-a) * random(); + } + + inline bool isMuchSmallerThan(const mpfr::mpreal& a, const mpfr::mpreal& b, const mpfr::mpreal& eps) + { + return mpfr::abs(a) <= mpfr::abs(b) * eps; + } + + inline bool isApprox(const mpfr::mpreal& a, const mpfr::mpreal& b, const mpfr::mpreal& eps) + { + return mpfr::isEqualFuzzy(a,b,eps); + } + + inline bool isApproxOrLessThan(const mpfr::mpreal& a, const mpfr::mpreal& b, const mpfr::mpreal& eps) + { + return a <= b || mpfr::isEqualFuzzy(a,b,eps); + } + + template<> inline long double cast(const mpfr::mpreal& x) + { return x.toLDouble(); } + + template<> inline double cast(const mpfr::mpreal& x) + { return x.toDouble(); } + + template<> inline long cast(const mpfr::mpreal& x) + { return x.toLong(); } + + template<> inline int cast(const mpfr::mpreal& x) + { return int(x.toLong()); } + + // Specialize GEBP kernel and traits for mpreal (no need for peeling, nor complicated stuff) + // This also permits to directly call mpfr's routines and avoid many temporaries produced by mpreal + template<> + class gebp_traits + { + public: + typedef mpfr::mpreal ResScalar; + enum { + Vectorizable = false, + LhsPacketSize = 1, + RhsPacketSize = 1, + ResPacketSize = 1, + NumberOfRegisters = 1, + nr = 1, + mr = 1, + LhsProgress = 1, + RhsProgress = 1 + }; + typedef ResScalar LhsPacket; + typedef ResScalar RhsPacket; + typedef ResScalar ResPacket; + typedef LhsPacket LhsPacket4Packing; + + }; + + + + template + struct gebp_kernel + { + typedef mpfr::mpreal mpreal; + + EIGEN_DONT_INLINE + void operator()(const DataMapper& res, const mpreal* blockA, const mpreal* blockB, + Index rows, Index depth, Index cols, const mpreal& alpha, + Index strideA=-1, Index strideB=-1, Index offsetA=0, Index offsetB=0) + { + if(rows==0 || cols==0 || depth==0) + return; + + mpreal acc1(0,mpfr_get_prec(blockA[0].mpfr_srcptr())), + tmp (0,mpfr_get_prec(blockA[0].mpfr_srcptr())); + + if(strideA==-1) strideA = depth; + if(strideB==-1) strideB = depth; + + for(Index i=0; i +// Copyright (C) 2012 Chen-Pang He +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_FUNCTIONS_MODULE_H +#define EIGEN_MATRIX_FUNCTIONS_MODULE_H + +#include +#include + +#include "../../Eigen/Core" +#include "../../Eigen/LU" +#include "../../Eigen/Eigenvalues" + +/** + * \defgroup MatrixFunctions_Module Matrix functions module + * \brief This module aims to provide various methods for the computation of + * matrix functions. + * + * To use this module, add + * \code + * #include + * \endcode + * at the start of your source file. + * + * This module defines the following MatrixBase methods. + * - \ref matrixbase_cos "MatrixBase::cos()", for computing the matrix cosine + * - \ref matrixbase_cosh "MatrixBase::cosh()", for computing the matrix hyperbolic cosine + * - \ref matrixbase_exp "MatrixBase::exp()", for computing the matrix exponential + * - \ref matrixbase_log "MatrixBase::log()", for computing the matrix logarithm + * - \ref matrixbase_pow "MatrixBase::pow()", for computing the matrix power + * - \ref matrixbase_matrixfunction "MatrixBase::matrixFunction()", for computing general matrix functions + * - \ref matrixbase_sin "MatrixBase::sin()", for computing the matrix sine + * - \ref matrixbase_sinh "MatrixBase::sinh()", for computing the matrix hyperbolic sine + * - \ref matrixbase_sqrt "MatrixBase::sqrt()", for computing the matrix square root + * + * These methods are the main entry points to this module. + * + * %Matrix functions are defined as follows. Suppose that \f$ f \f$ + * is an entire function (that is, a function on the complex plane + * that is everywhere complex differentiable). Then its Taylor + * series + * \f[ f(0) + f'(0) x + \frac{f''(0)}{2} x^2 + \frac{f'''(0)}{3!} x^3 + \cdots \f] + * converges to \f$ f(x) \f$. In this case, we can define the matrix + * function by the same series: + * \f[ f(M) = f(0) + f'(0) M + \frac{f''(0)}{2} M^2 + \frac{f'''(0)}{3!} M^3 + \cdots \f] + * + */ + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "src/MatrixFunctions/MatrixExponential.h" +#include "src/MatrixFunctions/MatrixFunction.h" +#include "src/MatrixFunctions/MatrixSquareRoot.h" +#include "src/MatrixFunctions/MatrixLogarithm.h" +#include "src/MatrixFunctions/MatrixPower.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + + +/** +\page matrixbaseextra_page +\ingroup MatrixFunctions_Module + +\section matrixbaseextra MatrixBase methods defined in the MatrixFunctions module + +The remainder of the page documents the following MatrixBase methods +which are defined in the MatrixFunctions module. + + + +\subsection matrixbase_cos MatrixBase::cos() + +Compute the matrix cosine. + +\code +const MatrixFunctionReturnValue MatrixBase::cos() const +\endcode + +\param[in] M a square matrix. +\returns expression representing \f$ \cos(M) \f$. + +This function computes the matrix cosine. Use ArrayBase::cos() for computing the entry-wise cosine. + +The implementation calls \ref matrixbase_matrixfunction "matrixFunction()" with StdStemFunctions::cos(). + +\sa \ref matrixbase_sin "sin()" for an example. + + + +\subsection matrixbase_cosh MatrixBase::cosh() + +Compute the matrix hyberbolic cosine. + +\code +const MatrixFunctionReturnValue MatrixBase::cosh() const +\endcode + +\param[in] M a square matrix. +\returns expression representing \f$ \cosh(M) \f$ + +This function calls \ref matrixbase_matrixfunction "matrixFunction()" with StdStemFunctions::cosh(). + +\sa \ref matrixbase_sinh "sinh()" for an example. + + + +\subsection matrixbase_exp MatrixBase::exp() + +Compute the matrix exponential. + +\code +const MatrixExponentialReturnValue MatrixBase::exp() const +\endcode + +\param[in] M matrix whose exponential is to be computed. +\returns expression representing the matrix exponential of \p M. + +The matrix exponential of \f$ M \f$ is defined by +\f[ \exp(M) = \sum_{k=0}^\infty \frac{M^k}{k!}. \f] +The matrix exponential can be used to solve linear ordinary +differential equations: the solution of \f$ y' = My \f$ with the +initial condition \f$ y(0) = y_0 \f$ is given by +\f$ y(t) = \exp(M) y_0 \f$. + +The matrix exponential is different from applying the exp function to all the entries in the matrix. +Use ArrayBase::exp() if you want to do the latter. + +The cost of the computation is approximately \f$ 20 n^3 \f$ for +matrices of size \f$ n \f$. The number 20 depends weakly on the +norm of the matrix. + +The matrix exponential is computed using the scaling-and-squaring +method combined with Padé approximation. The matrix is first +rescaled, then the exponential of the reduced matrix is computed +approximant, and then the rescaling is undone by repeated +squaring. The degree of the Padé approximant is chosen such +that the approximation error is less than the round-off +error. However, errors may accumulate during the squaring phase. + +Details of the algorithm can be found in: Nicholas J. Higham, "The +scaling and squaring method for the matrix exponential revisited," +SIAM J. %Matrix Anal. Applic., 26:1179–1193, +2005. + +Example: The following program checks that +\f[ \exp \left[ \begin{array}{ccc} + 0 & \frac14\pi & 0 \\ + -\frac14\pi & 0 & 0 \\ + 0 & 0 & 0 + \end{array} \right] = \left[ \begin{array}{ccc} + \frac12\sqrt2 & -\frac12\sqrt2 & 0 \\ + \frac12\sqrt2 & \frac12\sqrt2 & 0 \\ + 0 & 0 & 1 + \end{array} \right]. \f] +This corresponds to a rotation of \f$ \frac14\pi \f$ radians around +the z-axis. + +\include MatrixExponential.cpp +Output: \verbinclude MatrixExponential.out + +\note \p M has to be a matrix of \c float, \c double, `long double` +\c complex, \c complex, or `complex` . + + +\subsection matrixbase_log MatrixBase::log() + +Compute the matrix logarithm. + +\code +const MatrixLogarithmReturnValue MatrixBase::log() const +\endcode + +\param[in] M invertible matrix whose logarithm is to be computed. +\returns expression representing the matrix logarithm root of \p M. + +The matrix logarithm of \f$ M \f$ is a matrix \f$ X \f$ such that +\f$ \exp(X) = M \f$ where exp denotes the matrix exponential. As for +the scalar logarithm, the equation \f$ \exp(X) = M \f$ may have +multiple solutions; this function returns a matrix whose eigenvalues +have imaginary part in the interval \f$ (-\pi,\pi] \f$. + +The matrix logarithm is different from applying the log function to all the entries in the matrix. +Use ArrayBase::log() if you want to do the latter. + +In the real case, the matrix \f$ M \f$ should be invertible and +it should have no eigenvalues which are real and negative (pairs of +complex conjugate eigenvalues are allowed). In the complex case, it +only needs to be invertible. + +This function computes the matrix logarithm using the Schur-Parlett +algorithm as implemented by MatrixBase::matrixFunction(). The +logarithm of an atomic block is computed by MatrixLogarithmAtomic, +which uses direct computation for 1-by-1 and 2-by-2 blocks and an +inverse scaling-and-squaring algorithm for bigger blocks, with the +square roots computed by MatrixBase::sqrt(). + +Details of the algorithm can be found in Section 11.6.2 of: +Nicholas J. Higham, +Functions of Matrices: Theory and Computation, +SIAM 2008. ISBN 978-0-898716-46-7. + +Example: The following program checks that +\f[ \log \left[ \begin{array}{ccc} + \frac12\sqrt2 & -\frac12\sqrt2 & 0 \\ + \frac12\sqrt2 & \frac12\sqrt2 & 0 \\ + 0 & 0 & 1 + \end{array} \right] = \left[ \begin{array}{ccc} + 0 & \frac14\pi & 0 \\ + -\frac14\pi & 0 & 0 \\ + 0 & 0 & 0 + \end{array} \right]. \f] +This corresponds to a rotation of \f$ \frac14\pi \f$ radians around +the z-axis. This is the inverse of the example used in the +documentation of \ref matrixbase_exp "exp()". + +\include MatrixLogarithm.cpp +Output: \verbinclude MatrixLogarithm.out + +\note \p M has to be a matrix of \c float, \c double, `long +double`, \c complex, \c complex, or `complex`. + +\sa MatrixBase::exp(), MatrixBase::matrixFunction(), + class MatrixLogarithmAtomic, MatrixBase::sqrt(). + + +\subsection matrixbase_pow MatrixBase::pow() + +Compute the matrix raised to arbitrary real power. + +\code +const MatrixPowerReturnValue MatrixBase::pow(RealScalar p) const +\endcode + +\param[in] M base of the matrix power, should be a square matrix. +\param[in] p exponent of the matrix power. + +The matrix power \f$ M^p \f$ is defined as \f$ \exp(p \log(M)) \f$, +where exp denotes the matrix exponential, and log denotes the matrix +logarithm. This is different from raising all the entries in the matrix +to the p-th power. Use ArrayBase::pow() if you want to do the latter. + +If \p p is complex, the scalar type of \p M should be the type of \p +p . \f$ M^p \f$ simply evaluates into \f$ \exp(p \log(M)) \f$. +Therefore, the matrix \f$ M \f$ should meet the conditions to be an +argument of matrix logarithm. + +If \p p is real, it is casted into the real scalar type of \p M. Then +this function computes the matrix power using the Schur-Padé +algorithm as implemented by class MatrixPower. The exponent is split +into integral part and fractional part, where the fractional part is +in the interval \f$ (-1, 1) \f$. The main diagonal and the first +super-diagonal is directly computed. + +If \p M is singular with a semisimple zero eigenvalue and \p p is +positive, the Schur factor \f$ T \f$ is reordered with Givens +rotations, i.e. + +\f[ T = \left[ \begin{array}{cc} + T_1 & T_2 \\ + 0 & 0 + \end{array} \right] \f] + +where \f$ T_1 \f$ is invertible. Then \f$ T^p \f$ is given by + +\f[ T^p = \left[ \begin{array}{cc} + T_1^p & T_1^{-1} T_1^p T_2 \\ + 0 & 0 + \end{array}. \right] \f] + +\warning Fractional power of a matrix with a non-semisimple zero +eigenvalue is not well-defined. We introduce an assertion failure +against inaccurate result, e.g. \code +#include +#include + +int main() +{ + Eigen::Matrix4d A; + A << 0, 0, 2, 3, + 0, 0, 4, 5, + 0, 0, 6, 7, + 0, 0, 8, 9; + std::cout << A.pow(0.37) << std::endl; + + // The 1 makes eigenvalue 0 non-semisimple. + A.coeffRef(0, 1) = 1; + + // This fails if EIGEN_NO_DEBUG is undefined. + std::cout << A.pow(0.37) << std::endl; + + return 0; +} +\endcode + +Details of the algorithm can be found in: Nicholas J. Higham and +Lijing Lin, "A Schur-Padé algorithm for fractional powers of a +matrix," SIAM J. %Matrix Anal. Applic., +32(3):1056–1078, 2011. + +Example: The following program checks that +\f[ \left[ \begin{array}{ccc} + \cos1 & -\sin1 & 0 \\ + \sin1 & \cos1 & 0 \\ + 0 & 0 & 1 + \end{array} \right]^{\frac14\pi} = \left[ \begin{array}{ccc} + \frac12\sqrt2 & -\frac12\sqrt2 & 0 \\ + \frac12\sqrt2 & \frac12\sqrt2 & 0 \\ + 0 & 0 & 1 + \end{array} \right]. \f] +This corresponds to \f$ \frac14\pi \f$ rotations of 1 radian around +the z-axis. + +\include MatrixPower.cpp +Output: \verbinclude MatrixPower.out + +MatrixBase::pow() is user-friendly. However, there are some +circumstances under which you should use class MatrixPower directly. +MatrixPower can save the result of Schur decomposition, so it's +better for computing various powers for the same matrix. + +Example: +\include MatrixPower_optimal.cpp +Output: \verbinclude MatrixPower_optimal.out + +\note \p M has to be a matrix of \c float, \c double, `long +double`, \c complex, \c complex, or +\c complex . + +\sa MatrixBase::exp(), MatrixBase::log(), class MatrixPower. + + +\subsection matrixbase_matrixfunction MatrixBase::matrixFunction() + +Compute a matrix function. + +\code +const MatrixFunctionReturnValue MatrixBase::matrixFunction(typename internal::stem_function::Scalar>::type f) const +\endcode + +\param[in] M argument of matrix function, should be a square matrix. +\param[in] f an entire function; \c f(x,n) should compute the n-th +derivative of f at x. +\returns expression representing \p f applied to \p M. + +Suppose that \p M is a matrix whose entries have type \c Scalar. +Then, the second argument, \p f, should be a function with prototype +\code +ComplexScalar f(ComplexScalar, int) +\endcode +where \c ComplexScalar = \c std::complex if \c Scalar is +real (e.g., \c float or \c double) and \c ComplexScalar = +\c Scalar if \c Scalar is complex. The return value of \c f(x,n) +should be \f$ f^{(n)}(x) \f$, the n-th derivative of f at x. + +This routine uses the algorithm described in: +Philip Davies and Nicholas J. Higham, +"A Schur-Parlett algorithm for computing matrix functions", +SIAM J. %Matrix Anal. Applic., 25:464–485, 2003. + +The actual work is done by the MatrixFunction class. + +Example: The following program checks that +\f[ \exp \left[ \begin{array}{ccc} + 0 & \frac14\pi & 0 \\ + -\frac14\pi & 0 & 0 \\ + 0 & 0 & 0 + \end{array} \right] = \left[ \begin{array}{ccc} + \frac12\sqrt2 & -\frac12\sqrt2 & 0 \\ + \frac12\sqrt2 & \frac12\sqrt2 & 0 \\ + 0 & 0 & 1 + \end{array} \right]. \f] +This corresponds to a rotation of \f$ \frac14\pi \f$ radians around +the z-axis. This is the same example as used in the documentation +of \ref matrixbase_exp "exp()". + +\include MatrixFunction.cpp +Output: \verbinclude MatrixFunction.out + +Note that the function \c expfn is defined for complex numbers +\c x, even though the matrix \c A is over the reals. Instead of +\c expfn, we could also have used StdStemFunctions::exp: +\code +A.matrixFunction(StdStemFunctions >::exp, &B); +\endcode + + + +\subsection matrixbase_sin MatrixBase::sin() + +Compute the matrix sine. + +\code +const MatrixFunctionReturnValue MatrixBase::sin() const +\endcode + +\param[in] M a square matrix. +\returns expression representing \f$ \sin(M) \f$. + +This function computes the matrix sine. Use ArrayBase::sin() for computing the entry-wise sine. + +The implementation calls \ref matrixbase_matrixfunction "matrixFunction()" with StdStemFunctions::sin(). + +Example: \include MatrixSine.cpp +Output: \verbinclude MatrixSine.out + + + +\subsection matrixbase_sinh MatrixBase::sinh() + +Compute the matrix hyperbolic sine. + +\code +MatrixFunctionReturnValue MatrixBase::sinh() const +\endcode + +\param[in] M a square matrix. +\returns expression representing \f$ \sinh(M) \f$ + +This function calls \ref matrixbase_matrixfunction "matrixFunction()" with StdStemFunctions::sinh(). + +Example: \include MatrixSinh.cpp +Output: \verbinclude MatrixSinh.out + + +\subsection matrixbase_sqrt MatrixBase::sqrt() + +Compute the matrix square root. + +\code +const MatrixSquareRootReturnValue MatrixBase::sqrt() const +\endcode + +\param[in] M invertible matrix whose square root is to be computed. +\returns expression representing the matrix square root of \p M. + +The matrix square root of \f$ M \f$ is the matrix \f$ M^{1/2} \f$ +whose square is the original matrix; so if \f$ S = M^{1/2} \f$ then +\f$ S^2 = M \f$. This is different from taking the square root of all +the entries in the matrix; use ArrayBase::sqrt() if you want to do the +latter. + +In the real case, the matrix \f$ M \f$ should be invertible and +it should have no eigenvalues which are real and negative (pairs of +complex conjugate eigenvalues are allowed). In that case, the matrix +has a square root which is also real, and this is the square root +computed by this function. + +The matrix square root is computed by first reducing the matrix to +quasi-triangular form with the real Schur decomposition. The square +root of the quasi-triangular matrix can then be computed directly. The +cost is approximately \f$ 25 n^3 \f$ real flops for the real Schur +decomposition and \f$ 3\frac13 n^3 \f$ real flops for the remainder +(though the computation time in practice is likely more than this +indicates). + +Details of the algorithm can be found in: Nicholas J. Highan, +"Computing real square roots of a real matrix", Linear Algebra +Appl., 88/89:405–430, 1987. + +If the matrix is positive-definite symmetric, then the square +root is also positive-definite symmetric. In this case, it is best to +use SelfAdjointEigenSolver::operatorSqrt() to compute it. + +In the complex case, the matrix \f$ M \f$ should be invertible; +this is a restriction of the algorithm. The square root computed by +this algorithm is the one whose eigenvalues have an argument in the +interval \f$ (-\frac12\pi, \frac12\pi] \f$. This is the usual branch +cut. + +The computation is the same as in the real case, except that the +complex Schur decomposition is used to reduce the matrix to a +triangular matrix. The theoretical cost is the same. Details are in: +Åke Björck and Sven Hammarling, "A Schur method for the +square root of a matrix", Linear Algebra Appl., +52/53:127–140, 1983. + +Example: The following program checks that the square root of +\f[ \left[ \begin{array}{cc} + \cos(\frac13\pi) & -\sin(\frac13\pi) \\ + \sin(\frac13\pi) & \cos(\frac13\pi) + \end{array} \right], \f] +corresponding to a rotation over 60 degrees, is a rotation over 30 degrees: +\f[ \left[ \begin{array}{cc} + \cos(\frac16\pi) & -\sin(\frac16\pi) \\ + \sin(\frac16\pi) & \cos(\frac16\pi) + \end{array} \right]. \f] + +\include MatrixSquareRoot.cpp +Output: \verbinclude MatrixSquareRoot.out + +\sa class RealSchur, class ComplexSchur, class MatrixSquareRoot, + SelfAdjointEigenSolver::operatorSqrt(). + +*/ + +#endif // EIGEN_MATRIX_FUNCTIONS_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MoreVectorization b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MoreVectorization new file mode 100644 index 0000000000000000000000000000000000000000..ea86fac311b7c1cb4394bdfe09f6ae50b9fbce7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/MoreVectorization @@ -0,0 +1,26 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MOREVECTORIZATION_MODULE_H +#define EIGEN_MOREVECTORIZATION_MODULE_H + +#include "../../Eigen/Core" + +namespace Eigen { + +/** + * \defgroup MoreVectorization More vectorization module + */ + +} + +// IWYU pragma: begin_exports +#include "src/MoreVectorization/MathFunctions.h" +// IWYU pragma: end_exports + +#endif // EIGEN_MOREVECTORIZATION_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NNLS b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NNLS new file mode 100644 index 0000000000000000000000000000000000000000..280450850faed46e365e8439dd6d6133df48b11c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NNLS @@ -0,0 +1,388 @@ +/* Non-Negagive Least Squares Algorithm for Eigen. + * + * Copyright (C) 2021 Essex Edwards, + * Copyright (C) 2013 Hannes Matuschek, hannes.matuschek at uni-potsdam.de + * + * This Source Code Form is subject to the terms of the Mozilla + * Public License v. 2.0. If a copy of the MPL was not distributed + * with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/** \defgroup nnls Non-Negative Least Squares (NNLS) Module + * This module provides a single class @c Eigen::NNLS implementing the NNLS algorithm. + * The algorithm is described in "SOLVING LEAST SQUARES PROBLEMS", by Charles L. Lawson and + * Richard J. Hanson, Prentice-Hall, 1974 and solves optimization problems of the form + * + * \f[ \min \left\Vert Ax-b\right\Vert_2^2\quad s.t.\, x\ge 0\,.\f] + * + * The algorithm solves the constrained least-squares problem above by iteratively improving + * an estimate of which constraints are active (elements of \f$x\f$ equal to zero) + * and which constraints are inactive (elements of \f$x\f$ greater than zero). + * Each iteration, an unconstrained linear least-squares problem solves for the + * components of \f$x\f$ in the (estimated) inactive set and the sets are updated. + * The unconstrained problem minimizes \f$\left\Vert A^Nx^N-b\right\Vert_2^2\f$, + * where \f$A^N\f$ is a matrix formed by selecting all columns of A which are + * in the inactive set \f$N\f$. + * + */ + +#ifndef EIGEN_NNLS_H +#define EIGEN_NNLS_H + +#include "../../Eigen/Core" +#include "../../Eigen/QR" + +#include + +namespace Eigen { + +/** \ingroup nnls + * \class NNLS + * \brief Implementation of the Non-Negative Least Squares (NNLS) algorithm. + * \tparam MatrixType The type of the system matrix \f$A\f$. + * + * This class implements the NNLS algorithm as described in "SOLVING LEAST SQUARES PROBLEMS", + * Charles L. Lawson and Richard J. Hanson, Prentice-Hall, 1974. This algorithm solves a least + * squares problem iteratively and ensures that the solution is non-negative. I.e. + * + * \f[ \min \left\Vert Ax-b\right\Vert_2^2\quad s.t.\, x\ge 0 \f] + * + * The algorithm solves the constrained least-squares problem above by iteratively improving + * an estimate of which constraints are active (elements of \f$x\f$ equal to zero) + * and which constraints are inactive (elements of \f$x\f$ greater than zero). + * Each iteration, an unconstrained linear least-squares problem solves for the + * components of \f$x\f$ in the (estimated) inactive set and the sets are updated. + * The unconstrained problem minimizes \f$\left\Vert A^Nx^N-b\right\Vert_2^2\f$, + * where \f$A^N\f$ is a matrix formed by selecting all columns of A which are + * in the inactive set \f$N\f$. + * + * See the + * wikipedia page on non-negative least squares for more background information. + * + * \note Please note that it is possible to construct an NNLS problem for which the + * algorithm does not converge. In practice these cases are extremely rare. + */ +template +class NNLS { + public: + typedef MatrixType_ MatrixType; + + enum { + RowsAtCompileTime = MatrixType::RowsAtCompileTime, + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + Options = MatrixType::Options, + MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::Index Index; + + /** Type of a row vector of the system matrix \f$A\f$. */ + typedef Matrix SolutionVectorType; + /** Type of a column vector of the system matrix \f$A\f$. */ + typedef Matrix RhsVectorType; + typedef Matrix IndicesType; + + /** */ + NNLS(); + + /** \brief Constructs a NNLS sovler and initializes it with the given system matrix @c A. + * \param A Specifies the system matrix. + * \param max_iter Specifies the maximum number of iterations to solve the system. + * \param tol Specifies the precision of the optimum. + * This is an absolute tolerance on the gradient of the Lagrangian, \f$A^T(Ax-b)-\lambda\f$ + * (with Lagrange multipliers \f$\lambda\f$). + */ + NNLS(const MatrixType &A, Index max_iter = -1, Scalar tol = NumTraits::dummy_precision()); + + /** Initializes the solver with the matrix \a A for further solving NNLS problems. + * + * This function mostly initializes/computes the preconditioner. In the future + * we might, for instance, implement column reordering for faster matrix vector products. + */ + template + NNLS &compute(const EigenBase &A); + + /** \brief Solves the NNLS problem. + * + * The dimension of @c b must be equal to the number of rows of @c A, given to the constructor. + * + * \returns The approximate solution vector \f$ x \f$. Use info() to determine if the solve was a success or not. + * \sa info() + */ + const SolutionVectorType &solve(const RhsVectorType &b); + + /** \brief Returns the solution if a problem was solved. + * If not, an uninitialized vector may be returned. */ + const SolutionVectorType &x() const { return x_; } + + /** \returns the tolerance threshold used by the stopping criteria. + * \sa setTolerance() + */ + Scalar tolerance() const { return tolerance_; } + + /** Sets the tolerance threshold used by the stopping criteria. + * + * This is an absolute tolerance on the gradient of the Lagrangian, \f$A^T(Ax-b)-\lambda\f$ + * (with Lagrange multipliers \f$\lambda\f$). + */ + NNLS &setTolerance(const Scalar &tolerance) { + tolerance_ = tolerance; + return *this; + } + + /** \returns the max number of iterations. + * It is either the value set by setMaxIterations or, by default, twice the number of columns of the matrix. + */ + Index maxIterations() const { return max_iter_ < 0 ? 2 * A_.cols() : max_iter_; } + + /** Sets the max number of iterations. + * Default is twice the number of columns of the matrix. + * The algorithm requires at least k iterations to produce a solution vector with k non-zero entries. + */ + NNLS &setMaxIterations(Index maxIters) { + max_iter_ = maxIters; + return *this; + } + + /** \returns the number of iterations (least-squares solves) performed during the last solve */ + Index iterations() const { return iterations_; } + + /** \returns Success if the iterations converged, and an error values otherwise. */ + ComputationInfo info() const { return info_; } + + private: + /** \internal Adds the given index @c idx to the inactive set N and updates the QR decomposition of \f$A^N\f$. */ + void moveToInactiveSet_(Index idx); + + /** \internal Removes the given index idx from the inactive set N and updates the QR decomposition of \f$A^N\f$. */ + void moveToActiveSet_(Index idx); + + /** \internal Solves the least-squares problem \f$\left\Vert y-A^Nx\right\Vert_2^2\f$. */ + void solveInactiveSet_(const RhsVectorType &b); + + private: + typedef Matrix MatrixAtAType; + + /** \internal Holds the maximum number of iterations for the NNLS algorithm. + * @c -1 means to use the default value. */ + Index max_iter_; + /** \internal Holds the number of iterations. */ + Index iterations_; + /** \internal Holds success/fail of the last solve. */ + ComputationInfo info_; + /** \internal Size of the inactive set. */ + Index numInactive_; + /** \internal Accuracy of the algorithm w.r.t the optimality of the solution (gradient). */ + Scalar tolerance_; + /** \internal The system matrix, a copy of the one given to the constructor. */ + MatrixType A_; + /** \internal Precomputed product \f$A^TA\f$. */ + MatrixAtAType AtA_; + /** \internal Will hold the solution. */ + SolutionVectorType x_; + /** \internal Will hold the current gradient.\f$A^Tb - A^TAx\f$ */ + SolutionVectorType gradient_; + /** \internal Will hold the partial solution. */ + SolutionVectorType y_; + /** \internal Precomputed product \f$A^Tb\f$. */ + SolutionVectorType Atb_; + /** \internal Holds the current permutation partitioning the active and inactive sets. + * The first @c numInactive_ elements form the inactive set and the rest the active set. */ + IndicesType index_sets_; + /** \internal QR decomposition to solve the (inactive) sub system (together with @c qrCoeffs_). */ + MatrixType QR_; + /** \internal QR decomposition to solve the (inactive) sub system (together with @c QR_). */ + SolutionVectorType qrCoeffs_; + /** \internal Some workspace for QR decomposition. */ + SolutionVectorType tempSolutionVector_; + RhsVectorType tempRhsVector_; +}; + +/* ******************************************************************************************** + * Implementation + * ******************************************************************************************** */ + +template +NNLS::NNLS() + : max_iter_(-1), + iterations_(0), + info_(ComputationInfo::InvalidInput), + numInactive_(0), + tolerance_(NumTraits::dummy_precision()) {} + +template +NNLS::NNLS(const MatrixType &A, Index max_iter, Scalar tol) : max_iter_(max_iter), tolerance_(tol) { + compute(A); +} + +template +template +NNLS &NNLS::compute(const EigenBase &A) { + // Ensure Scalar type is real. The non-negativity constraint doesn't obviously extend to complex numbers. + EIGEN_STATIC_ASSERT(!NumTraits::IsComplex, NUMERIC_TYPE_MUST_BE_REAL); + + // max_iter_: unchanged + iterations_ = 0; + info_ = ComputationInfo::Success; + numInactive_ = 0; + // tolerance: unchanged + A_ = A.derived(); + AtA_.noalias() = A_.transpose() * A_; + x_.resize(A_.cols()); + gradient_.resize(A_.cols()); + y_.resize(A_.cols()); + Atb_.resize(A_.cols()); + index_sets_.resize(A_.cols()); + QR_.resize(A_.rows(), A_.cols()); + qrCoeffs_.resize(A_.cols()); + tempSolutionVector_.resize(A_.cols()); + tempRhsVector_.resize(A_.rows()); + + return *this; +} + +template +const typename NNLS::SolutionVectorType &NNLS::solve(const RhsVectorType &b) { + // Initialize solver + iterations_ = 0; + info_ = ComputationInfo::NumericalIssue; + x_.setZero(); + + index_sets_ = IndicesType::LinSpaced(A_.cols(), 0, A_.cols() - 1); // Identity permutation. + numInactive_ = 0; + + // Precompute A^T*b + Atb_.noalias() = A_.transpose() * b; + + const Index maxIterations = this->maxIterations(); + + // OUTER LOOP + while (true) { + // Early exit if all variables are inactive, which breaks 'maxCoeff' below. + if (A_.cols() == numInactive_) { + info_ = ComputationInfo::Success; + return x_; + } + + // Find the maximum element of the gradient in the active set. + // If it is small or negative, then we have converged. + // Else, we move that variable to the inactive set. + gradient_.noalias() = Atb_ - AtA_ * x_; + + const Index numActive = A_.cols() - numInactive_; + Index argmaxGradient = -1; + const Scalar maxGradient = gradient_(index_sets_.tail(numActive)).maxCoeff(&argmaxGradient); + argmaxGradient += numInactive_; // beacause tail() skipped the first numInactive_ elements + + if (maxGradient < tolerance_) { + info_ = ComputationInfo::Success; + return x_; + } + + moveToInactiveSet_(argmaxGradient); + + // INNER LOOP + while (true) { + // Check if max. number of iterations is reached + if (iterations_ >= maxIterations) { + info_ = ComputationInfo::NoConvergence; + return x_; + } + + // Solve least-squares problem in inactive set only, + // this step is rather trivial as moveToInactiveSet_ & moveToActiveSet_ + // updates the QR decomposition of inactive columns A^N. + // solveInactiveSet_ puts the solution in y_ + solveInactiveSet_(b); + ++iterations_; // The solve is expensive, so that is what we count as an iteration. + + // Check feasability... + bool feasible = true; + Scalar alpha = NumTraits::highest(); + Index infeasibleIdx = -1; // Which variable became infeasible first. + for (Index i = 0; i < numInactive_; i++) { + Index idx = index_sets_[i]; + if (y_(idx) < 0) { + // t should always be in [0,1]. + Scalar t = -x_(idx) / (y_(idx) - x_(idx)); + if (alpha > t) { + alpha = t; + infeasibleIdx = i; + feasible = false; + } + } + } + eigen_assert(feasible || 0 <= infeasibleIdx); + + // If solution is feasible, exit to outer loop + if (feasible) { + x_ = y_; + break; + } + + // Infeasible solution -> interpolate to feasible one + for (Index i = 0; i < numInactive_; i++) { + Index idx = index_sets_[i]; + x_(idx) += alpha * (y_(idx) - x_(idx)); + } + + // Remove these indices from the inactive set and update QR decomposition + moveToActiveSet_(infeasibleIdx); + } + } +} + +template +void NNLS::moveToInactiveSet_(Index idx) { + // Update permutation matrix: + std::swap(index_sets_(idx), index_sets_(numInactive_)); + numInactive_++; + + // Perform rank-1 update of the QR decomposition stored in QR_ & qrCoeff_ + internal::householder_qr_inplace_update(QR_, qrCoeffs_, A_.col(index_sets_(numInactive_ - 1)), numInactive_ - 1, + tempSolutionVector_.data()); +} + +template +void NNLS::moveToActiveSet_(Index idx) { + // swap index with last inactive one & reduce number of inactive columns + std::swap(index_sets_(idx), index_sets_(numInactive_ - 1)); + numInactive_--; + // Update QR decomposition starting from the removed index up to the end [idx, ..., numInactive_] + for (Index i = idx; i < numInactive_; i++) { + Index col = index_sets_(i); + internal::householder_qr_inplace_update(QR_, qrCoeffs_, A_.col(col), i, tempSolutionVector_.data()); + } +} + +template +void NNLS::solveInactiveSet_(const RhsVectorType &b) { + eigen_assert(numInactive_ > 0); + + tempRhsVector_ = b; + + // tmpRHS(0:numInactive_-1) := Q'*b + // tmpRHS(numInactive_:end) := useless stuff we would rather not compute at all. + tempRhsVector_.applyOnTheLeft( + householderSequence(QR_.leftCols(numInactive_), qrCoeffs_.head(numInactive_)).transpose()); + + // tempSol(0:numInactive_-1) := inv(R) * Q' * b + // = the least-squares solution for the inactive variables. + tempSolutionVector_.head(numInactive_) = // + QR_.topLeftCorner(numInactive_, numInactive_) // + .template triangularView() // + .solve(tempRhsVector_.head(numInactive_)); // + + // tempSol(numInactive_:end) := 0 = the value for the constrained variables. + tempSolutionVector_.tail(y_.size() - numInactive_).setZero(); + + // Back permute into original column order of A + y_.noalias() = index_sets_.asPermutation() * tempSolutionVector_.head(y_.size()); +} + +} // namespace Eigen + +#endif // EIGEN_NNLS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NonLinearOptimization b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NonLinearOptimization new file mode 100644 index 0000000000000000000000000000000000000000..929c5038b33015420031b5a0c8d135c7a437e4d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NonLinearOptimization @@ -0,0 +1,141 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NONLINEAROPTIMIZATION_MODULE_H +#define EIGEN_NONLINEAROPTIMIZATION_MODULE_H + +#include + +#include "../../Eigen/Core" +#include "../../Eigen/Jacobi" +#include "../../Eigen/QR" +#include "NumericalDiff" + +/** + * \defgroup NonLinearOptimization_Module Non linear optimization module + * + * \code + * #include + * \endcode + * + * This module provides implementation of two important algorithms in non linear + * optimization. In both cases, we consider a system of non linear functions. Of + * course, this should work, and even work very well if those functions are + * actually linear. But if this is so, you should probably better use other + * methods more fitted to this special case. + * + * One algorithm allows to find a least-squares solution of such a system + * (Levenberg-Marquardt algorithm) and the second one is used to find + * a zero for the system (Powell hybrid "dogleg" method). + * + * This code is a port of minpack (http://en.wikipedia.org/wiki/MINPACK). + * Minpack is a very famous, old, robust and well renowned package, written in + * fortran. Those implementations have been carefully tuned, tested, and used + * for several decades. + * + * The original fortran code was automatically translated using f2c (http://en.wikipedia.org/wiki/F2c) in C, + * then c++, and then cleaned by several different authors. + * The last one of those cleanings being our starting point : + * http://devernay.free.fr/hacks/cminpack.html + * + * Finally, we ported this code to Eigen, creating classes and API + * coherent with Eigen. When possible, we switched to Eigen + * implementation, such as most linear algebra (vectors, matrices, stable norms). + * + * Doing so, we were very careful to check the tests we setup at the very + * beginning, which ensure that the same results are found. + * + * \section Tests Tests + * + * The tests are placed in the file unsupported/test/NonLinear.cpp. + * + * There are two kinds of tests : those that come from examples bundled with cminpack. + * They guaranty we get the same results as the original algorithms (value for 'x', + * for the number of evaluations of the function, and for the number of evaluations + * of the Jacobian if ever). + * + * Other tests were added by myself at the very beginning of the + * process and check the results for Levenberg-Marquardt using the reference data + * on http://www.itl.nist.gov/div898/strd/nls/nls_main.shtml. Since then i've + * carefully checked that the same results were obtained when modifying the + * code. Please note that we do not always get the exact same decimals as they do, + * but this is ok : they use 128bits float, and we do the tests using the C type 'double', + * which is 64 bits on most platforms (x86 and amd64, at least). + * I've performed those tests on several other implementations of Levenberg-Marquardt, and + * (c)minpack performs VERY well compared to those, both in accuracy and speed. + * + * The documentation for running the tests is on the wiki + * http://eigen.tuxfamily.org/index.php?title=Tests + * + * \section API API: overview of methods + * + * Both algorithms needs a functor computing the Jacobian. It can be computed by + * hand, using auto-differentiation (see \ref AutoDiff_Module), or using numerical + * differences (see \ref NumericalDiff_Module). For instance: + *\code + * MyFunc func; + * NumericalDiff func_with_num_diff(func); + * LevenbergMarquardt > lm(func_with_num_diff); + * \endcode + * For HybridNonLinearSolver, the method solveNumericalDiff() does the above wrapping for + * you. + * + * The methods LevenbergMarquardt.lmder1()/lmdif1()/lmstr1() and + * HybridNonLinearSolver.hybrj1()/hybrd1() are specific methods from the original + * minpack package that you probably should NOT use until you are porting a code that + * was previously using minpack. They just define a 'simple' API with default values + * for some parameters. + * + * All algorithms are provided using two APIs : + * - one where the user inits the algorithm, and uses '*OneStep()' as much as he wants : + * this way the caller have control over the steps + * - one where the user just calls a method (optimize() or solve()) which will + * handle the loop: init + loop until a stop condition is met. Those are provided for + * convenience. + * + * As an example, the method LevenbergMarquardt::minimize() is + * implemented as follow: + * \code + * Status LevenbergMarquardt::minimize(FVectorType &x, const int mode) + * { + * Status status = minimizeInit(x, mode); + * do { + * status = minimizeOneStep(x, mode); + * } while (status==Running); + * return status; + * } + * \endcode + * + * \section examples Examples + * + * The easiest way to understand how to use this module is by looking at the many examples in the file + * unsupported/test/NonLinearOptimization.cpp. + */ + +// IWYU pragma: begin_exports +#ifndef EIGEN_PARSED_BY_DOXYGEN + +#include "src/NonLinearOptimization/qrsolv.h" +#include "src/NonLinearOptimization/r1updt.h" +#include "src/NonLinearOptimization/r1mpyq.h" +#include "src/NonLinearOptimization/rwupdt.h" +#include "src/NonLinearOptimization/fdjac1.h" +#include "src/NonLinearOptimization/lmpar.h" +#include "src/NonLinearOptimization/dogleg.h" +#include "src/NonLinearOptimization/covar.h" + +#include "src/NonLinearOptimization/chkder.h" + +#endif + +#include "src/NonLinearOptimization/HybridNonLinearSolver.h" +#include "src/NonLinearOptimization/LevenbergMarquardt.h" +// IWYU pragma: end_exports + +#endif // EIGEN_NONLINEAROPTIMIZATION_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NumericalDiff b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NumericalDiff new file mode 100644 index 0000000000000000000000000000000000000000..542e51ad9bab8c328c56599821808a111e580af4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/NumericalDiff @@ -0,0 +1,58 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NUMERICALDIFF_MODULE_H +#define EIGEN_NUMERICALDIFF_MODULE_H + +#include "../../Eigen/Core" + +namespace Eigen { + +/** + * \defgroup NumericalDiff_Module Numerical differentiation module + * + * \code + * #include + * \endcode + * + * See http://en.wikipedia.org/wiki/Numerical_differentiation + * + * Warning : this should NOT be confused with automatic differentiation, which + * is a different method and has its own module in Eigen : \ref + * AutoDiff_Module. + * + * Currently only "Forward" and "Central" schemes are implemented. Those + * are basic methods, and there exist some more elaborated way of + * computing such approximates. They are implemented using both + * proprietary and free software, and usually requires linking to an + * external library. It is very easy for you to write a functor + * using such software, and the purpose is quite orthogonal to what we + * want to achieve with Eigen. + * + * This is why we will not provide wrappers for every great numerical + * differentiation software that exist, but should rather stick with those + * basic ones, that still are useful for testing. + * + * Also, the \ref NonLinearOptimization_Module needs this in order to + * provide full features compatibility with the original (c)minpack + * package. + * + */ +} + +//@{ + +// IWYU pragma: begin_exports +#include "src/NumericalDiff/NumericalDiff.h" +// IWYU pragma: end_exports + +//@} + + +#endif // EIGEN_NUMERICALDIFF_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/OpenGLSupport b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/OpenGLSupport new file mode 100644 index 0000000000000000000000000000000000000000..24683333ff390e70f86efd3ef3f153f6e056b5b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/OpenGLSupport @@ -0,0 +1,322 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_OPENGL_MODULE_H +#define EIGEN_OPENGL_MODULE_H + +#include "../../Eigen/Geometry" + +#if defined(__APPLE_CC__) + #include +#else + #include +#endif + +namespace Eigen { + +/** + * \defgroup OpenGLSUpport_Module OpenGL Support module + * + * This module provides wrapper functions for a couple of OpenGL functions + * which simplify the way to pass Eigen's object to openGL. + * Here is an example: + * + * \code + * // You need to add path_to_eigen/unsupported to your include path. + * #include + * // ... + * Vector3f x, y; + * Matrix3f rot; + * + * glVertex(y + x * rot); + * + * Quaternion q; + * glRotate(q); + * + * // ... + * \endcode + * + */ +//@{ + +#define EIGEN_GL_FUNC_DECLARATION(FUNC) \ +namespace internal { \ + template< typename XprType, \ + typename Scalar = typename XprType::Scalar, \ + int Rows = XprType::RowsAtCompileTime, \ + int Cols = XprType::ColsAtCompileTime, \ + bool IsGLCompatible = bool(internal::evaluator::Flags&LinearAccessBit) \ + && bool(XprType::Flags&DirectAccessBit) \ + && (XprType::IsVectorAtCompileTime || (XprType::Flags&RowMajorBit)==0)> \ + struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl); \ + \ + template \ + struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(const XprType& p) { \ + EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl)::type>::run(p); } \ + }; \ +} \ + \ +template inline void FUNC(const Eigen::DenseBase& p) { \ + EIGEN_CAT(EIGEN_CAT(internal::gl_,FUNC),_impl)::run(p.derived()); \ +} + + +#define EIGEN_GL_FUNC_SPECIALIZATION_MAT(FUNC,SCALAR,ROWS,COLS,SUFFIX) \ +namespace internal { \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(const XprType& p) { FUNC##SUFFIX(p.data()); } \ + }; \ +} + + +#define EIGEN_GL_FUNC_SPECIALIZATION_VEC(FUNC,SCALAR,SIZE,SUFFIX) \ +namespace internal { \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(const XprType& p) { FUNC##SUFFIX(p.data()); } \ + }; \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(const XprType& p) { FUNC##SUFFIX(p.data()); } \ + }; \ +} + + +EIGEN_GL_FUNC_DECLARATION (glVertex) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,int, 2,2iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,short, 2,2sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,float, 2,2fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,double, 2,2dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,int, 3,3iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,short, 3,3sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,double, 3,3dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,int, 4,4iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,short, 4,4sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,float, 4,4fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glVertex,double, 4,4dv) + +EIGEN_GL_FUNC_DECLARATION (glTexCoord) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,int, 2,2iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,short, 2,2sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,float, 2,2fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,double, 2,2dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,int, 3,3iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,short, 3,3sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,double, 3,3dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,int, 4,4iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,short, 4,4sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,float, 4,4fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTexCoord,double, 4,4dv) + +EIGEN_GL_FUNC_DECLARATION (glColor) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,int, 2,2iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,short, 2,2sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,float, 2,2fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,double, 2,2dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,int, 3,3iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,short, 3,3sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,double, 3,3dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,int, 4,4iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,short, 4,4sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,float, 4,4fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glColor,double, 4,4dv) + +EIGEN_GL_FUNC_DECLARATION (glNormal) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glNormal,int, 3,3iv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glNormal,short, 3,3sv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glNormal,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glNormal,double, 3,3dv) + +inline void glScale2fv(const float* v) { glScalef(v[0], v[1], 1.f); } +inline void glScale2dv(const double* v) { glScaled(v[0], v[1], 1.0); } +inline void glScale3fv(const float* v) { glScalef(v[0], v[1], v[2]); } +inline void glScale3dv(const double* v) { glScaled(v[0], v[1], v[2]); } + +EIGEN_GL_FUNC_DECLARATION (glScale) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glScale,float, 2,2fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glScale,double, 2,2dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glScale,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glScale,double, 3,3dv) + +template void glScale(const UniformScaling& s) { glScale(Matrix::Constant(s.factor())); } + +inline void glTranslate2fv(const float* v) { glTranslatef(v[0], v[1], 0.f); } +inline void glTranslate2dv(const double* v) { glTranslated(v[0], v[1], 0.0); } +inline void glTranslate3fv(const float* v) { glTranslatef(v[0], v[1], v[2]); } +inline void glTranslate3dv(const double* v) { glTranslated(v[0], v[1], v[2]); } + +EIGEN_GL_FUNC_DECLARATION (glTranslate) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTranslate,float, 2,2fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTranslate,double, 2,2dv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTranslate,float, 3,3fv) +EIGEN_GL_FUNC_SPECIALIZATION_VEC(glTranslate,double, 3,3dv) + +template void glTranslate(const Translation& t) { glTranslate(t.vector()); } +template void glTranslate(const Translation& t) { glTranslate(t.vector()); } + +EIGEN_GL_FUNC_DECLARATION (glMultMatrix) +EIGEN_GL_FUNC_SPECIALIZATION_MAT(glMultMatrix,float, 4,4,f) +EIGEN_GL_FUNC_SPECIALIZATION_MAT(glMultMatrix,double, 4,4,d) + +template void glMultMatrix(const Transform& t) { glMultMatrix(t.matrix()); } +template void glMultMatrix(const Transform& t) { glMultMatrix(t.matrix()); } +template void glMultMatrix(const Transform& t) { glMultMatrix(Transform(t).matrix()); } + +EIGEN_GL_FUNC_DECLARATION (glLoadMatrix) +EIGEN_GL_FUNC_SPECIALIZATION_MAT(glLoadMatrix,float, 4,4,f) +EIGEN_GL_FUNC_SPECIALIZATION_MAT(glLoadMatrix,double, 4,4,d) + +template void glLoadMatrix(const Transform& t) { glLoadMatrix(t.matrix()); } +template void glLoadMatrix(const Transform& t) { glLoadMatrix(t.matrix()); } +template void glLoadMatrix(const Transform& t) { glLoadMatrix(Transform(t).matrix()); } + +inline void glRotate(const Rotation2D& rot) +{ + glRotatef(rot.angle()*180.f/float(EIGEN_PI), 0.f, 0.f, 1.f); +} +inline void glRotate(const Rotation2D& rot) +{ + glRotated(rot.angle()*180.0/double(EIGEN_PI), 0.0, 0.0, 1.0); +} + +template void glRotate(const RotationBase& rot) +{ + Transform tr(rot); + glMultMatrix(tr.matrix()); +} + +#define EIGEN_GL_MAKE_CONST_const const +#define EIGEN_GL_MAKE_CONST__ +#define EIGEN_GL_EVAL(X) X + +#define EIGEN_GL_FUNC1_DECLARATION(FUNC,ARG1,CONST) \ +namespace internal { \ + template< typename XprType, \ + typename Scalar = typename XprType::Scalar, \ + int Rows = XprType::RowsAtCompileTime, \ + int Cols = XprType::ColsAtCompileTime, \ + bool IsGLCompatible = bool(internal::evaluator::Flags&LinearAccessBit) \ + && bool(XprType::Flags&DirectAccessBit) \ + && (XprType::IsVectorAtCompileTime || (XprType::Flags&RowMajorBit)==0)> \ + struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl); \ + \ + template \ + struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(ARG1 a,EIGEN_GL_EVAL(EIGEN_GL_MAKE_CONST_##CONST) XprType& p) { \ + EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl)::type>::run(a,p); } \ + }; \ +} \ + \ +template inline void FUNC(ARG1 a,EIGEN_GL_EVAL(EIGEN_GL_MAKE_CONST_##CONST) Eigen::DenseBase& p) { \ + EIGEN_CAT(EIGEN_CAT(internal::gl_,FUNC),_impl)::run(a,p.derived()); \ +} + + +#define EIGEN_GL_FUNC1_SPECIALIZATION_MAT(FUNC,ARG1,CONST,SCALAR,ROWS,COLS,SUFFIX) \ +namespace internal { \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(ARG1 a, EIGEN_GL_EVAL(EIGEN_GL_MAKE_CONST_##CONST) XprType& p) { FUNC##SUFFIX(a,p.data()); } \ + }; \ +} + + +#define EIGEN_GL_FUNC1_SPECIALIZATION_VEC(FUNC,ARG1,CONST,SCALAR,SIZE,SUFFIX) \ +namespace internal { \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(ARG1 a, EIGEN_GL_EVAL(EIGEN_GL_MAKE_CONST_##CONST) XprType& p) { FUNC##SUFFIX(a,p.data()); } \ + }; \ + template< typename XprType> struct EIGEN_CAT(EIGEN_CAT(gl_,FUNC),_impl) { \ + inline static void run(ARG1 a, EIGEN_GL_EVAL(EIGEN_GL_MAKE_CONST_##CONST) XprType& p) { FUNC##SUFFIX(a,p.data()); } \ + }; \ +} + +EIGEN_GL_FUNC1_DECLARATION (glGet,GLenum,_) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glGet,GLenum,_,float, 4,4,Floatv) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glGet,GLenum,_,double, 4,4,Doublev) + +// glUniform API + +#ifdef GL_VERSION_2_0 + +inline void glUniform2fv_ei (GLint loc, const float* v) { glUniform2fv(loc,1,v); } +inline void glUniform2iv_ei (GLint loc, const int* v) { glUniform2iv(loc,1,v); } + +inline void glUniform3fv_ei (GLint loc, const float* v) { glUniform3fv(loc,1,v); } +inline void glUniform3iv_ei (GLint loc, const int* v) { glUniform3iv(loc,1,v); } + +inline void glUniform4fv_ei (GLint loc, const float* v) { glUniform4fv(loc,1,v); } +inline void glUniform4iv_ei (GLint loc, const int* v) { glUniform4iv(loc,1,v); } + +inline void glUniformMatrix2fv_ei (GLint loc, const float* v) { glUniformMatrix2fv(loc,1,false,v); } +inline void glUniformMatrix3fv_ei (GLint loc, const float* v) { glUniformMatrix3fv(loc,1,false,v); } +inline void glUniformMatrix4fv_ei (GLint loc, const float* v) { glUniformMatrix4fv(loc,1,false,v); } + + +EIGEN_GL_FUNC1_DECLARATION (glUniform,GLint,const) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,float, 2,2fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,int, 2,2iv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,float, 3,3fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,int, 3,3iv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,float, 4,4fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,int, 4,4iv_ei) + +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 2,2,Matrix2fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 3,3,Matrix3fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 4,4,Matrix4fv_ei) + +#endif + +#ifdef GL_VERSION_2_1 + +inline void glUniformMatrix2x3fv_ei(GLint loc, const float* v) { glUniformMatrix2x3fv(loc,1,false,v); } +inline void glUniformMatrix3x2fv_ei(GLint loc, const float* v) { glUniformMatrix3x2fv(loc,1,false,v); } +inline void glUniformMatrix2x4fv_ei(GLint loc, const float* v) { glUniformMatrix2x4fv(loc,1,false,v); } +inline void glUniformMatrix4x2fv_ei(GLint loc, const float* v) { glUniformMatrix4x2fv(loc,1,false,v); } +inline void glUniformMatrix3x4fv_ei(GLint loc, const float* v) { glUniformMatrix3x4fv(loc,1,false,v); } +inline void glUniformMatrix4x3fv_ei(GLint loc, const float* v) { glUniformMatrix4x3fv(loc,1,false,v); } + +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 2,3,Matrix2x3fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 3,2,Matrix3x2fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 2,4,Matrix2x4fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 4,2,Matrix4x2fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 3,4,Matrix3x4fv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_MAT(glUniform,GLint,const,float, 4,3,Matrix4x3fv_ei) + +#endif + +#ifdef GL_VERSION_3_0 + +inline void glUniform2uiv_ei (GLint loc, const unsigned int* v) { glUniform2uiv(loc,1,v); } +inline void glUniform3uiv_ei (GLint loc, const unsigned int* v) { glUniform3uiv(loc,1,v); } +inline void glUniform4uiv_ei (GLint loc, const unsigned int* v) { glUniform4uiv(loc,1,v); } + +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,unsigned int, 2,2uiv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,unsigned int, 3,3uiv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,unsigned int, 4,4uiv_ei) + +#endif + +#ifdef GL_ARB_gpu_shader_fp64 +inline void glUniform2dv_ei (GLint loc, const double* v) { glUniform2dv(loc,1,v); } +inline void glUniform3dv_ei (GLint loc, const double* v) { glUniform3dv(loc,1,v); } +inline void glUniform4dv_ei (GLint loc, const double* v) { glUniform4dv(loc,1,v); } + +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,double, 2,2dv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,double, 3,3dv_ei) +EIGEN_GL_FUNC1_SPECIALIZATION_VEC(glUniform,GLint,const,double, 4,4dv_ei) +#endif + + +//@} + +} + +#endif // EIGEN_OPENGL_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Polynomials b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Polynomials new file mode 100644 index 0000000000000000000000000000000000000000..0df6fa1f8184fd9b471821f24c2598f705da4e8a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Polynomials @@ -0,0 +1,139 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_POLYNOMIALS_MODULE_H +#define EIGEN_POLYNOMIALS_MODULE_H + +#include "../../Eigen/Core" + +#include "../../Eigen/Eigenvalues" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// Note that EIGEN_HIDE_HEAVY_CODE has to be defined per module +#if (defined EIGEN_EXTERN_INSTANTIATIONS) && (EIGEN_EXTERN_INSTANTIATIONS>=2) + #ifndef EIGEN_HIDE_HEAVY_CODE + #define EIGEN_HIDE_HEAVY_CODE + #endif +#elif defined EIGEN_HIDE_HEAVY_CODE + #undef EIGEN_HIDE_HEAVY_CODE +#endif + +/** + * \defgroup Polynomials_Module Polynomials module + * \brief This module provides a QR based polynomial solver. + * + * To use this module, add + * \code + * #include + * \endcode + * at the start of your source file. + */ + +// IWYU pragma: begin_exports +#include "src/Polynomials/PolynomialUtils.h" +#include "src/Polynomials/Companion.h" +#include "src/Polynomials/PolynomialSolver.h" +// IWYU pragma: end_exports + +/** + \page polynomials Polynomials defines functions for dealing with polynomials + and a QR based polynomial solver. + \ingroup Polynomials_Module + + The remainder of the page documents first the functions for evaluating, computing + polynomials, computing estimates about polynomials and next the QR based polynomial + solver. + + \section polynomialUtils convenient functions to deal with polynomials + \subsection roots_to_monicPolynomial + The function + \code + void roots_to_monicPolynomial( const RootVector& rv, Polynomial& poly ) + \endcode + computes the coefficients \f$ a_i \f$ of + + \f$ p(x) = a_0 + a_{1}x + ... + a_{n-1}x^{n-1} + x^n \f$ + + where \f$ p \f$ is known through its roots i.e. \f$ p(x) = (x-r_1)(x-r_2)...(x-r_n) \f$. + + \subsection poly_eval + The function + \code + T poly_eval( const Polynomials& poly, const T& x ) + \endcode + evaluates a polynomial at a given point using stabilized Hörner method. + + The following code: first computes the coefficients in the monomial basis of the monic polynomial that has the provided roots; + then, it evaluates the computed polynomial, using a stabilized Hörner method. + + \include PolynomialUtils1.cpp + Output: \verbinclude PolynomialUtils1.out + + \subsection Cauchy bounds + The function + \code + Real cauchy_max_bound( const Polynomial& poly ) + \endcode + provides a maximum bound (the Cauchy one: \f$C(p)\f$) for the absolute value of a root of the given polynomial i.e. + \f$ \forall r_i \f$ root of \f$ p(x) = \sum_{k=0}^d a_k x^k \f$, + \f$ |r_i| \le C(p) = \sum_{k=0}^{d} \left | \frac{a_k}{a_d} \right | \f$ + The leading coefficient \f$ p \f$: should be non zero \f$a_d \neq 0\f$. + + + The function + \code + Real cauchy_min_bound( const Polynomial& poly ) + \endcode + provides a minimum bound (the Cauchy one: \f$c(p)\f$) for the absolute value of a non zero root of the given polynomial i.e. + \f$ \forall r_i \neq 0 \f$ root of \f$ p(x) = \sum_{k=0}^d a_k x^k \f$, + \f$ |r_i| \ge c(p) = \left( \sum_{k=0}^{d} \left | \frac{a_k}{a_0} \right | \right)^{-1} \f$ + + + + + \section QR polynomial solver class + Computes the complex roots of a polynomial by computing the eigenvalues of the associated companion matrix with the QR algorithm. + + The roots of \f$ p(x) = a_0 + a_1 x + a_2 x^2 + a_{3} x^3 + x^4 \f$ are the eigenvalues of + \f$ + \left [ + \begin{array}{cccc} + 0 & 0 & 0 & a_0 \\ + 1 & 0 & 0 & a_1 \\ + 0 & 1 & 0 & a_2 \\ + 0 & 0 & 1 & a_3 + \end{array} \right ] + \f$ + + However, the QR algorithm is not guaranteed to converge when there are several eigenvalues with same modulus. + + Therefore the current polynomial solver is guaranteed to provide a correct result only when the complex roots \f$r_1,r_2,...,r_d\f$ have distinct moduli i.e. + + \f$ \forall i,j \in [1;d],~ \| r_i \| \neq \| r_j \| \f$. + + With 32bit (float) floating types this problem shows up frequently. + However, almost always, correct accuracy is reached even in these cases for 64bit + (double) floating types and small polynomial degree (<20). + + \include PolynomialSolver1.cpp + + In the above example: + + -# a simple use of the polynomial solver is shown; + -# the accuracy problem with the QR algorithm is presented: a polynomial with almost conjugate roots is provided to the solver. + Those roots have almost same module therefore the QR algorithm failed to converge: the accuracy + of the last root is bad; + -# a simple way to circumvent the problem is shown: use doubles instead of floats. + + Output: \verbinclude PolynomialSolver1.out +*/ + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_POLYNOMIALS_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Skyline b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Skyline new file mode 100644 index 0000000000000000000000000000000000000000..7a9f0ca51d05582e7695b18741c73a5488e91893 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Skyline @@ -0,0 +1,41 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINE_MODULE_H +#define EIGEN_SKYLINE_MODULE_H + + +#include "../../Eigen/Core" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +#include +#include +#include +#include + +/** + * \defgroup Skyline_Module Skyline module + * + * + * + * + */ + +// IWYU pragma: begin_exports +#include "src/Skyline/SkylineUtil.h" +#include "src/Skyline/SkylineMatrixBase.h" +#include "src/Skyline/SkylineStorage.h" +#include "src/Skyline/SkylineMatrix.h" +#include "src/Skyline/SkylineInplaceLU.h" +#include "src/Skyline/SkylineProduct.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SKYLINE_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SparseExtra b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SparseExtra new file mode 100644 index 0000000000000000000000000000000000000000..88a639e5b618de9180f0d0fa7fa0a8af05e682c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SparseExtra @@ -0,0 +1,58 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_EXTRA_MODULE_H +#define EIGEN_SPARSE_EXTRA_MODULE_H + +#include "../../Eigen/Sparse" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef EIGEN_GOOGLEHASH_SUPPORT + #include + #include +#endif + +/** + * \defgroup SparseExtra_Module SparseExtra module + * + * This module contains some experimental features extending the sparse module: + * - A RandomSetter which is a wrapper object allowing to set/update a sparse matrix with random access. + * - A SparseInverse which calculates a sparse subset of the inverse of a sparse matrix corresponding to nonzeros of the input + * - MatrixMarket format(https://math.nist.gov/MatrixMarket/formats.html) readers and writers for sparse and dense matrices. + * + * \code + * #include + * \endcode + */ + +// IWYU pragma: begin_exports +#include "src/SparseExtra/RandomSetter.h" +#include "src/SparseExtra/SparseInverse.h" + +#include "src/SparseExtra/MarketIO.h" + +#if !defined(_WIN32) +#include +#include "src/SparseExtra/MatrixMarketIterator.h" +#endif +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSE_EXTRA_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SpecialFunctions b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SpecialFunctions new file mode 100644 index 0000000000000000000000000000000000000000..fb03db7fa8e95f014887022272cf6fc70b2c51b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/SpecialFunctions @@ -0,0 +1,105 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIALFUNCTIONS_MODULE_H +#define EIGEN_SPECIALFUNCTIONS_MODULE_H + +#include + +#include "../../Eigen/Core" + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +namespace Eigen { + +/** + * \defgroup SpecialFunctions_Module Special math functions module + * + * This module features additional coefficient-wise math functions available + * within the numext:: namespace for the scalar version, and as method and/or free + * functions of Array. Those include: + * + * - erf + * - erfc + * - lgamma + * - igamma + * - igamma_der_a + * - gamma_sample_der_alpha + * - igammac + * - digamma + * - ndtri + * - polygamma + * - zeta + * - betainc + * + * Bessel Functions + * - bessel_i0 + * - bessel_i0e + * - bessel_i1 + * - bessel_i1e + * - bessel_j0 + * - bessel_j1 + * - bessel_k0 + * - bessel_k0e + * - bessel_k1 + * - bessel_k1e + * - bessel_y0 + * - bessel_y1 + * + * \code + * #include + * \endcode + */ +//@{ + +} + +// IWYU pragma: begin_exports +#include "src/SpecialFunctions/BesselFunctionsImpl.h" +#include "src/SpecialFunctions/BesselFunctionsBFloat16.h" +#include "src/SpecialFunctions/BesselFunctionsHalf.h" +#include "src/SpecialFunctions/BesselFunctionsPacketMath.h" +#include "src/SpecialFunctions/BesselFunctionsFunctors.h" +#include "src/SpecialFunctions/BesselFunctionsArrayAPI.h" +#include "src/SpecialFunctions/SpecialFunctionsImpl.h" +#if defined(EIGEN_HIPCC) +#include "src/SpecialFunctions/HipVectorCompatibility.h" +#endif +#include "src/SpecialFunctions/SpecialFunctionsBFloat16.h" +#include "src/SpecialFunctions/SpecialFunctionsHalf.h" +#include "src/SpecialFunctions/SpecialFunctionsPacketMath.h" +#include "src/SpecialFunctions/SpecialFunctionsFunctors.h" +#include "src/SpecialFunctions/SpecialFunctionsArrayAPI.h" + +#if defined EIGEN_VECTORIZE_AVX512 + #include "src/SpecialFunctions/arch/AVX/BesselFunctions.h" + #include "src/SpecialFunctions/arch/AVX/SpecialFunctions.h" + #include "src/SpecialFunctions/arch/AVX512/BesselFunctions.h" + #include "src/SpecialFunctions/arch/AVX512/SpecialFunctions.h" +#elif defined EIGEN_VECTORIZE_AVX + #include "src/SpecialFunctions/arch/AVX/BesselFunctions.h" + #include "src/SpecialFunctions/arch/AVX/SpecialFunctions.h" +#elif defined EIGEN_VECTORIZE_NEON + #include "src/SpecialFunctions/arch/NEON/BesselFunctions.h" + #include "src/SpecialFunctions/arch/NEON/SpecialFunctions.h" +#endif + +#if defined EIGEN_VECTORIZE_GPU + #include "src/SpecialFunctions/arch/GPU/SpecialFunctions.h" +#endif +// IWYU pragma: end_exports + +namespace Eigen { +//@} +} + + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPECIALFUNCTIONS_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Splines b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Splines new file mode 100644 index 0000000000000000000000000000000000000000..b4fc81ed77c5d5703a4ecc4561af8088037c6291 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/Splines @@ -0,0 +1,37 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 20010-2011 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPLINES_MODULE_H +#define EIGEN_SPLINES_MODULE_H + +namespace Eigen +{ +/** + * \defgroup Splines_Module Spline and spline fitting module + * + * This module provides a simple multi-dimensional spline class while + * offering most basic functionality to fit a spline to point sets. + * + * \code + * #include + * \endcode + */ +} + +#include "../../Eigen/src/Core/util/DisableStupidWarnings.h" + +// IWYU pragma: begin_exports +#include "src/Splines/SplineFwd.h" +#include "src/Splines/Spline.h" +#include "src/Splines/SplineFitting.h" +// IWYU pragma: end_exports + +#include "../../Eigen/src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPLINES_MODULE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffJacobian.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffJacobian.h new file mode 100644 index 0000000000000000000000000000000000000000..6ef6bf4083430fa71a120c99c7b1dbc18a4ace46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffJacobian.h @@ -0,0 +1,89 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_AUTODIFF_JACOBIAN_H +#define EIGEN_AUTODIFF_JACOBIAN_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen +{ + +template class AutoDiffJacobian : public Functor +{ +public: + AutoDiffJacobian() : Functor() {} + AutoDiffJacobian(const Functor& f) : Functor(f) {} + + // forward constructors + template + AutoDiffJacobian(const T& ...Values) : Functor(Values...) {} + + typedef typename Functor::InputType InputType; + typedef typename Functor::ValueType ValueType; + typedef typename ValueType::Scalar Scalar; + + enum { + InputsAtCompileTime = InputType::RowsAtCompileTime, + ValuesAtCompileTime = ValueType::RowsAtCompileTime + }; + + typedef Matrix JacobianType; + typedef typename JacobianType::Index Index; + + typedef Matrix DerivativeType; + typedef AutoDiffScalar ActiveScalar; + + typedef Matrix ActiveInput; + typedef Matrix ActiveValue; + + // Some compilers don't accept variadic parameters after a default parameter, + // i.e., we can't just write _jac=0 but we need to overload operator(): + EIGEN_STRONG_INLINE + void operator() (const InputType& x, ValueType* v) const + { + this->operator()(x, v, 0); + } + template + void operator() (const InputType& x, ValueType* v, JacobianType* _jac, + const ParamsType&... Params) const + { + eigen_assert(v!=0); + + if (!_jac) + { + Functor::operator()(x, v, Params...); + return; + } + + JacobianType& jac = *_jac; + + ActiveInput ax = x.template cast(); + ActiveValue av(jac.rows()); + + if(InputsAtCompileTime==Dynamic) + for (Index j=0; j +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_AUTODIFF_SCALAR_H +#define EIGEN_AUTODIFF_SCALAR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +struct make_coherent_impl { + static void run(A&, B&) {} +}; + +// resize a to match b is a.size()==0, and conversely. +template +void make_coherent(const A& a, const B&b) +{ + make_coherent_impl::run(a.const_cast_derived(), b.const_cast_derived()); +} + +template struct auto_diff_special_op; + +} // end namespace internal + +template class AutoDiffScalar; + +template +inline AutoDiffScalar MakeAutoDiffScalar(const typename NewDerType::Scalar& value, const NewDerType &der) { + return AutoDiffScalar(value,der); +} + +/** \class AutoDiffScalar + * \brief A scalar type replacement with automatic differentiation capability + * + * \param DerivativeType the vector type used to store/represent the derivatives. The base scalar type + * as well as the number of derivatives to compute are determined from this type. + * Typical choices include, e.g., \c Vector4f for 4 derivatives, or \c VectorXf + * if the number of derivatives is not known at compile time, and/or, the number + * of derivatives is large. + * Note that DerivativeType can also be a reference (e.g., \c VectorXf&) to wrap a + * existing vector into an AutoDiffScalar. + * Finally, DerivativeType can also be any Eigen compatible expression. + * + * This class represents a scalar value while tracking its respective derivatives using Eigen's expression + * template mechanism. + * + * It supports the following list of global math function: + * - std::abs, std::sqrt, std::pow, std::exp, std::log, std::sin, std::cos, + * - internal::abs, internal::sqrt, numext::pow, internal::exp, internal::log, internal::sin, internal::cos, + * - internal::conj, internal::real, internal::imag, numext::abs2. + * + * AutoDiffScalar can be used as the scalar type of an Eigen::Matrix object. However, + * in that case, the expression template mechanism only occurs at the top Matrix level, + * while derivatives are computed right away. + * + */ + +template +class AutoDiffScalar + : public internal::auto_diff_special_op + >::Scalar, + typename NumTraits>::Scalar>::Real>::value> +{ + public: + typedef internal::auto_diff_special_op + >::Scalar, + typename NumTraits>::Scalar>::Real>::value> Base; + typedef internal::remove_all_t DerType; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real Real; + + using Base::operator+; + using Base::operator*; + + /** Default constructor without any initialization. */ + AutoDiffScalar() {} + + /** Constructs an active scalar from its \a value, + and initializes the \a nbDer derivatives such that it corresponds to the \a derNumber -th variable */ + AutoDiffScalar(const Scalar& value, int nbDer, int derNumber) + : m_value(value), m_derivatives(DerType::Zero(nbDer)) + { + m_derivatives.coeffRef(derNumber) = Scalar(1); + } + + /** Conversion from a scalar constant to an active scalar. + * The derivatives are set to zero. */ + /*explicit*/ AutoDiffScalar(const Real& value) + : m_value(value) + { + if(m_derivatives.size()>0) + m_derivatives.setZero(); + } + + /** Constructs an active scalar from its \a value and derivatives \a der */ + AutoDiffScalar(const Scalar& value, const DerType& der) + : m_value(value), m_derivatives(der) + {} + + template + AutoDiffScalar(const AutoDiffScalar& other +#ifndef EIGEN_PARSED_BY_DOXYGEN + , std::enable_if_t< + internal::is_same>::Scalar>::value + && internal::is_convertible::value , void*> = 0 +#endif + ) + : m_value(other.value()), m_derivatives(other.derivatives()) + {} + + friend std::ostream & operator << (std::ostream & s, const AutoDiffScalar& a) + { + return s << a.value(); + } + + AutoDiffScalar(const AutoDiffScalar& other) + : m_value(other.value()), m_derivatives(other.derivatives()) + {} + + template + inline AutoDiffScalar& operator=(const AutoDiffScalar& other) + { + m_value = other.value(); + m_derivatives = other.derivatives(); + return *this; + } + + inline AutoDiffScalar& operator=(const AutoDiffScalar& other) + { + m_value = other.value(); + m_derivatives = other.derivatives(); + return *this; + } + + inline AutoDiffScalar& operator=(const Scalar& other) + { + m_value = other; + if(m_derivatives.size()>0) + m_derivatives.setZero(); + return *this; + } + +// inline operator const Scalar& () const { return m_value; } +// inline operator Scalar& () { return m_value; } + + inline const Scalar& value() const { return m_value; } + inline Scalar& value() { return m_value; } + + inline const DerType& derivatives() const { return m_derivatives; } + inline DerType& derivatives() { return m_derivatives; } + + inline bool operator< (const Scalar& other) const { return m_value < other; } + inline bool operator<=(const Scalar& other) const { return m_value <= other; } + inline bool operator> (const Scalar& other) const { return m_value > other; } + inline bool operator>=(const Scalar& other) const { return m_value >= other; } + inline bool operator==(const Scalar& other) const { return m_value == other; } + inline bool operator!=(const Scalar& other) const { return m_value != other; } + + friend inline bool operator< (const Scalar& a, const AutoDiffScalar& b) { return a < b.value(); } + friend inline bool operator<=(const Scalar& a, const AutoDiffScalar& b) { return a <= b.value(); } + friend inline bool operator> (const Scalar& a, const AutoDiffScalar& b) { return a > b.value(); } + friend inline bool operator>=(const Scalar& a, const AutoDiffScalar& b) { return a >= b.value(); } + friend inline bool operator==(const Scalar& a, const AutoDiffScalar& b) { return a == b.value(); } + friend inline bool operator!=(const Scalar& a, const AutoDiffScalar& b) { return a != b.value(); } + + template inline bool operator< (const AutoDiffScalar& b) const { return m_value < b.value(); } + template inline bool operator<=(const AutoDiffScalar& b) const { return m_value <= b.value(); } + template inline bool operator> (const AutoDiffScalar& b) const { return m_value > b.value(); } + template inline bool operator>=(const AutoDiffScalar& b) const { return m_value >= b.value(); } + template inline bool operator==(const AutoDiffScalar& b) const { return m_value == b.value(); } + template inline bool operator!=(const AutoDiffScalar& b) const { return m_value != b.value(); } + + inline AutoDiffScalar operator+(const Scalar& other) const + { + return AutoDiffScalar(m_value + other, m_derivatives); + } + + friend inline AutoDiffScalar operator+(const Scalar& a, const AutoDiffScalar& b) + { + return AutoDiffScalar(a + b.value(), b.derivatives()); + } + +// inline const AutoDiffScalar operator+(const Real& other) const +// { +// return AutoDiffScalar(m_value + other, m_derivatives); +// } + +// friend inline const AutoDiffScalar operator+(const Real& a, const AutoDiffScalar& b) +// { +// return AutoDiffScalar(a + b.value(), b.derivatives()); +// } + + inline AutoDiffScalar& operator+=(const Scalar& other) + { + value() += other; + return *this; + } + + template + inline AutoDiffScalar,const DerType,const internal::remove_all_t> > + operator+(const AutoDiffScalar& other) const + { + internal::make_coherent(m_derivatives, other.derivatives()); + return AutoDiffScalar,const DerType,const internal::remove_all_t> >( + m_value + other.value(), + m_derivatives + other.derivatives()); + } + + template + inline AutoDiffScalar& + operator+=(const AutoDiffScalar& other) + { + (*this) = (*this) + other; + return *this; + } + + inline AutoDiffScalar operator-(const Scalar& b) const + { + return AutoDiffScalar(m_value - b, m_derivatives); + } + + friend inline AutoDiffScalar, const DerType> > + operator-(const Scalar& a, const AutoDiffScalar& b) + { + return AutoDiffScalar, const DerType> > + (a - b.value(), -b.derivatives()); + } + + inline AutoDiffScalar& operator-=(const Scalar& other) + { + value() -= other; + return *this; + } + + template + inline AutoDiffScalar, const DerType,const internal::remove_all_t> > + operator-(const AutoDiffScalar& other) const + { + internal::make_coherent(m_derivatives, other.derivatives()); + return AutoDiffScalar, const DerType,const internal::remove_all_t> >( + m_value - other.value(), + m_derivatives - other.derivatives()); + } + + template + inline AutoDiffScalar& + operator-=(const AutoDiffScalar& other) + { + *this = *this - other; + return *this; + } + + inline AutoDiffScalar, const DerType> > + operator-() const + { + return AutoDiffScalar, const DerType> >( + -m_value, + -m_derivatives); + } + + inline AutoDiffScalar + operator*(const Scalar& other) const + { + return MakeAutoDiffScalar(m_value * other, m_derivatives * other); + } + + friend inline AutoDiffScalar + operator*(const Scalar& other, const AutoDiffScalar& a) + { + return MakeAutoDiffScalar(a.value() * other, a.derivatives() * other); + } + +// inline const AutoDiffScalar, DerType>::Type > +// operator*(const Real& other) const +// { +// return AutoDiffScalar, DerType>::Type >( +// m_value * other, +// (m_derivatives * other)); +// } +// +// friend inline const AutoDiffScalar, DerType>::Type > +// operator*(const Real& other, const AutoDiffScalar& a) +// { +// return AutoDiffScalar, DerType>::Type >( +// a.value() * other, +// a.derivatives() * other); +// } + + inline AutoDiffScalar + operator/(const Scalar& other) const + { + return MakeAutoDiffScalar(m_value / other, (m_derivatives * (Scalar(1)/other))); + } + + friend inline AutoDiffScalar + operator/(const Scalar& other, const AutoDiffScalar& a) + { + return MakeAutoDiffScalar(other / a.value(), a.derivatives() * (Scalar(-other) / (a.value()*a.value()))); + } + +// inline const AutoDiffScalar, DerType>::Type > +// operator/(const Real& other) const +// { +// return AutoDiffScalar, DerType>::Type >( +// m_value / other, +// (m_derivatives * (Real(1)/other))); +// } +// +// friend inline const AutoDiffScalar, DerType>::Type > +// operator/(const Real& other, const AutoDiffScalar& a) +// { +// return AutoDiffScalar, DerType>::Type >( +// other / a.value(), +// a.derivatives() * (-Real(1)/other)); +// } + + template + inline AutoDiffScalar EIGEN_COMMA + const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(DerType,Scalar,product) EIGEN_COMMA + const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(internal::remove_all_t,Scalar,product) >,Scalar,product) > + operator/(const AutoDiffScalar& other) const + { + internal::make_coherent(m_derivatives, other.derivatives()); + return MakeAutoDiffScalar( + m_value / other.value(), + ((m_derivatives * other.value()) - (other.derivatives() * m_value)) + * (Scalar(1)/(other.value()*other.value()))); + } + + template + inline AutoDiffScalar, + const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(DerType,Scalar,product), + const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(internal::remove_all_t,Scalar,product) > > + operator*(const AutoDiffScalar& other) const + { + internal::make_coherent(m_derivatives, other.derivatives()); + return MakeAutoDiffScalar( + m_value * other.value(), + (m_derivatives * other.value()) + (other.derivatives() * m_value)); + } + + inline AutoDiffScalar& operator*=(const Scalar& other) + { + *this = *this * other; + return *this; + } + + template + inline AutoDiffScalar& operator*=(const AutoDiffScalar& other) + { + *this = *this * other; + return *this; + } + + inline AutoDiffScalar& operator/=(const Scalar& other) + { + *this = *this / other; + return *this; + } + + template + inline AutoDiffScalar& operator/=(const AutoDiffScalar& other) + { + *this = *this / other; + return *this; + } + + protected: + Scalar m_value; + DerType m_derivatives; + +}; + +namespace internal { + +template +struct auto_diff_special_op +// : auto_diff_scalar_op::Real, +// is_same::Real>::value> +{ + typedef remove_all_t DerType; + typedef typename traits::Scalar Scalar; + typedef typename NumTraits::Real Real; + +// typedef auto_diff_scalar_op::Real, +// is_same::Real>::value> Base; + +// using Base::operator+; +// using Base::operator+=; +// using Base::operator-; +// using Base::operator-=; +// using Base::operator*; +// using Base::operator*=; + + const AutoDiffScalar& derived() const { return *static_cast*>(this); } + AutoDiffScalar& derived() { return *static_cast*>(this); } + + + inline AutoDiffScalar operator+(const Real& other) const + { + return AutoDiffScalar(derived().value() + other, derived().derivatives()); + } + + friend inline AutoDiffScalar operator+(const Real& a, const AutoDiffScalar& b) + { + return AutoDiffScalar(a + b.value(), b.derivatives()); + } + + inline AutoDiffScalar& operator+=(const Real& other) + { + derived().value() += other; + return derived(); + } + + + inline AutoDiffScalar >, DerType>::Type > + operator*(const Real& other) const + { + return AutoDiffScalar >, DerType>::Type >( + derived().value() * other, + derived().derivatives() * other); + } + + friend inline AutoDiffScalar >, DerType>::Type > + operator*(const Real& other, const AutoDiffScalar& a) + { + return AutoDiffScalar >, DerType>::Type >( + a.value() * other, + a.derivatives() * other); + } + + inline AutoDiffScalar& operator*=(const Scalar& other) + { + *this = *this * other; + return derived(); + } +}; + +template +struct auto_diff_special_op +{ + void operator*() const; + void operator-() const; + void operator+() const; +}; + +template +void make_coherent_expression(CwiseBinaryOp xpr, const RefType &ref) +{ + make_coherent(xpr.const_cast_derived().lhs(), ref); + make_coherent(xpr.const_cast_derived().rhs(), ref); +} + +template +void make_coherent_expression(const CwiseUnaryOp &xpr, const RefType &ref) +{ + make_coherent(xpr.nestedExpression().const_cast_derived(), ref); +} + +// needed for compilation only +template +void make_coherent_expression(const CwiseNullaryOp &, const RefType &) +{} + +template +struct make_coherent_impl, B> { + typedef Matrix A; + static void run(A& a, B& b) { + if((A_Rows==Dynamic || A_Cols==Dynamic) && (a.size()==0)) + { + a.resize(b.size()); + a.setZero(); + } + else if (B::SizeAtCompileTime==Dynamic && a.size()!=0 && b.size()==0) + { + make_coherent_expression(b,a); + } + } +}; + +template +struct make_coherent_impl > { + typedef Matrix B; + static void run(A& a, B& b) { + if((B_Rows==Dynamic || B_Cols==Dynamic) && (b.size()==0)) + { + b.resize(a.size()); + b.setZero(); + } + else if (A::SizeAtCompileTime==Dynamic && b.size()!=0 && a.size()==0) + { + make_coherent_expression(a,b); + } + } +}; + +template +struct make_coherent_impl, + Matrix > { + typedef Matrix A; + typedef Matrix B; + static void run(A& a, B& b) { + if((A_Rows==Dynamic || A_Cols==Dynamic) && (a.size()==0)) + { + a.resize(b.size()); + a.setZero(); + } + else if((B_Rows==Dynamic || B_Cols==Dynamic) && (b.size()==0)) + { + b.resize(a.size()); + b.setZero(); + } + } +}; + +} // end namespace internal + +template +struct ScalarBinaryOpTraits,typename DerType::Scalar,BinOp> +{ + typedef AutoDiffScalar ReturnType; +}; + +template +struct ScalarBinaryOpTraits, BinOp> +{ + typedef AutoDiffScalar ReturnType; +}; + + +// The following is an attempt to let Eigen's known about expression template, but that's more tricky! + +// template +// struct ScalarBinaryOpTraits,AutoDiffScalar, BinOp> +// { +// enum { Defined = 1 }; +// typedef AutoDiffScalar ReturnType; +// }; +// +// template +// struct ScalarBinaryOpTraits,AutoDiffScalar, BinOp> +// { +// enum { Defined = 1 };//internal::is_same::value }; +// typedef AutoDiffScalar ReturnType; +// }; + +#define EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(FUNC,CODE) \ + template \ + inline Eigen::AutoDiffScalar< \ + EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(Eigen::internal::remove_all_t, typename Eigen::internal::traits>::Scalar, product) > \ + FUNC(const Eigen::AutoDiffScalar& x) { \ + using namespace Eigen; \ + typedef typename Eigen::internal::traits>::Scalar Scalar; \ + EIGEN_UNUSED_VARIABLE(sizeof(Scalar)); \ + CODE; \ + } + +template +struct CleanedUpDerType { + typedef AutoDiffScalar::PlainObject> type; +}; + +template +inline const AutoDiffScalar& conj(const AutoDiffScalar& x) { return x; } +template +inline const AutoDiffScalar& real(const AutoDiffScalar& x) { return x; } +template +inline typename DerType::Scalar imag(const AutoDiffScalar&) { return 0.; } +template +inline typename CleanedUpDerType::type (min)(const AutoDiffScalar& x, const T& y) { + typedef typename CleanedUpDerType::type ADS; + return (x <= y ? ADS(x) : ADS(y)); +} +template +inline typename CleanedUpDerType::type (max)(const AutoDiffScalar& x, const T& y) { + typedef typename CleanedUpDerType::type ADS; + return (x >= y ? ADS(x) : ADS(y)); +} +template +inline typename CleanedUpDerType::type (min)(const T& x, const AutoDiffScalar& y) { + typedef typename CleanedUpDerType::type ADS; + return (x < y ? ADS(x) : ADS(y)); +} +template +inline typename CleanedUpDerType::type (max)(const T& x, const AutoDiffScalar& y) { + typedef typename CleanedUpDerType::type ADS; + return (x > y ? ADS(x) : ADS(y)); +} +template +inline typename CleanedUpDerType::type (min)(const AutoDiffScalar& x, const AutoDiffScalar& y) { + return (x.value() < y.value() ? x : y); +} +template +inline typename CleanedUpDerType::type (max)(const AutoDiffScalar& x, const AutoDiffScalar& y) { + return (x.value() >= y.value() ? x : y); +} + + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(abs, + using std::abs; + return Eigen::MakeAutoDiffScalar(abs(x.value()), x.derivatives() * (x.value()<0 ? -1 : 1) );) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(abs2, + using numext::abs2; + return Eigen::MakeAutoDiffScalar(abs2(x.value()), x.derivatives() * (Scalar(2)*x.value()));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(sqrt, + using std::sqrt; + Scalar sqrtx = sqrt(x.value()); + return Eigen::MakeAutoDiffScalar(sqrtx,x.derivatives() * (Scalar(0.5) / sqrtx));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(cos, + using std::cos; + using std::sin; + return Eigen::MakeAutoDiffScalar(cos(x.value()), x.derivatives() * (-sin(x.value())));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(sin, + using std::sin; + using std::cos; + return Eigen::MakeAutoDiffScalar(sin(x.value()),x.derivatives() * cos(x.value()));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(exp, + using std::exp; + Scalar expx = exp(x.value()); + return Eigen::MakeAutoDiffScalar(expx,x.derivatives() * expx);) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(log, + using std::log; + return Eigen::MakeAutoDiffScalar(log(x.value()),x.derivatives() * (Scalar(1)/x.value()));) + +template +inline Eigen::AutoDiffScalar< +EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(internal::remove_all_t, typename internal::traits>::Scalar,product) > +pow(const Eigen::AutoDiffScalar &x, const typename internal::traits>::Scalar &y) +{ + using namespace Eigen; + using std::pow; + return Eigen::MakeAutoDiffScalar(pow(x.value(),y), x.derivatives() * (y * pow(x.value(),y-1))); +} + + +template +inline AutoDiffScalar>::Scalar,Dynamic,1> > +atan2(const AutoDiffScalar& a, const AutoDiffScalar& b) +{ + using std::atan2; + typedef typename internal::traits>::Scalar Scalar; + typedef AutoDiffScalar > PlainADS; + PlainADS ret; + ret.value() = atan2(a.value(), b.value()); + + Scalar squared_hypot = a.value() * a.value() + b.value() * b.value(); + + // if (squared_hypot==0) the derivation is undefined and the following results in a NaN: + ret.derivatives() = (a.derivatives() * b.value() - a.value() * b.derivatives()) / squared_hypot; + + return ret; +} + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(tan, + using std::tan; + using std::cos; + return Eigen::MakeAutoDiffScalar(tan(x.value()),x.derivatives() * (Scalar(1)/numext::abs2(cos(x.value()))));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(asin, + using std::sqrt; + using std::asin; + return Eigen::MakeAutoDiffScalar(asin(x.value()),x.derivatives() * (Scalar(1)/sqrt(1-numext::abs2(x.value()))));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(acos, + using std::sqrt; + using std::acos; + return Eigen::MakeAutoDiffScalar(acos(x.value()),x.derivatives() * (Scalar(-1)/sqrt(1-numext::abs2(x.value()))));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(tanh, + using std::cosh; + using std::tanh; + return Eigen::MakeAutoDiffScalar(tanh(x.value()),x.derivatives() * (Scalar(1)/numext::abs2(cosh(x.value()))));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(sinh, + using std::sinh; + using std::cosh; + return Eigen::MakeAutoDiffScalar(sinh(x.value()),x.derivatives() * cosh(x.value()));) + +EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY(cosh, + using std::sinh; + using std::cosh; + return Eigen::MakeAutoDiffScalar(cosh(x.value()),x.derivatives() * sinh(x.value()));) + +#undef EIGEN_AUTODIFF_DECLARE_GLOBAL_UNARY + +template struct NumTraits > + : NumTraits< typename NumTraits::Scalar>::Real > +{ + typedef internal::remove_all_t DerTypeCleaned; + typedef AutoDiffScalar::Real,DerTypeCleaned::RowsAtCompileTime,DerTypeCleaned::ColsAtCompileTime, + 0, DerTypeCleaned::MaxRowsAtCompileTime, DerTypeCleaned::MaxColsAtCompileTime> > Real; + typedef AutoDiffScalar NonInteger; + typedef AutoDiffScalar Nested; + typedef typename NumTraits::Literal Literal; + enum{ + RequireInitialization = 1 + }; +}; + +namespace internal { +template +struct is_identically_zero_impl> { + static inline bool run(const AutoDiffScalar& s) + { + const DerivativeType& derivatives = s.derivatives(); + for(int i=0; i +class numeric_limits > + : public numeric_limits {}; + +template +class numeric_limits > + : public numeric_limits {}; + +} // namespace std + +#endif // EIGEN_AUTODIFF_SCALAR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffVector.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffVector.h new file mode 100644 index 0000000000000000000000000000000000000000..c544422d4fe7427462aac5daf6b56b8459d742f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/AutoDiffVector.h @@ -0,0 +1,222 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_AUTODIFF_VECTOR_H +#define EIGEN_AUTODIFF_VECTOR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/* \class AutoDiffScalar + * \brief A scalar type replacement with automatic differentation capability + * + * \param DerType the vector type used to store/represent the derivatives (e.g. Vector3f) + * + * This class represents a scalar value while tracking its respective derivatives. + * + * It supports the following list of global math function: + * - std::abs, std::sqrt, std::pow, std::exp, std::log, std::sin, std::cos, + * - internal::abs, internal::sqrt, numext::pow, internal::exp, internal::log, internal::sin, internal::cos, + * - internal::conj, internal::real, internal::imag, numext::abs2. + * + * AutoDiffScalar can be used as the scalar type of an Eigen::Matrix object. However, + * in that case, the expression template mechanism only occurs at the top Matrix level, + * while derivatives are computed right away. + * + */ +template +class AutoDiffVector +{ + public: + //typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::Scalar BaseScalar; + typedef AutoDiffScalar > ActiveScalar; + typedef ActiveScalar Scalar; + typedef AutoDiffScalar CoeffType; + typedef typename JacobianType::Index Index; + + inline AutoDiffVector() {} + + inline AutoDiffVector(const ValueType& values) + : m_values(values) + { + m_jacobian.setZero(); + } + + + CoeffType operator[] (Index i) { return CoeffType(m_values[i], m_jacobian.col(i)); } + const CoeffType operator[] (Index i) const { return CoeffType(m_values[i], m_jacobian.col(i)); } + + CoeffType operator() (Index i) { return CoeffType(m_values[i], m_jacobian.col(i)); } + const CoeffType operator() (Index i) const { return CoeffType(m_values[i], m_jacobian.col(i)); } + + CoeffType coeffRef(Index i) { return CoeffType(m_values[i], m_jacobian.col(i)); } + const CoeffType coeffRef(Index i) const { return CoeffType(m_values[i], m_jacobian.col(i)); } + + Index size() const { return m_values.size(); } + + // FIXME here we could return an expression of the sum + Scalar sum() const { /*std::cerr << "sum \n\n";*/ /*std::cerr << m_jacobian.rowwise().sum() << "\n\n";*/ return Scalar(m_values.sum(), m_jacobian.rowwise().sum()); } + + + inline AutoDiffVector(const ValueType& values, const JacobianType& jac) + : m_values(values), m_jacobian(jac) + {} + + template + inline AutoDiffVector(const AutoDiffVector& other) + : m_values(other.values()), m_jacobian(other.jacobian()) + {} + + inline AutoDiffVector(const AutoDiffVector& other) + : m_values(other.values()), m_jacobian(other.jacobian()) + {} + + template + inline AutoDiffVector& operator=(const AutoDiffVector& other) + { + m_values = other.values(); + m_jacobian = other.jacobian(); + return *this; + } + + inline AutoDiffVector& operator=(const AutoDiffVector& other) + { + m_values = other.values(); + m_jacobian = other.jacobian(); + return *this; + } + + inline const ValueType& values() const { return m_values; } + inline ValueType& values() { return m_values; } + + inline const JacobianType& jacobian() const { return m_jacobian; } + inline JacobianType& jacobian() { return m_jacobian; } + + template + inline const AutoDiffVector< + typename MakeCwiseBinaryOp,ValueType,OtherValueType>::Type, + typename MakeCwiseBinaryOp,JacobianType,OtherJacobianType>::Type > + operator+(const AutoDiffVector& other) const + { + return AutoDiffVector< + typename MakeCwiseBinaryOp,ValueType,OtherValueType>::Type, + typename MakeCwiseBinaryOp,JacobianType,OtherJacobianType>::Type >( + m_values + other.values(), + m_jacobian + other.jacobian()); + } + + template + inline AutoDiffVector& + operator+=(const AutoDiffVector& other) + { + m_values += other.values(); + m_jacobian += other.jacobian(); + return *this; + } + + template + inline const AutoDiffVector< + typename MakeCwiseBinaryOp,ValueType,OtherValueType>::Type, + typename MakeCwiseBinaryOp,JacobianType,OtherJacobianType>::Type > + operator-(const AutoDiffVector& other) const + { + return AutoDiffVector< + typename MakeCwiseBinaryOp,ValueType,OtherValueType>::Type, + typename MakeCwiseBinaryOp,JacobianType,OtherJacobianType>::Type >( + m_values - other.values(), + m_jacobian - other.jacobian()); + } + + template + inline AutoDiffVector& + operator-=(const AutoDiffVector& other) + { + m_values -= other.values(); + m_jacobian -= other.jacobian(); + return *this; + } + + inline const AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type > + operator-() const + { + return AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type >( + -m_values, + -m_jacobian); + } + + inline const AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type> + operator*(const BaseScalar& other) const + { + return AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type >( + m_values * other, + m_jacobian * other); + } + + friend inline const AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type > + operator*(const Scalar& other, const AutoDiffVector& v) + { + return AutoDiffVector< + typename MakeCwiseUnaryOp, ValueType>::Type, + typename MakeCwiseUnaryOp, JacobianType>::Type >( + v.values() * other, + v.jacobian() * other); + } + +// template +// inline const AutoDiffVector< +// CwiseBinaryOp, ValueType, OtherValueType> +// CwiseBinaryOp, +// CwiseUnaryOp, JacobianType>, +// CwiseUnaryOp, OtherJacobianType> > > +// operator*(const AutoDiffVector& other) const +// { +// return AutoDiffVector< +// CwiseBinaryOp, ValueType, OtherValueType> +// CwiseBinaryOp, +// CwiseUnaryOp, JacobianType>, +// CwiseUnaryOp, OtherJacobianType> > >( +// m_values.cwise() * other.values(), +// (m_jacobian * other.values()) + (m_values * other.jacobian())); +// } + + inline AutoDiffVector& operator*=(const Scalar& other) + { + m_values *= other; + m_jacobian *= other; + return *this; + } + + template + inline AutoDiffVector& operator*=(const AutoDiffVector& other) + { + *this = *this * other; + return *this; + } + + protected: + ValueType m_values; + JacobianType m_jacobian; + +}; + +} + +#endif // EIGEN_AUTODIFF_VECTOR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..1584337c60331421a1b77e6861f3c9c97fee4c5d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/AutoDiff/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_AUTODIFF_MODULE_H +#error "Please include unsupported/Eigen/AutoDiff instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/BVAlgorithms.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/BVAlgorithms.h new file mode 100644 index 0000000000000000000000000000000000000000..7c83a5f7a4c994d97acbddca393048b048ac83a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/BVAlgorithms.h @@ -0,0 +1,295 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Ilya Baran +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BVALGORITHMS_H +#define EIGEN_BVALGORITHMS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +bool intersect_helper(const BVH &tree, Intersector &intersector, typename BVH::Index root) +{ + typedef typename BVH::Index Index; + typedef typename BVH::VolumeIterator VolIter; + typedef typename BVH::ObjectIterator ObjIter; + + VolIter vBegin = VolIter(), vEnd = VolIter(); + ObjIter oBegin = ObjIter(), oEnd = ObjIter(); + + std::vector todo(1, root); + + while(!todo.empty()) { + tree.getChildren(todo.back(), vBegin, vEnd, oBegin, oEnd); + todo.pop_back(); + + for(; vBegin != vEnd; ++vBegin) //go through child volumes + if(intersector.intersectVolume(tree.getVolume(*vBegin))) + todo.push_back(*vBegin); + + for(; oBegin != oEnd; ++oBegin) //go through child objects + if(intersector.intersectObject(*oBegin)) + return true; //intersector said to stop query + } + return false; +} +#endif //not EIGEN_PARSED_BY_DOXYGEN + +template +struct intersector_helper1 +{ + intersector_helper1(const Object2 &inStored, Intersector &in) : stored(inStored), intersector(in) {} + bool intersectVolume(const Volume1 &vol) { return intersector.intersectVolumeObject(vol, stored); } + bool intersectObject(const Object1 &obj) { return intersector.intersectObjectObject(obj, stored); } + Object2 stored; + Intersector &intersector; +private: + intersector_helper1& operator=(const intersector_helper1&); +}; + +template +struct intersector_helper2 +{ + intersector_helper2(const Object1 &inStored, Intersector &in) : stored(inStored), intersector(in) {} + bool intersectVolume(const Volume2 &vol) { return intersector.intersectObjectVolume(stored, vol); } + bool intersectObject(const Object2 &obj) { return intersector.intersectObjectObject(stored, obj); } + Object1 stored; + Intersector &intersector; +private: + intersector_helper2& operator=(const intersector_helper2&); +}; + +} // end namespace internal + +/** Given a BVH, runs the query encapsulated by \a intersector. + * The Intersector type must provide the following members: \code + bool intersectVolume(const BVH::Volume &volume) //returns true if volume intersects the query + bool intersectObject(const BVH::Object &object) //returns true if the search should terminate immediately + \endcode + */ +template +void BVIntersect(const BVH &tree, Intersector &intersector) +{ + internal::intersect_helper(tree, intersector, tree.getRootIndex()); +} + +/** Given two BVH's, runs the query on their Cartesian product encapsulated by \a intersector. + * The Intersector type must provide the following members: \code + bool intersectVolumeVolume(const BVH1::Volume &v1, const BVH2::Volume &v2) //returns true if product of volumes intersects the query + bool intersectVolumeObject(const BVH1::Volume &v1, const BVH2::Object &o2) //returns true if the volume-object product intersects the query + bool intersectObjectVolume(const BVH1::Object &o1, const BVH2::Volume &v2) //returns true if the volume-object product intersects the query + bool intersectObjectObject(const BVH1::Object &o1, const BVH2::Object &o2) //returns true if the search should terminate immediately + \endcode + */ +template +void BVIntersect(const BVH1 &tree1, const BVH2 &tree2, Intersector &intersector) //TODO: tandem descent when it makes sense +{ + typedef typename BVH1::Index Index1; + typedef typename BVH2::Index Index2; + typedef internal::intersector_helper1 Helper1; + typedef internal::intersector_helper2 Helper2; + typedef typename BVH1::VolumeIterator VolIter1; + typedef typename BVH1::ObjectIterator ObjIter1; + typedef typename BVH2::VolumeIterator VolIter2; + typedef typename BVH2::ObjectIterator ObjIter2; + + VolIter1 vBegin1 = VolIter1(), vEnd1 = VolIter1(); + ObjIter1 oBegin1 = ObjIter1(), oEnd1 = ObjIter1(); + VolIter2 vBegin2 = VolIter2(), vEnd2 = VolIter2(), vCur2 = VolIter2(); + ObjIter2 oBegin2 = ObjIter2(), oEnd2 = ObjIter2(), oCur2 = ObjIter2(); + + std::vector > todo(1, std::make_pair(tree1.getRootIndex(), tree2.getRootIndex())); + + while(!todo.empty()) { + tree1.getChildren(todo.back().first, vBegin1, vEnd1, oBegin1, oEnd1); + tree2.getChildren(todo.back().second, vBegin2, vEnd2, oBegin2, oEnd2); + todo.pop_back(); + + for(; vBegin1 != vEnd1; ++vBegin1) { //go through child volumes of first tree + const typename BVH1::Volume &vol1 = tree1.getVolume(*vBegin1); + for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree + if(intersector.intersectVolumeVolume(vol1, tree2.getVolume(*vCur2))) + todo.push_back(std::make_pair(*vBegin1, *vCur2)); + } + + for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree + Helper1 helper(*oCur2, intersector); + if(internal::intersect_helper(tree1, helper, *vBegin1)) + return; //intersector said to stop query + } + } + + for(; oBegin1 != oEnd1; ++oBegin1) { //go through child objects of first tree + for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree + Helper2 helper(*oBegin1, intersector); + if(internal::intersect_helper(tree2, helper, *vCur2)) + return; //intersector said to stop query + } + + for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree + if(intersector.intersectObjectObject(*oBegin1, *oCur2)) + return; //intersector said to stop query + } + } + } +} + +namespace internal { + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +typename Minimizer::Scalar minimize_helper(const BVH &tree, Minimizer &minimizer, typename BVH::Index root, typename Minimizer::Scalar minimum) +{ + typedef typename Minimizer::Scalar Scalar; + typedef typename BVH::Index Index; + typedef std::pair QueueElement; //first element is priority + typedef typename BVH::VolumeIterator VolIter; + typedef typename BVH::ObjectIterator ObjIter; + + VolIter vBegin = VolIter(), vEnd = VolIter(); + ObjIter oBegin = ObjIter(), oEnd = ObjIter(); + std::priority_queue, std::greater > todo; //smallest is at the top + + todo.push(std::make_pair(Scalar(), root)); + + while(!todo.empty()) { + tree.getChildren(todo.top().second, vBegin, vEnd, oBegin, oEnd); + todo.pop(); + + for(; oBegin != oEnd; ++oBegin) //go through child objects + minimum = (std::min)(minimum, minimizer.minimumOnObject(*oBegin)); + + for(; vBegin != vEnd; ++vBegin) { //go through child volumes + Scalar val = minimizer.minimumOnVolume(tree.getVolume(*vBegin)); + if(val < minimum) + todo.push(std::make_pair(val, *vBegin)); + } + } + + return minimum; +} +#endif //not EIGEN_PARSED_BY_DOXYGEN + + +template +struct minimizer_helper1 +{ + typedef typename Minimizer::Scalar Scalar; + minimizer_helper1(const Object2 &inStored, Minimizer &m) : stored(inStored), minimizer(m) {} + Scalar minimumOnVolume(const Volume1 &vol) { return minimizer.minimumOnVolumeObject(vol, stored); } + Scalar minimumOnObject(const Object1 &obj) { return minimizer.minimumOnObjectObject(obj, stored); } + Object2 stored; + Minimizer &minimizer; +private: + minimizer_helper1& operator=(const minimizer_helper1&); +}; + +template +struct minimizer_helper2 +{ + typedef typename Minimizer::Scalar Scalar; + minimizer_helper2(const Object1 &inStored, Minimizer &m) : stored(inStored), minimizer(m) {} + Scalar minimumOnVolume(const Volume2 &vol) { return minimizer.minimumOnObjectVolume(stored, vol); } + Scalar minimumOnObject(const Object2 &obj) { return minimizer.minimumOnObjectObject(stored, obj); } + Object1 stored; + Minimizer &minimizer; +private: + minimizer_helper2& operator=(const minimizer_helper2&); +}; + +} // end namespace internal + +/** Given a BVH, runs the query encapsulated by \a minimizer. + * \returns the minimum value. + * The Minimizer type must provide the following members: \code + typedef Scalar //the numeric type of what is being minimized--not necessarily the Scalar type of the BVH (if it has one) + Scalar minimumOnVolume(const BVH::Volume &volume) + Scalar minimumOnObject(const BVH::Object &object) + \endcode + */ +template +typename Minimizer::Scalar BVMinimize(const BVH &tree, Minimizer &minimizer) +{ + return internal::minimize_helper(tree, minimizer, tree.getRootIndex(), (std::numeric_limits::max)()); +} + +/** Given two BVH's, runs the query on their cartesian product encapsulated by \a minimizer. + * \returns the minimum value. + * The Minimizer type must provide the following members: \code + typedef Scalar //the numeric type of what is being minimized--not necessarily the Scalar type of the BVH (if it has one) + Scalar minimumOnVolumeVolume(const BVH1::Volume &v1, const BVH2::Volume &v2) + Scalar minimumOnVolumeObject(const BVH1::Volume &v1, const BVH2::Object &o2) + Scalar minimumOnObjectVolume(const BVH1::Object &o1, const BVH2::Volume &v2) + Scalar minimumOnObjectObject(const BVH1::Object &o1, const BVH2::Object &o2) + \endcode + */ +template +typename Minimizer::Scalar BVMinimize(const BVH1 &tree1, const BVH2 &tree2, Minimizer &minimizer) +{ + typedef typename Minimizer::Scalar Scalar; + typedef typename BVH1::Index Index1; + typedef typename BVH2::Index Index2; + typedef internal::minimizer_helper1 Helper1; + typedef internal::minimizer_helper2 Helper2; + typedef std::pair > QueueElement; //first element is priority + typedef typename BVH1::VolumeIterator VolIter1; + typedef typename BVH1::ObjectIterator ObjIter1; + typedef typename BVH2::VolumeIterator VolIter2; + typedef typename BVH2::ObjectIterator ObjIter2; + + VolIter1 vBegin1 = VolIter1(), vEnd1 = VolIter1(); + ObjIter1 oBegin1 = ObjIter1(), oEnd1 = ObjIter1(); + VolIter2 vBegin2 = VolIter2(), vEnd2 = VolIter2(), vCur2 = VolIter2(); + ObjIter2 oBegin2 = ObjIter2(), oEnd2 = ObjIter2(), oCur2 = ObjIter2(); + std::priority_queue, std::greater > todo; //smallest is at the top + + Scalar minimum = (std::numeric_limits::max)(); + todo.push(std::make_pair(Scalar(), std::make_pair(tree1.getRootIndex(), tree2.getRootIndex()))); + + while(!todo.empty()) { + tree1.getChildren(todo.top().second.first, vBegin1, vEnd1, oBegin1, oEnd1); + tree2.getChildren(todo.top().second.second, vBegin2, vEnd2, oBegin2, oEnd2); + todo.pop(); + + for(; oBegin1 != oEnd1; ++oBegin1) { //go through child objects of first tree + for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree + minimum = (std::min)(minimum, minimizer.minimumOnObjectObject(*oBegin1, *oCur2)); + } + + for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree + Helper2 helper(*oBegin1, minimizer); + minimum = (std::min)(minimum, internal::minimize_helper(tree2, helper, *vCur2, minimum)); + } + } + + for(; vBegin1 != vEnd1; ++vBegin1) { //go through child volumes of first tree + const typename BVH1::Volume &vol1 = tree1.getVolume(*vBegin1); + + for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree + Helper1 helper(*oCur2, minimizer); + minimum = (std::min)(minimum, internal::minimize_helper(tree1, helper, *vBegin1, minimum)); + } + + for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree + Scalar val = minimizer.minimumOnVolumeVolume(vol1, tree2.getVolume(*vCur2)); + if(val < minimum) + todo.push(std::make_pair(val, std::make_pair(*vBegin1, *vCur2))); + } + } + } + return minimum; +} + +} // end namespace Eigen + +#endif // EIGEN_BVALGORITHMS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..7aade9b027f584e4ba66161ebae541a8f5e68374 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_BVH_MODULE_H +#error "Please include unsupported/Eigen/BVH instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/KdBVH.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/KdBVH.h new file mode 100644 index 0000000000000000000000000000000000000000..e7d668403b5850e97de2dbf00dddbf752ef890da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/BVH/KdBVH.h @@ -0,0 +1,225 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Ilya Baran +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef KDBVH_H_INCLUDED +#define KDBVH_H_INCLUDED + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +//internal pair class for the BVH--used instead of std::pair because of alignment +template +struct vector_int_pair +{ +EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar, Dim) + typedef Matrix VectorType; + + vector_int_pair(const VectorType &v, int i) : first(v), second(i) {} + + VectorType first; + int second; +}; + +//these templates help the tree initializer get the bounding boxes either from a provided +//iterator range or using bounding_box in a unified way +template +struct get_boxes_helper { + void operator()(const ObjectList &objects, BoxIter boxBegin, BoxIter boxEnd, VolumeList &outBoxes) + { + outBoxes.insert(outBoxes.end(), boxBegin, boxEnd); + eigen_assert(outBoxes.size() == objects.size()); + EIGEN_ONLY_USED_FOR_DEBUG(objects); + } +}; + +template +struct get_boxes_helper { + void operator()(const ObjectList &objects, int, int, VolumeList &outBoxes) + { + outBoxes.reserve(objects.size()); + for(int i = 0; i < (int)objects.size(); ++i) + outBoxes.push_back(bounding_box(objects[i])); + } +}; + +} // end namespace internal + + +/** \class KdBVH + * \brief A simple bounding volume hierarchy based on AlignedBox + * + * \param Scalar_ The underlying scalar type of the bounding boxes + * \param Dim_ The dimension of the space in which the hierarchy lives + * \param _Object The object type that lives in the hierarchy. It must have value semantics. Either bounding_box(_Object) must + * be defined and return an AlignedBox or bounding boxes must be provided to the tree initializer. + * + * This class provides a simple (as opposed to optimized) implementation of a bounding volume hierarchy analogous to a Kd-tree. + * Given a sequence of objects, it computes their bounding boxes, constructs a Kd-tree of their centers + * and builds a BVH with the structure of that Kd-tree. When the elements of the tree are too expensive to be copied around, + * it is useful for _Object to be a pointer. + */ +template class KdBVH +{ +public: + enum { Dim = Dim_ }; + typedef _Object Object; + typedef std::vector > ObjectList; + typedef Scalar_ Scalar; + typedef AlignedBox Volume; + typedef std::vector > VolumeList; + typedef int Index; + typedef const int *VolumeIterator; //the iterators are just pointers into the tree's vectors + typedef const Object *ObjectIterator; + + KdBVH() {} + + /** Given an iterator range over \a Object references, constructs the BVH. Requires that bounding_box(Object) return a Volume. */ + template KdBVH(Iter begin, Iter end) { init(begin, end, 0, 0); } //int is recognized by init as not being an iterator type + + /** Given an iterator range over \a Object references and an iterator range over their bounding boxes, constructs the BVH */ + template KdBVH(OIter begin, OIter end, BIter boxBegin, BIter boxEnd) { init(begin, end, boxBegin, boxEnd); } + + /** Given an iterator range over \a Object references, constructs the BVH, overwriting whatever is in there currently. + * Requires that bounding_box(Object) return a Volume. */ + template void init(Iter begin, Iter end) { init(begin, end, 0, 0); } + + /** Given an iterator range over \a Object references and an iterator range over their bounding boxes, + * constructs the BVH, overwriting whatever is in there currently. */ + template void init(OIter begin, OIter end, BIter boxBegin, BIter boxEnd) + { + objects.clear(); + boxes.clear(); + children.clear(); + + objects.insert(objects.end(), begin, end); + int n = static_cast(objects.size()); + + if(n < 2) + return; //if we have at most one object, we don't need any internal nodes + + VolumeList objBoxes; + VIPairList objCenters; + + //compute the bounding boxes depending on BIter type + internal::get_boxes_helper()(objects, boxBegin, boxEnd, objBoxes); + + objCenters.reserve(n); + boxes.reserve(n - 1); + children.reserve(2 * n - 2); + + for(int i = 0; i < n; ++i) + objCenters.push_back(VIPair(objBoxes[i].center(), i)); + + build(objCenters, 0, n, objBoxes, 0); //the recursive part of the algorithm + + ObjectList tmp(n); + tmp.swap(objects); + for(int i = 0; i < n; ++i) + objects[i] = tmp[objCenters[i].second]; + } + + /** \returns the index of the root of the hierarchy */ + inline Index getRootIndex() const { return (int)boxes.size() - 1; } + + /** Given an \a index of a node, on exit, \a outVBegin and \a outVEnd range over the indices of the volume children of the node + * and \a outOBegin and \a outOEnd range over the object children of the node */ + EIGEN_STRONG_INLINE void getChildren(Index index, VolumeIterator &outVBegin, VolumeIterator &outVEnd, + ObjectIterator &outOBegin, ObjectIterator &outOEnd) const + { //inlining this function should open lots of optimization opportunities to the compiler + if(index < 0) { + outVBegin = outVEnd; + if(!objects.empty()) + outOBegin = &(objects[0]); + outOEnd = outOBegin + objects.size(); //output all objects--necessary when the tree has only one object + return; + } + + int numBoxes = static_cast(boxes.size()); + + int idx = index * 2; + if(children[idx + 1] < numBoxes) { //second index is always bigger + outVBegin = &(children[idx]); + outVEnd = outVBegin + 2; + outOBegin = outOEnd; + } + else if(children[idx] >= numBoxes) { //if both children are objects + outVBegin = outVEnd; + outOBegin = &(objects[children[idx] - numBoxes]); + outOEnd = outOBegin + 2; + } else { //if the first child is a volume and the second is an object + outVBegin = &(children[idx]); + outVEnd = outVBegin + 1; + outOBegin = &(objects[children[idx + 1] - numBoxes]); + outOEnd = outOBegin + 1; + } + } + + /** \returns the bounding box of the node at \a index */ + inline const Volume &getVolume(Index index) const + { + return boxes[index]; + } + +private: + typedef internal::vector_int_pair VIPair; + typedef std::vector > VIPairList; + typedef Matrix VectorType; + struct VectorComparator //compares vectors, or more specifically, VIPairs along a particular dimension + { + VectorComparator(int inDim) : dim(inDim) {} + inline bool operator()(const VIPair &v1, const VIPair &v2) const { return v1.first[dim] < v2.first[dim]; } + int dim; + }; + + //Build the part of the tree between objects[from] and objects[to] (not including objects[to]). + //This routine partitions the objCenters in [from, to) along the dimension dim, recursively constructs + //the two halves, and adds their parent node. TODO: a cache-friendlier layout + void build(VIPairList &objCenters, int from, int to, const VolumeList &objBoxes, int dim) + { + eigen_assert(to - from > 1); + if(to - from == 2) { + boxes.push_back(objBoxes[objCenters[from].second].merged(objBoxes[objCenters[from + 1].second])); + children.push_back(from + (int)objects.size() - 1); //there are objects.size() - 1 tree nodes + children.push_back(from + (int)objects.size()); + } + else if(to - from == 3) { + int mid = from + 2; + std::nth_element(objCenters.begin() + from, objCenters.begin() + mid, + objCenters.begin() + to, VectorComparator(dim)); //partition + build(objCenters, from, mid, objBoxes, (dim + 1) % Dim); + int idx1 = (int)boxes.size() - 1; + boxes.push_back(boxes[idx1].merged(objBoxes[objCenters[mid].second])); + children.push_back(idx1); + children.push_back(mid + (int)objects.size() - 1); + } + else { + int mid = from + (to - from) / 2; + nth_element(objCenters.begin() + from, objCenters.begin() + mid, + objCenters.begin() + to, VectorComparator(dim)); //partition + build(objCenters, from, mid, objBoxes, (dim + 1) % Dim); + int idx1 = (int)boxes.size() - 1; + build(objCenters, mid, to, objBoxes, (dim + 1) % Dim); + int idx2 = (int)boxes.size() - 1; + boxes.push_back(boxes[idx1].merged(boxes[idx2])); + children.push_back(idx1); + children.push_back(idx2); + } + } + + std::vector children; //children of x are children[2x] and children[2x+1], indices bigger than boxes.size() index into objects. + VolumeList boxes; + ObjectList objects; +}; + +} // end namespace Eigen + +#endif //KDBVH_H_INCLUDED diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/ArpackSelfAdjointEigenSolver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/ArpackSelfAdjointEigenSolver.h new file mode 100644 index 0000000000000000000000000000000000000000..b74449f356812da7e26555c346d1370bf940c3d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/ArpackSelfAdjointEigenSolver.h @@ -0,0 +1,792 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 David Harmon +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ARPACKGENERALIZEDSELFADJOINTEIGENSOLVER_H +#define EIGEN_ARPACKGENERALIZEDSELFADJOINTEIGENSOLVER_H + +#include "../../../../Eigen/Dense" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + template struct arpack_wrapper; + template struct OP; +} + + + +template, bool BisSPD=false> +class ArpackGeneralizedSelfAdjointEigenSolver +{ +public: + //typedef typename MatrixSolver::MatrixType MatrixType; + + /** \brief Scalar type for matrices of type \p MatrixType. */ + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::Index Index; + + /** \brief Real scalar type for \p MatrixType. + * + * This is just \c Scalar if #Scalar is real (e.g., \c float or + * \c Scalar), and the type of the real part of \c Scalar if #Scalar is + * complex. + */ + typedef typename NumTraits::Real RealScalar; + + /** \brief Type for vector of eigenvalues as returned by eigenvalues(). + * + * This is a column vector with entries of type #RealScalar. + * The length of the vector is the size of \p nbrEigenvalues. + */ + typedef typename internal::plain_col_type::type RealVectorType; + + /** \brief Default constructor. + * + * The default constructor is for cases in which the user intends to + * perform decompositions via compute(). + * + */ + ArpackGeneralizedSelfAdjointEigenSolver() + : m_eivec(), + m_eivalues(), + m_isInitialized(false), + m_eigenvectorsOk(false), + m_nbrConverged(0), + m_nbrIterations(0) + { } + + /** \brief Constructor; computes generalized eigenvalues of given matrix with respect to another matrix. + * + * \param[in] A Self-adjoint matrix whose eigenvalues / eigenvectors will + * computed. By default, the upper triangular part is used, but can be changed + * through the template parameter. + * \param[in] B Self-adjoint matrix for the generalized eigenvalue problem. + * \param[in] nbrEigenvalues The number of eigenvalues / eigenvectors to compute. + * Must be less than the size of the input matrix, or an error is returned. + * \param[in] eigs_sigma String containing either "LM", "SM", "LA", or "SA", with + * respective meanings to find the largest magnitude , smallest magnitude, + * largest algebraic, or smallest algebraic eigenvalues. Alternatively, this + * value can contain floating point value in string form, in which case the + * eigenvalues closest to this value will be found. + * \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly. + * \param[in] tol What tolerance to find the eigenvalues to. Default is 0, which + * means machine precision. + * + * This constructor calls compute(const MatrixType&, const MatrixType&, Index, string, int, RealScalar) + * to compute the eigenvalues of the matrix \p A with respect to \p B. The eigenvectors are computed if + * \p options equals #ComputeEigenvectors. + * + */ + ArpackGeneralizedSelfAdjointEigenSolver(const MatrixType& A, const MatrixType& B, + Index nbrEigenvalues, std::string eigs_sigma="LM", + int options=ComputeEigenvectors, RealScalar tol=0.0) + : m_eivec(), + m_eivalues(), + m_isInitialized(false), + m_eigenvectorsOk(false), + m_nbrConverged(0), + m_nbrIterations(0) + { + compute(A, B, nbrEigenvalues, eigs_sigma, options, tol); + } + + /** \brief Constructor; computes eigenvalues of given matrix. + * + * \param[in] A Self-adjoint matrix whose eigenvalues / eigenvectors will + * computed. By default, the upper triangular part is used, but can be changed + * through the template parameter. + * \param[in] nbrEigenvalues The number of eigenvalues / eigenvectors to compute. + * Must be less than the size of the input matrix, or an error is returned. + * \param[in] eigs_sigma String containing either "LM", "SM", "LA", or "SA", with + * respective meanings to find the largest magnitude , smallest magnitude, + * largest algebraic, or smallest algebraic eigenvalues. Alternatively, this + * value can contain floating point value in string form, in which case the + * eigenvalues closest to this value will be found. + * \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly. + * \param[in] tol What tolerance to find the eigenvalues to. Default is 0, which + * means machine precision. + * + * This constructor calls compute(const MatrixType&, Index, string, int, RealScalar) + * to compute the eigenvalues of the matrix \p A. The eigenvectors are computed if + * \p options equals #ComputeEigenvectors. + * + */ + + ArpackGeneralizedSelfAdjointEigenSolver(const MatrixType& A, + Index nbrEigenvalues, std::string eigs_sigma="LM", + int options=ComputeEigenvectors, RealScalar tol=0.0) + : m_eivec(), + m_eivalues(), + m_isInitialized(false), + m_eigenvectorsOk(false), + m_nbrConverged(0), + m_nbrIterations(0) + { + compute(A, nbrEigenvalues, eigs_sigma, options, tol); + } + + + /** \brief Computes generalized eigenvalues / eigenvectors of given matrix using the external ARPACK library. + * + * \param[in] A Selfadjoint matrix whose eigendecomposition is to be computed. + * \param[in] B Selfadjoint matrix for generalized eigenvalues. + * \param[in] nbrEigenvalues The number of eigenvalues / eigenvectors to compute. + * Must be less than the size of the input matrix, or an error is returned. + * \param[in] eigs_sigma String containing either "LM", "SM", "LA", or "SA", with + * respective meanings to find the largest magnitude , smallest magnitude, + * largest algebraic, or smallest algebraic eigenvalues. Alternatively, this + * value can contain floating point value in string form, in which case the + * eigenvalues closest to this value will be found. + * \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly. + * \param[in] tol What tolerance to find the eigenvalues to. Default is 0, which + * means machine precision. + * + * \returns Reference to \c *this + * + * This function computes the generalized eigenvalues of \p A with respect to \p B using ARPACK. The eigenvalues() + * function can be used to retrieve them. If \p options equals #ComputeEigenvectors, + * then the eigenvectors are also computed and can be retrieved by + * calling eigenvectors(). + * + */ + ArpackGeneralizedSelfAdjointEigenSolver& compute(const MatrixType& A, const MatrixType& B, + Index nbrEigenvalues, std::string eigs_sigma="LM", + int options=ComputeEigenvectors, RealScalar tol=0.0); + + /** \brief Computes eigenvalues / eigenvectors of given matrix using the external ARPACK library. + * + * \param[in] A Selfadjoint matrix whose eigendecomposition is to be computed. + * \param[in] nbrEigenvalues The number of eigenvalues / eigenvectors to compute. + * Must be less than the size of the input matrix, or an error is returned. + * \param[in] eigs_sigma String containing either "LM", "SM", "LA", or "SA", with + * respective meanings to find the largest magnitude , smallest magnitude, + * largest algebraic, or smallest algebraic eigenvalues. Alternatively, this + * value can contain floating point value in string form, in which case the + * eigenvalues closest to this value will be found. + * \param[in] options Can be #ComputeEigenvectors (default) or #EigenvaluesOnly. + * \param[in] tol What tolerance to find the eigenvalues to. Default is 0, which + * means machine precision. + * + * \returns Reference to \c *this + * + * This function computes the eigenvalues of \p A using ARPACK. The eigenvalues() + * function can be used to retrieve them. If \p options equals #ComputeEigenvectors, + * then the eigenvectors are also computed and can be retrieved by + * calling eigenvectors(). + * + */ + ArpackGeneralizedSelfAdjointEigenSolver& compute(const MatrixType& A, + Index nbrEigenvalues, std::string eigs_sigma="LM", + int options=ComputeEigenvectors, RealScalar tol=0.0); + + + /** \brief Returns the eigenvectors of given matrix. + * + * \returns A const reference to the matrix whose columns are the eigenvectors. + * + * \pre The eigenvectors have been computed before. + * + * Column \f$ k \f$ of the returned matrix is an eigenvector corresponding + * to eigenvalue number \f$ k \f$ as returned by eigenvalues(). The + * eigenvectors are normalized to have (Euclidean) norm equal to one. If + * this object was used to solve the eigenproblem for the selfadjoint + * matrix \f$ A \f$, then the matrix returned by this function is the + * matrix \f$ V \f$ in the eigendecomposition \f$ A V = D V \f$. + * For the generalized eigenproblem, the matrix returned is the solution \f$ A V = D B V \f$ + * + * Example: \include SelfAdjointEigenSolver_eigenvectors.cpp + * Output: \verbinclude SelfAdjointEigenSolver_eigenvectors.out + * + * \sa eigenvalues() + */ + const Matrix& eigenvectors() const + { + eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized."); + eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues."); + return m_eivec; + } + + /** \brief Returns the eigenvalues of given matrix. + * + * \returns A const reference to the column vector containing the eigenvalues. + * + * \pre The eigenvalues have been computed before. + * + * The eigenvalues are repeated according to their algebraic multiplicity, + * so there are as many eigenvalues as rows in the matrix. The eigenvalues + * are sorted in increasing order. + * + * Example: \include SelfAdjointEigenSolver_eigenvalues.cpp + * Output: \verbinclude SelfAdjointEigenSolver_eigenvalues.out + * + * \sa eigenvectors(), MatrixBase::eigenvalues() + */ + const Matrix& eigenvalues() const + { + eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized."); + return m_eivalues; + } + + /** \brief Computes the positive-definite square root of the matrix. + * + * \returns the positive-definite square root of the matrix + * + * \pre The eigenvalues and eigenvectors of a positive-definite matrix + * have been computed before. + * + * The square root of a positive-definite matrix \f$ A \f$ is the + * positive-definite matrix whose square equals \f$ A \f$. This function + * uses the eigendecomposition \f$ A = V D V^{-1} \f$ to compute the + * square root as \f$ A^{1/2} = V D^{1/2} V^{-1} \f$. + * + * Example: \include SelfAdjointEigenSolver_operatorSqrt.cpp + * Output: \verbinclude SelfAdjointEigenSolver_operatorSqrt.out + * + * \sa operatorInverseSqrt(), + * \ref MatrixFunctions_Module "MatrixFunctions Module" + */ + Matrix operatorSqrt() const + { + eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized."); + eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues."); + return m_eivec * m_eivalues.cwiseSqrt().asDiagonal() * m_eivec.adjoint(); + } + + /** \brief Computes the inverse square root of the matrix. + * + * \returns the inverse positive-definite square root of the matrix + * + * \pre The eigenvalues and eigenvectors of a positive-definite matrix + * have been computed before. + * + * This function uses the eigendecomposition \f$ A = V D V^{-1} \f$ to + * compute the inverse square root as \f$ V D^{-1/2} V^{-1} \f$. This is + * cheaper than first computing the square root with operatorSqrt() and + * then its inverse with MatrixBase::inverse(). + * + * Example: \include SelfAdjointEigenSolver_operatorInverseSqrt.cpp + * Output: \verbinclude SelfAdjointEigenSolver_operatorInverseSqrt.out + * + * \sa operatorSqrt(), MatrixBase::inverse(), + * \ref MatrixFunctions_Module "MatrixFunctions Module" + */ + Matrix operatorInverseSqrt() const + { + eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized."); + eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues."); + return m_eivec * m_eivalues.cwiseInverse().cwiseSqrt().asDiagonal() * m_eivec.adjoint(); + } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was successful, \c NoConvergence otherwise. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "ArpackGeneralizedSelfAdjointEigenSolver is not initialized."); + return m_info; + } + + size_t getNbrConvergedEigenValues() const + { return m_nbrConverged; } + + size_t getNbrIterations() const + { return m_nbrIterations; } + +protected: + Matrix m_eivec; + Matrix m_eivalues; + ComputationInfo m_info; + bool m_isInitialized; + bool m_eigenvectorsOk; + + size_t m_nbrConverged; + size_t m_nbrIterations; +}; + + + + + +template +ArpackGeneralizedSelfAdjointEigenSolver& + ArpackGeneralizedSelfAdjointEigenSolver +::compute(const MatrixType& A, Index nbrEigenvalues, + std::string eigs_sigma, int options, RealScalar tol) +{ + MatrixType B(0,0); + compute(A, B, nbrEigenvalues, eigs_sigma, options, tol); + + return *this; +} + + +template +ArpackGeneralizedSelfAdjointEigenSolver& + ArpackGeneralizedSelfAdjointEigenSolver +::compute(const MatrixType& A, const MatrixType& B, Index nbrEigenvalues, + std::string eigs_sigma, int options, RealScalar tol) +{ + eigen_assert(A.cols() == A.rows()); + eigen_assert(B.cols() == B.rows()); + eigen_assert(B.rows() == 0 || A.cols() == B.rows()); + eigen_assert((options &~ (EigVecMask | GenEigMask)) == 0 + && (options & EigVecMask) != EigVecMask + && "invalid option parameter"); + + bool isBempty = (B.rows() == 0) || (B.cols() == 0); + + // For clarity, all parameters match their ARPACK name + // + // Always 0 on the first call + // + int ido = 0; + + int n = (int)A.cols(); + + // User options: "LA", "SA", "SM", "LM", "BE" + // + char whch[3] = "LM"; + + // Specifies the shift if iparam[6] = { 3, 4, 5 }, not used if iparam[6] = { 1, 2 } + // + RealScalar sigma = 0.0; + + if (eigs_sigma.length() >= 2 && isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1])) + { + eigs_sigma[0] = toupper(eigs_sigma[0]); + eigs_sigma[1] = toupper(eigs_sigma[1]); + + // In the following special case we're going to invert the problem, since solving + // for larger magnitude is much much faster + // i.e., if 'SM' is specified, we're going to really use 'LM', the default + // + if (eigs_sigma.substr(0,2) != "SM") + { + whch[0] = eigs_sigma[0]; + whch[1] = eigs_sigma[1]; + } + } + else + { + eigen_assert(false && "Specifying clustered eigenvalues is not yet supported!"); + + // If it's not scalar values, then the user may be explicitly + // specifying the sigma value to cluster the evs around + // + sigma = atof(eigs_sigma.c_str()); + + // If atof fails, it returns 0.0, which is a fine default + // + } + + // "I" means normal eigenvalue problem, "G" means generalized + // + char bmat[2] = "I"; + if (eigs_sigma.substr(0,2) == "SM" || !(isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1])) || (!isBempty && !BisSPD)) + bmat[0] = 'G'; + + // Now we determine the mode to use + // + int mode = (bmat[0] == 'G') + 1; + if (eigs_sigma.substr(0,2) == "SM" || !(isalpha(eigs_sigma[0]) && isalpha(eigs_sigma[1]))) + { + // We're going to use shift-and-invert mode, and basically find + // the largest eigenvalues of the inverse operator + // + mode = 3; + } + + // The user-specified number of eigenvalues/vectors to compute + // + int nev = (int)nbrEigenvalues; + + // Allocate space for ARPACK to store the residual + // + Scalar *resid = new Scalar[n]; + + // Number of Lanczos vectors, must satisfy nev < ncv <= n + // Note that this indicates that nev != n, and we cannot compute + // all eigenvalues of a mtrix + // + int ncv = std::min(std::max(2*nev, 20), n); + + // The working n x ncv matrix, also store the final eigenvectors (if computed) + // + Scalar *v = new Scalar[n*ncv]; + int ldv = n; + + // Working space + // + Scalar *workd = new Scalar[3*n]; + int lworkl = ncv*ncv+8*ncv; // Must be at least this length + Scalar *workl = new Scalar[lworkl]; + + int *iparam= new int[11]; + iparam[0] = 1; // 1 means we let ARPACK perform the shifts, 0 means we'd have to do it + iparam[2] = std::max(300, (int)std::ceil(2*n/std::max(ncv,1))); + iparam[6] = mode; // The mode, 1 is standard ev problem, 2 for generalized ev, 3 for shift-and-invert + + // Used during reverse communicate to notify where arrays start + // + int *ipntr = new int[11]; + + // Error codes are returned in here, initial value of 0 indicates a random initial + // residual vector is used, any other values means resid contains the initial residual + // vector, possibly from a previous run + // + int info = 0; + + Scalar scale = 1.0; + //if (!isBempty) + //{ + //Scalar scale = B.norm() / std::sqrt(n); + //scale = std::pow(2, std::floor(std::log(scale+1))); + ////M /= scale; + //for (size_t i=0; i<(size_t)B.outerSize(); i++) + // for (typename MatrixType::InnerIterator it(B, i); it; ++it) + // it.valueRef() /= scale; + //} + + MatrixSolver OP; + if (mode == 1 || mode == 2) + { + if (!isBempty) + OP.compute(B); + } + else if (mode == 3) + { + if (sigma == 0.0) + { + OP.compute(A); + } + else + { + // Note: We will never enter here because sigma must be 0.0 + // + if (isBempty) + { + MatrixType AminusSigmaB(A); + for (Index i=0; i::saupd(&ido, bmat, &n, whch, &nev, &tol, resid, + &ncv, v, &ldv, iparam, ipntr, workd, workl, + &lworkl, &info); + + if (ido == -1 || ido == 1) + { + Scalar *in = workd + ipntr[0] - 1; + Scalar *out = workd + ipntr[1] - 1; + + if (ido == 1 && mode != 2) + { + Scalar *out2 = workd + ipntr[2] - 1; + if (isBempty || mode == 1) + Matrix::Map(out2, n) = Matrix::Map(in, n); + else + Matrix::Map(out2, n) = B * Matrix::Map(in, n); + + in = workd + ipntr[2] - 1; + } + + if (mode == 1) + { + if (isBempty) + { + // OP = A + // + Matrix::Map(out, n) = A * Matrix::Map(in, n); + } + else + { + // OP = L^{-1}AL^{-T} + // + internal::OP::applyOP(OP, A, n, in, out); + } + } + else if (mode == 2) + { + if (ido == 1) + Matrix::Map(in, n) = A * Matrix::Map(in, n); + + // OP = B^{-1} A + // + Matrix::Map(out, n) = OP.solve(Matrix::Map(in, n)); + } + else if (mode == 3) + { + // OP = (A-\sigmaB)B (\sigma could be 0, and B could be I) + // The B * in is already computed and stored at in if ido == 1 + // + if (ido == 1 || isBempty) + Matrix::Map(out, n) = OP.solve(Matrix::Map(in, n)); + else + Matrix::Map(out, n) = OP.solve(B * Matrix::Map(in, n)); + } + } + else if (ido == 2) + { + Scalar *in = workd + ipntr[0] - 1; + Scalar *out = workd + ipntr[1] - 1; + + if (isBempty || mode == 1) + Matrix::Map(out, n) = Matrix::Map(in, n); + else + Matrix::Map(out, n) = B * Matrix::Map(in, n); + } + } while (ido != 99); + + if (info == 1) + m_info = NoConvergence; + else if (info == 3) + m_info = NumericalIssue; + else if (info < 0) + m_info = InvalidInput; + else if (info != 0) + eigen_assert(false && "Unknown ARPACK return value!"); + else + { + // Do we compute eigenvectors or not? + // + int rvec = (options & ComputeEigenvectors) == ComputeEigenvectors; + + // "A" means "All", use "S" to choose specific eigenvalues (not yet supported in ARPACK)) + // + char howmny[2] = "A"; + + // if howmny == "S", specifies the eigenvalues to compute (not implemented in ARPACK) + // + int *select = new int[ncv]; + + // Final eigenvalues + // + m_eivalues.resize(nev, 1); + + internal::arpack_wrapper::seupd(&rvec, howmny, select, m_eivalues.data(), v, &ldv, + &sigma, bmat, &n, whch, &nev, &tol, resid, &ncv, + v, &ldv, iparam, ipntr, workd, workl, &lworkl, &info); + + if (info == -14) + m_info = NoConvergence; + else if (info != 0) + m_info = InvalidInput; + else + { + if (rvec) + { + m_eivec.resize(A.rows(), nev); + for (int i=0; i::project(OP, n, nev, m_eivec.data()); + + m_eigenvectorsOk = true; + } + + m_nbrIterations = iparam[2]; + m_nbrConverged = iparam[4]; + + m_info = Success; + } + + delete[] select; + } + + delete[] v; + delete[] iparam; + delete[] ipntr; + delete[] workd; + delete[] workl; + delete[] resid; + + m_isInitialized = true; + + return *this; +} + + +// Single precision +// +extern "C" void ssaupd_(int *ido, char *bmat, int *n, char *which, + int *nev, float *tol, float *resid, int *ncv, + float *v, int *ldv, int *iparam, int *ipntr, + float *workd, float *workl, int *lworkl, + int *info); + +extern "C" void sseupd_(int *rvec, char *All, int *select, float *d, + float *z, int *ldz, float *sigma, + char *bmat, int *n, char *which, int *nev, + float *tol, float *resid, int *ncv, float *v, + int *ldv, int *iparam, int *ipntr, float *workd, + float *workl, int *lworkl, int *ierr); + +// Double precision +// +extern "C" void dsaupd_(int *ido, char *bmat, int *n, char *which, + int *nev, double *tol, double *resid, int *ncv, + double *v, int *ldv, int *iparam, int *ipntr, + double *workd, double *workl, int *lworkl, + int *info); + +extern "C" void dseupd_(int *rvec, char *All, int *select, double *d, + double *z, int *ldz, double *sigma, + char *bmat, int *n, char *which, int *nev, + double *tol, double *resid, int *ncv, double *v, + int *ldv, int *iparam, int *ipntr, double *workd, + double *workl, int *lworkl, int *ierr); + + +namespace internal { + +template struct arpack_wrapper +{ + static inline void saupd(int *ido, char *bmat, int *n, char *which, + int *nev, RealScalar *tol, Scalar *resid, int *ncv, + Scalar *v, int *ldv, int *iparam, int *ipntr, + Scalar *workd, Scalar *workl, int *lworkl, int *info) + { + EIGEN_STATIC_ASSERT(!NumTraits::IsComplex, NUMERIC_TYPE_MUST_BE_REAL) + } + + static inline void seupd(int *rvec, char *All, int *select, Scalar *d, + Scalar *z, int *ldz, RealScalar *sigma, + char *bmat, int *n, char *which, int *nev, + RealScalar *tol, Scalar *resid, int *ncv, Scalar *v, + int *ldv, int *iparam, int *ipntr, Scalar *workd, + Scalar *workl, int *lworkl, int *ierr) + { + EIGEN_STATIC_ASSERT(!NumTraits::IsComplex, NUMERIC_TYPE_MUST_BE_REAL) + } +}; + +template <> struct arpack_wrapper +{ + static inline void saupd(int *ido, char *bmat, int *n, char *which, + int *nev, float *tol, float *resid, int *ncv, + float *v, int *ldv, int *iparam, int *ipntr, + float *workd, float *workl, int *lworkl, int *info) + { + ssaupd_(ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd, workl, lworkl, info); + } + + static inline void seupd(int *rvec, char *All, int *select, float *d, + float *z, int *ldz, float *sigma, + char *bmat, int *n, char *which, int *nev, + float *tol, float *resid, int *ncv, float *v, + int *ldv, int *iparam, int *ipntr, float *workd, + float *workl, int *lworkl, int *ierr) + { + sseupd_(rvec, All, select, d, z, ldz, sigma, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, + workd, workl, lworkl, ierr); + } +}; + +template <> struct arpack_wrapper +{ + static inline void saupd(int *ido, char *bmat, int *n, char *which, + int *nev, double *tol, double *resid, int *ncv, + double *v, int *ldv, int *iparam, int *ipntr, + double *workd, double *workl, int *lworkl, int *info) + { + dsaupd_(ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, workd, workl, lworkl, info); + } + + static inline void seupd(int *rvec, char *All, int *select, double *d, + double *z, int *ldz, double *sigma, + char *bmat, int *n, char *which, int *nev, + double *tol, double *resid, int *ncv, double *v, + int *ldv, int *iparam, int *ipntr, double *workd, + double *workl, int *lworkl, int *ierr) + { + dseupd_(rvec, All, select, d, v, ldv, sigma, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, ipntr, + workd, workl, lworkl, ierr); + } +}; + + +template +struct OP +{ + static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out); + static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs); +}; + +template +struct OP +{ + static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out) +{ + // OP = L^{-1} A L^{-T} (B = LL^T) + // + // First solve L^T out = in + // + Matrix::Map(out, n) = OP.matrixU().solve(Matrix::Map(in, n)); + Matrix::Map(out, n) = OP.permutationPinv() * Matrix::Map(out, n); + + // Then compute out = A out + // + Matrix::Map(out, n) = A * Matrix::Map(out, n); + + // Then solve L out = out + // + Matrix::Map(out, n) = OP.permutationP() * Matrix::Map(out, n); + Matrix::Map(out, n) = OP.matrixL().solve(Matrix::Map(out, n)); +} + + static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs) +{ + // Solve L^T out = in + // + Matrix::Map(vecs, n, k) = OP.matrixU().solve(Matrix::Map(vecs, n, k)); + Matrix::Map(vecs, n, k) = OP.permutationPinv() * Matrix::Map(vecs, n, k); +} + +}; + +template +struct OP +{ + static inline void applyOP(MatrixSolver &OP, const MatrixType &A, int n, Scalar *in, Scalar *out) +{ + eigen_assert(false && "Should never be in here..."); +} + + static inline void project(MatrixSolver &OP, int n, int k, Scalar *vecs) +{ + eigen_assert(false && "Should never be in here..."); +} + +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_ARPACKSELFADJOINTEIGENSOLVER_H + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..c00cb576fac3a97a316ca507b46c4a2e6318e606 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Eigenvalues/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_EIGENVALUES_MODULE_H +#error "Please include unsupported/Eigen/Eigenvalues instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerAngles.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerAngles.h new file mode 100644 index 0000000000000000000000000000000000000000..252be429e6d8ae1dc6c319e47b33b94e0113d5fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerAngles.h @@ -0,0 +1,357 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Tal Hadad +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EULERANGLESCLASS_H// TODO: Fix previous "EIGEN_EULERANGLES_H" definition? +#define EIGEN_EULERANGLESCLASS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen +{ + /** \class EulerAngles + * + * \ingroup EulerAngles_Module + * + * \brief Represents a rotation in a 3 dimensional space as three Euler angles. + * + * Euler rotation is a set of three rotation of three angles over three fixed axes, defined by the EulerSystem given as a template parameter. + * + * Here is how intrinsic Euler angles works: + * - first, rotate the axes system over the alpha axis in angle alpha + * - then, rotate the axes system over the beta axis(which was rotated in the first stage) in angle beta + * - then, rotate the axes system over the gamma axis(which was rotated in the two stages above) in angle gamma + * + * \note This class support only intrinsic Euler angles for simplicity, + * see EulerSystem how to easily overcome this for extrinsic systems. + * + * ### Rotation representation and conversions ### + * + * It has been proved(see Wikipedia link below) that every rotation can be represented + * by Euler angles, but there is no single representation (e.g. unlike rotation matrices). + * Therefore, you can convert from Eigen rotation and to them + * (including rotation matrices, which is not called "rotations" by Eigen design). + * + * Euler angles usually used for: + * - convenient human representation of rotation, especially in interactive GUI. + * - gimbal systems and robotics + * - efficient encoding(i.e. 3 floats only) of rotation for network protocols. + * + * However, Euler angles are slow comparing to quaternion or matrices, + * because their unnatural math definition, although it's simple for human. + * To overcome this, this class provide easy movement from the math friendly representation + * to the human friendly representation, and vise-versa. + * + * All the user need to do is a safe simple C++ type conversion, + * and this class take care for the math. + * Additionally, some axes related computation is done in compile time. + * + * #### Euler angles ranges in conversions #### + * Rotations representation as EulerAngles are not single (unlike matrices), + * and even have infinite EulerAngles representations.
+ * For example, add or subtract 2*PI from either angle of EulerAngles + * and you'll get the same rotation. + * This is the general reason for infinite representation, + * but it's not the only general reason for not having a single representation. + * + * When converting rotation to EulerAngles, this class convert it to specific ranges + * When converting some rotation to EulerAngles, the rules for ranges are as follow: + * - If the rotation we converting from is an EulerAngles + * (even when it represented as RotationBase explicitly), angles ranges are __undefined__. + * - otherwise, alpha and gamma angles will be in the range [-PI, PI].
+ * As for Beta angle: + * - If the system is Tait-Bryan, the beta angle will be in the range [-PI/2, PI/2]. + * - otherwise: + * - If the beta axis is positive, the beta angle will be in the range [0, PI] + * - If the beta axis is negative, the beta angle will be in the range [-PI, 0] + * + * \sa EulerAngles(const MatrixBase&) + * \sa EulerAngles(const RotationBase&) + * + * ### Convenient user typedefs ### + * + * Convenient typedefs for EulerAngles exist for float and double scalar, + * in a form of EulerAngles{A}{B}{C}{scalar}, + * e.g. \ref EulerAnglesXYZd, \ref EulerAnglesZYZf. + * + * Only for positive axes{+x,+y,+z} Euler systems are have convenient typedef. + * If you need negative axes{-x,-y,-z}, it is recommended to create you own typedef with + * a word that represent what you need. + * + * ### Example ### + * + * \include EulerAngles.cpp + * Output: \verbinclude EulerAngles.out + * + * ### Additional reading ### + * + * If you're want to get more idea about how Euler system work in Eigen see EulerSystem. + * + * More information about Euler angles: https://en.wikipedia.org/wiki/Euler_angles + * + * \tparam Scalar_ the scalar type, i.e. the type of the angles. + * + * \tparam _System the EulerSystem to use, which represents the axes of rotation. + */ + template + class EulerAngles : public RotationBase, 3> + { + public: + typedef RotationBase, 3> Base; + + /** the scalar type of the angles */ + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + + /** the EulerSystem to use, which represents the axes of rotation. */ + typedef _System System; + + typedef Matrix Matrix3; /*!< the equivalent rotation matrix type */ + typedef Matrix Vector3; /*!< the equivalent 3 dimension vector type */ + typedef Quaternion QuaternionType; /*!< the equivalent quaternion type */ + typedef AngleAxis AngleAxisType; /*!< the equivalent angle-axis type */ + + /** \returns the axis vector of the first (alpha) rotation */ + static Vector3 AlphaAxisVector() { + const Vector3& u = Vector3::Unit(System::AlphaAxisAbs - 1); + return System::IsAlphaOpposite ? -u : u; + } + + /** \returns the axis vector of the second (beta) rotation */ + static Vector3 BetaAxisVector() { + const Vector3& u = Vector3::Unit(System::BetaAxisAbs - 1); + return System::IsBetaOpposite ? -u : u; + } + + /** \returns the axis vector of the third (gamma) rotation */ + static Vector3 GammaAxisVector() { + const Vector3& u = Vector3::Unit(System::GammaAxisAbs - 1); + return System::IsGammaOpposite ? -u : u; + } + + private: + Vector3 m_angles; + + public: + /** Default constructor without initialization. */ + EulerAngles() {} + /** Constructs and initialize an EulerAngles (\p alpha, \p beta, \p gamma). */ + EulerAngles(const Scalar& alpha, const Scalar& beta, const Scalar& gamma) : + m_angles(alpha, beta, gamma) {} + + // TODO: Test this constructor + /** Constructs and initialize an EulerAngles from the array data {alpha, beta, gamma} */ + explicit EulerAngles(const Scalar* data) : m_angles(data) {} + + /** Constructs and initializes an EulerAngles from either: + * - a 3x3 rotation matrix expression(i.e. pure orthogonal matrix with determinant of +1), + * - a 3D vector expression representing Euler angles. + * + * \note If \p other is a 3x3 rotation matrix, the angles range rules will be as follow:
+ * Alpha and gamma angles will be in the range [-PI, PI].
+ * As for Beta angle: + * - If the system is Tait-Bryan, the beta angle will be in the range [-PI/2, PI/2]. + * - otherwise: + * - If the beta axis is positive, the beta angle will be in the range [0, PI] + * - If the beta axis is negative, the beta angle will be in the range [-PI, 0] + */ + template + explicit EulerAngles(const MatrixBase& other) { *this = other; } + + /** Constructs and initialize Euler angles from a rotation \p rot. + * + * \note If \p rot is an EulerAngles (even when it represented as RotationBase explicitly), + * angles ranges are __undefined__. + * Otherwise, alpha and gamma angles will be in the range [-PI, PI].
+ * As for Beta angle: + * - If the system is Tait-Bryan, the beta angle will be in the range [-PI/2, PI/2]. + * - otherwise: + * - If the beta axis is positive, the beta angle will be in the range [0, PI] + * - If the beta axis is negative, the beta angle will be in the range [-PI, 0] + */ + template + EulerAngles(const RotationBase& rot) { System::CalcEulerAngles(*this, rot.toRotationMatrix()); } + + /*EulerAngles(const QuaternionType& q) + { + // TODO: Implement it in a faster way for quaternions + // According to http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/ + // we can compute only the needed matrix cells and then convert to euler angles. (see ZYX example below) + // Currently we compute all matrix cells from quaternion. + + // Special case only for ZYX + //Scalar y2 = q.y() * q.y(); + //m_angles[0] = std::atan2(2*(q.w()*q.z() + q.x()*q.y()), (1 - 2*(y2 + q.z()*q.z()))); + //m_angles[1] = std::asin( 2*(q.w()*q.y() - q.z()*q.x())); + //m_angles[2] = std::atan2(2*(q.w()*q.x() + q.y()*q.z()), (1 - 2*(q.x()*q.x() + y2))); + }*/ + + /** \returns The angle values stored in a vector (alpha, beta, gamma). */ + const Vector3& angles() const { return m_angles; } + /** \returns A read-write reference to the angle values stored in a vector (alpha, beta, gamma). */ + Vector3& angles() { return m_angles; } + + /** \returns The value of the first angle. */ + Scalar alpha() const { return m_angles[0]; } + /** \returns A read-write reference to the angle of the first angle. */ + Scalar& alpha() { return m_angles[0]; } + + /** \returns The value of the second angle. */ + Scalar beta() const { return m_angles[1]; } + /** \returns A read-write reference to the angle of the second angle. */ + Scalar& beta() { return m_angles[1]; } + + /** \returns The value of the third angle. */ + Scalar gamma() const { return m_angles[2]; } + /** \returns A read-write reference to the angle of the third angle. */ + Scalar& gamma() { return m_angles[2]; } + + /** \returns The Euler angles rotation inverse (which is as same as the negative), + * (-alpha, -beta, -gamma). + */ + EulerAngles inverse() const + { + EulerAngles res; + res.m_angles = -m_angles; + return res; + } + + /** \returns The Euler angles rotation negative (which is as same as the inverse), + * (-alpha, -beta, -gamma). + */ + EulerAngles operator -() const + { + return inverse(); + } + + /** Set \c *this from either: + * - a 3x3 rotation matrix expression(i.e. pure orthogonal matrix with determinant of +1), + * - a 3D vector expression representing Euler angles. + * + * See EulerAngles(const MatrixBase&) for more information about + * angles ranges output. + */ + template + EulerAngles& operator=(const MatrixBase& other) + { + EIGEN_STATIC_ASSERT((internal::is_same::value), + YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) + + internal::eulerangles_assign_impl::run(*this, other.derived()); + return *this; + } + + // TODO: Assign and construct from another EulerAngles (with different system) + + /** Set \c *this from a rotation. + * + * See EulerAngles(const RotationBase&) for more information about + * angles ranges output. + */ + template + EulerAngles& operator=(const RotationBase& rot) { + System::CalcEulerAngles(*this, rot.toRotationMatrix()); + return *this; + } + + /** \returns \c true if \c *this is approximately equal to \a other, within the precision + * determined by \a prec. + * + * \sa MatrixBase::isApprox() */ + bool isApprox(const EulerAngles& other, + const RealScalar& prec = NumTraits::dummy_precision()) const + { return angles().isApprox(other.angles(), prec); } + + /** \returns an equivalent 3x3 rotation matrix. */ + Matrix3 toRotationMatrix() const + { + // TODO: Calc it faster + return static_cast(*this).toRotationMatrix(); + } + + /** Convert the Euler angles to quaternion. */ + operator QuaternionType() const + { + return + AngleAxisType(alpha(), AlphaAxisVector()) * + AngleAxisType(beta(), BetaAxisVector()) * + AngleAxisType(gamma(), GammaAxisVector()); + } + + friend std::ostream& operator<<(std::ostream& s, const EulerAngles& eulerAngles) + { + s << eulerAngles.angles().transpose(); + return s; + } + + /** \returns \c *this with scalar type casted to \a NewScalarType */ + template + EulerAngles cast() const + { + EulerAngles e; + e.angles() = angles().template cast(); + return e; + } + }; + +#define EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(AXES, SCALAR_TYPE, SCALAR_POSTFIX) \ + /** \ingroup EulerAngles_Module */ \ + typedef EulerAngles EulerAngles##AXES##SCALAR_POSTFIX; + +#define EIGEN_EULER_ANGLES_TYPEDEFS(SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(XYZ, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(XYX, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(XZY, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(XZX, SCALAR_TYPE, SCALAR_POSTFIX) \ + \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(YZX, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(YZY, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(YXZ, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(YXY, SCALAR_TYPE, SCALAR_POSTFIX) \ + \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(ZXY, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(ZXZ, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(ZYX, SCALAR_TYPE, SCALAR_POSTFIX) \ + EIGEN_EULER_ANGLES_SINGLE_TYPEDEF(ZYZ, SCALAR_TYPE, SCALAR_POSTFIX) + +EIGEN_EULER_ANGLES_TYPEDEFS(float, f) +EIGEN_EULER_ANGLES_TYPEDEFS(double, d) + + namespace internal + { + template + struct traits > + { + typedef Scalar_ Scalar; + }; + + // set from a rotation matrix + template + struct eulerangles_assign_impl + { + typedef typename Other::Scalar Scalar; + static void run(EulerAngles& e, const Other& m) + { + System::CalcEulerAngles(e, m); + } + }; + + // set from a vector of Euler angles + template + struct eulerangles_assign_impl + { + typedef typename Other::Scalar Scalar; + static void run(EulerAngles& e, const Other& vec) + { + e.angles() = vec; + } + }; + } +} + +#endif // EIGEN_EULERANGLESCLASS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerSystem.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerSystem.h new file mode 100644 index 0000000000000000000000000000000000000000..278f9bf22275b2338c29aaa4f5a1e9989efb98b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/EulerSystem.h @@ -0,0 +1,307 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Tal Hadad +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EULERSYSTEM_H +#define EIGEN_EULERSYSTEM_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen +{ + // Forward declarations + template + class EulerAngles; + + namespace internal + { + // TODO: Add this trait to the Eigen internal API? + template 0)> + struct Abs + { + enum { value = Num }; + }; + + template + struct Abs + { + enum { value = -Num }; + }; + + template + struct IsValidAxis + { + enum { value = Axis != 0 && Abs::value <= 3 }; + }; + + template + struct eulerangles_assign_impl; + } + + #define EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1] + + /** \brief Representation of a fixed signed rotation axis for EulerSystem. + * + * \ingroup EulerAngles_Module + * + * Values here represent: + * - The axis of the rotation: X, Y or Z. + * - The sign (i.e. direction of the rotation along the axis): positive(+) or negative(-) + * + * Therefore, this could express all the axes {+X,+Y,+Z,-X,-Y,-Z} + * + * For positive axis, use +EULER_{axis}, and for negative axis use -EULER_{axis}. + */ + enum EulerAxis + { + EULER_X = 1, /*!< the X axis */ + EULER_Y = 2, /*!< the Y axis */ + EULER_Z = 3 /*!< the Z axis */ + }; + + /** \class EulerSystem + * + * \ingroup EulerAngles_Module + * + * \brief Represents a fixed Euler rotation system. + * + * This meta-class goal is to represent the Euler system in compilation time, for EulerAngles. + * + * You can use this class to get two things: + * - Build an Euler system, and then pass it as a template parameter to EulerAngles. + * - Query some compile time data about an Euler system. (e.g. Whether it's Tait-Bryan) + * + * Euler rotation is a set of three rotation on fixed axes. (see \ref EulerAngles) + * This meta-class store constantly those signed axes. (see \ref EulerAxis) + * + * ### Types of Euler systems ### + * + * All and only valid 3 dimension Euler rotation over standard + * signed axes{+X,+Y,+Z,-X,-Y,-Z} are supported: + * - all axes X, Y, Z in each valid order (see below what order is valid) + * - rotation over the axis is supported both over the positive and negative directions. + * - both Tait-Bryan and proper/classic Euler angles (i.e. the opposite). + * + * Since EulerSystem support both positive and negative directions, + * you may call this rotation distinction in other names: + * - _right handed_ or _left handed_ + * - _counterclockwise_ or _clockwise_ + * + * Notice all axed combination are valid, and would trigger a static assertion. + * Same unsigned axes can't be neighbors, e.g. {X,X,Y} is invalid. + * This yield two and only two classes: + * - _Tait-Bryan_ - all unsigned axes are distinct, e.g. {X,Y,Z} + * - _proper/classic Euler angles_ - The first and the third unsigned axes is equal, + * and the second is different, e.g. {X,Y,X} + * + * ### Intrinsic vs extrinsic Euler systems ### + * + * Only intrinsic Euler systems are supported for simplicity. + * If you want to use extrinsic Euler systems, + * just use the equal intrinsic opposite order for axes and angles. + * I.e axes (A,B,C) becomes (C,B,A), and angles (a,b,c) becomes (c,b,a). + * + * ### Convenient user typedefs ### + * + * Convenient typedefs for EulerSystem exist (only for positive axes Euler systems), + * in a form of EulerSystem{A}{B}{C}, e.g. \ref EulerSystemXYZ. + * + * ### Additional reading ### + * + * More information about Euler angles: https://en.wikipedia.org/wiki/Euler_angles + * + * \tparam _AlphaAxis the first fixed EulerAxis + * + * \tparam _BetaAxis the second fixed EulerAxis + * + * \tparam _GammaAxis the third fixed EulerAxis + */ + template + class EulerSystem + { + public: + // It's defined this way and not as enum, because I think + // that enum is not guerantee to support negative numbers + + /** The first rotation axis */ + static constexpr int AlphaAxis = _AlphaAxis; + + /** The second rotation axis */ + static constexpr int BetaAxis = _BetaAxis; + + /** The third rotation axis */ + static constexpr int GammaAxis = _GammaAxis; + + enum + { + AlphaAxisAbs = internal::Abs::value, /*!< the first rotation axis unsigned */ + BetaAxisAbs = internal::Abs::value, /*!< the second rotation axis unsigned */ + GammaAxisAbs = internal::Abs::value, /*!< the third rotation axis unsigned */ + + IsAlphaOpposite = (AlphaAxis < 0) ? 1 : 0, /*!< whether alpha axis is negative */ + IsBetaOpposite = (BetaAxis < 0) ? 1 : 0, /*!< whether beta axis is negative */ + IsGammaOpposite = (GammaAxis < 0) ? 1 : 0, /*!< whether gamma axis is negative */ + + // Parity is even if alpha axis X is followed by beta axis Y, or Y is followed + // by Z, or Z is followed by X; otherwise it is odd. + IsOdd = ((AlphaAxisAbs)%3 == (BetaAxisAbs - 1)%3) ? 0 : 1, /*!< whether the Euler system is odd */ + IsEven = IsOdd ? 0 : 1, /*!< whether the Euler system is even */ + + IsTaitBryan = ((unsigned)AlphaAxisAbs != (unsigned)GammaAxisAbs) ? 1 : 0 /*!< whether the Euler system is Tait-Bryan */ + }; + + private: + + EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis::value, + ALPHA_AXIS_IS_INVALID); + + EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis::value, + BETA_AXIS_IS_INVALID); + + EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT(internal::IsValidAxis::value, + GAMMA_AXIS_IS_INVALID); + + EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT((unsigned)AlphaAxisAbs != (unsigned)BetaAxisAbs, + ALPHA_AXIS_CANT_BE_EQUAL_TO_BETA_AXIS); + + EIGEN_EULER_ANGLES_CLASS_STATIC_ASSERT((unsigned)BetaAxisAbs != (unsigned)GammaAxisAbs, + BETA_AXIS_CANT_BE_EQUAL_TO_GAMMA_AXIS); + + static const int + // I, J, K are the pivot indexes permutation for the rotation matrix, that match this Euler system. + // They are used in this class converters. + // They are always different from each other, and their possible values are: 0, 1, or 2. + I_ = AlphaAxisAbs - 1, + J_ = (AlphaAxisAbs - 1 + 1 + IsOdd)%3, + K_ = (AlphaAxisAbs - 1 + 2 - IsOdd)%3 + ; + + // TODO: Get @mat parameter in form that avoids double evaluation. + template + static void CalcEulerAngles_imp(Matrix::Scalar, 3, 1>& res, const MatrixBase& mat, internal::true_type /*isTaitBryan*/) + { + using std::atan2; + using std::sqrt; + + typedef typename Derived::Scalar Scalar; + + const Scalar plusMinus = IsEven? 1 : -1; + const Scalar minusPlus = IsOdd? 1 : -1; + + const Scalar Rsum = sqrt((mat(I_,I_) * mat(I_,I_) + mat(I_,J_) * mat(I_,J_) + mat(J_,K_) * mat(J_,K_) + mat(K_,K_) * mat(K_,K_))/2); + res[1] = atan2(plusMinus * mat(I_,K_), Rsum); + + // There is a singularity when cos(beta) == 0 + if(Rsum > 4 * NumTraits::epsilon()) {// cos(beta) != 0 + res[0] = atan2(minusPlus * mat(J_, K_), mat(K_, K_)); + res[2] = atan2(minusPlus * mat(I_, J_), mat(I_, I_)); + } + else if(plusMinus * mat(I_, K_) > 0) {// cos(beta) == 0 and sin(beta) == 1 + Scalar spos = mat(J_, I_) + plusMinus * mat(K_, J_); // 2*sin(alpha + plusMinus * gamma + Scalar cpos = mat(J_, J_) + minusPlus * mat(K_, I_); // 2*cos(alpha + plusMinus * gamma) + Scalar alphaPlusMinusGamma = atan2(spos, cpos); + res[0] = alphaPlusMinusGamma; + res[2] = 0; + } + else {// cos(beta) == 0 and sin(beta) == -1 + Scalar sneg = plusMinus * (mat(K_, J_) + minusPlus * mat(J_, I_)); // 2*sin(alpha + minusPlus*gamma) + Scalar cneg = mat(J_, J_) + plusMinus * mat(K_, I_); // 2*cos(alpha + minusPlus*gamma) + Scalar alphaMinusPlusBeta = atan2(sneg, cneg); + res[0] = alphaMinusPlusBeta; + res[2] = 0; + } + } + + template + static void CalcEulerAngles_imp(Matrix::Scalar,3,1>& res, + const MatrixBase& mat, internal::false_type /*isTaitBryan*/) + { + using std::atan2; + using std::sqrt; + + typedef typename Derived::Scalar Scalar; + + const Scalar plusMinus = IsEven? 1 : -1; + const Scalar minusPlus = IsOdd? 1 : -1; + + const Scalar Rsum = sqrt((mat(I_, J_) * mat(I_, J_) + mat(I_, K_) * mat(I_, K_) + mat(J_, I_) * mat(J_, I_) + mat(K_, I_) * mat(K_, I_)) / 2); + + res[1] = atan2(Rsum, mat(I_, I_)); + + // There is a singularity when sin(beta) == 0 + if(Rsum > 4 * NumTraits::epsilon()) {// sin(beta) != 0 + res[0] = atan2(mat(J_, I_), minusPlus * mat(K_, I_)); + res[2] = atan2(mat(I_, J_), plusMinus * mat(I_, K_)); + } + else if(mat(I_, I_) > 0) {// sin(beta) == 0 and cos(beta) == 1 + Scalar spos = plusMinus * mat(K_, J_) + minusPlus * mat(J_, K_); // 2*sin(alpha + gamma) + Scalar cpos = mat(J_, J_) + mat(K_, K_); // 2*cos(alpha + gamma) + res[0] = atan2(spos, cpos); + res[2] = 0; + } + else {// sin(beta) == 0 and cos(beta) == -1 + Scalar sneg = plusMinus * mat(K_, J_) + plusMinus * mat(J_, K_); // 2*sin(alpha - gamma) + Scalar cneg = mat(J_, J_) - mat(K_, K_); // 2*cos(alpha - gamma) + res[0] = atan2(sneg, cneg); + res[2] = 0; + } + } + + template + static void CalcEulerAngles( + EulerAngles& res, + const typename EulerAngles::Matrix3& mat) + { + CalcEulerAngles_imp( + res.angles(), mat, + std::conditional_t()); + + if (IsAlphaOpposite) + res.alpha() = -res.alpha(); + + if (IsBetaOpposite) + res.beta() = -res.beta(); + + if (IsGammaOpposite) + res.gamma() = -res.gamma(); + } + + template + friend class Eigen::EulerAngles; + + template + friend struct internal::eulerangles_assign_impl; + }; + +#define EIGEN_EULER_SYSTEM_TYPEDEF(A, B, C) \ + /** \ingroup EulerAngles_Module */ \ + typedef EulerSystem EulerSystem##A##B##C; + + EIGEN_EULER_SYSTEM_TYPEDEF(X,Y,Z) + EIGEN_EULER_SYSTEM_TYPEDEF(X,Y,X) + EIGEN_EULER_SYSTEM_TYPEDEF(X,Z,Y) + EIGEN_EULER_SYSTEM_TYPEDEF(X,Z,X) + + EIGEN_EULER_SYSTEM_TYPEDEF(Y,Z,X) + EIGEN_EULER_SYSTEM_TYPEDEF(Y,Z,Y) + EIGEN_EULER_SYSTEM_TYPEDEF(Y,X,Z) + EIGEN_EULER_SYSTEM_TYPEDEF(Y,X,Y) + + EIGEN_EULER_SYSTEM_TYPEDEF(Z,X,Y) + EIGEN_EULER_SYSTEM_TYPEDEF(Z,X,Z) + EIGEN_EULER_SYSTEM_TYPEDEF(Z,Y,X) + EIGEN_EULER_SYSTEM_TYPEDEF(Z,Y,Z) +} + +#endif // EIGEN_EULERSYSTEM_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..0c00a306b04d3bae897c0ba0cf974bebd43c3047 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/EulerAngles/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_EULERANGLES_MODULE_H +#error "Please include unsupported/Eigen/EulerAngles instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..801e24548c1aac50df97afea89272502ed7fd9b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_FFT_MODULE_H +#error "Please include unsupported/Eigen/FFT instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_fftw_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_fftw_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..034343d978816b2d34233c3e6cce893db485c773 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_fftw_impl.h @@ -0,0 +1,265 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Mark Borgerding mark a borgerding net +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include "./InternalHeaderCheck.h" + +#include + +namespace Eigen { + +namespace internal { + + // FFTW uses non-const arguments + // so we must use ugly const_cast calls for all the args it uses + // + // This should be safe as long as + // 1. we use FFTW_ESTIMATE for all our planning + // see the FFTW docs section 4.3.2 "Planner Flags" + // 2. fftw_complex is compatible with std::complex + // This assumes std::complex layout is array of size 2 with real,imag + template + inline + T * fftw_cast(const T* p) + { + return const_cast( p); + } + + inline + fftw_complex * fftw_cast( const std::complex * p) + { + return const_cast( reinterpret_cast(p) ); + } + + inline + fftwf_complex * fftw_cast( const std::complex * p) + { + return const_cast( reinterpret_cast(p) ); + } + + inline + fftwl_complex * fftw_cast( const std::complex * p) + { + return const_cast( reinterpret_cast(p) ); + } + + template + struct fftw_plan {}; + + template <> + struct fftw_plan + { + typedef float scalar_type; + typedef fftwf_complex complex_type; + std::shared_ptr m_plan; + fftw_plan() = default; + + void set_plan(fftwf_plan p) { m_plan.reset(p, fftwf_destroy_plan); } + inline + void fwd(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwf_plan_dft_1d(nfft,src,dst, FFTW_FORWARD, FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft( m_plan.get(), src,dst); + } + inline + void inv(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwf_plan_dft_1d(nfft,src,dst, FFTW_BACKWARD , FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft( m_plan.get(), src,dst); + } + inline + void fwd(complex_type * dst,scalar_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwf_plan_dft_r2c_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft_r2c( m_plan.get(),src,dst); + } + inline + void inv(scalar_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) + set_plan(fftwf_plan_dft_c2r_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft_c2r( m_plan.get(), src,dst); + } + + inline + void fwd2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftwf_plan_dft_2d(n0,n1,src,dst,FFTW_FORWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft( m_plan.get(), src,dst); + } + inline + void inv2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftwf_plan_dft_2d(n0,n1,src,dst,FFTW_BACKWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwf_execute_dft( m_plan.get(), src,dst); + } + + }; + template <> + struct fftw_plan + { + typedef double scalar_type; + typedef fftw_complex complex_type; + std::shared_ptr m_plan; + fftw_plan() = default; + + void set_plan(::fftw_plan p) { m_plan.reset(p, fftw_destroy_plan); } + inline + void fwd(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftw_plan_dft_1d(nfft,src,dst, FFTW_FORWARD, FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft( m_plan.get(), src,dst); + } + inline + void inv(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftw_plan_dft_1d(nfft,src,dst, FFTW_BACKWARD , FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft( m_plan.get(), src,dst); + } + inline + void fwd(complex_type * dst,scalar_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftw_plan_dft_r2c_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft_r2c( m_plan.get(),src,dst); + } + inline + void inv(scalar_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) + set_plan(fftw_plan_dft_c2r_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft_c2r( m_plan.get(), src,dst); + } + inline + void fwd2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftw_plan_dft_2d(n0,n1,src,dst,FFTW_FORWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft( m_plan.get(), src,dst); + } + inline + void inv2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftw_plan_dft_2d(n0,n1,src,dst,FFTW_BACKWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftw_execute_dft( m_plan.get(), src,dst); + } + }; + template <> + struct fftw_plan + { + typedef long double scalar_type; + typedef fftwl_complex complex_type; + std::shared_ptr m_plan; + fftw_plan() = default; + + void set_plan(fftwl_plan p) { m_plan.reset(p, fftwl_destroy_plan); } + inline + void fwd(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwl_plan_dft_1d(nfft,src,dst, FFTW_FORWARD, FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft( m_plan.get(), src,dst); + } + inline + void inv(complex_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwl_plan_dft_1d(nfft,src,dst, FFTW_BACKWARD , FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft( m_plan.get(), src,dst); + } + inline + void fwd(complex_type * dst,scalar_type * src,int nfft) { + if (m_plan==NULL) set_plan(fftwl_plan_dft_r2c_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft_r2c( m_plan.get(),src,dst); + } + inline + void inv(scalar_type * dst,complex_type * src,int nfft) { + if (m_plan==NULL) + set_plan(fftwl_plan_dft_c2r_1d(nfft,src,dst,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft_c2r( m_plan.get(), src,dst); + } + inline + void fwd2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftwl_plan_dft_2d(n0,n1,src,dst,FFTW_FORWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft( m_plan.get(), src,dst); + } + inline + void inv2( complex_type * dst,complex_type * src,int n0,int n1) { + if (m_plan==NULL) set_plan(fftwl_plan_dft_2d(n0,n1,src,dst,FFTW_BACKWARD,FFTW_ESTIMATE|FFTW_PRESERVE_INPUT)); + fftwl_execute_dft( m_plan.get(), src,dst); + } + }; + + template + struct fftw_impl + { + typedef Scalar_ Scalar; + typedef std::complex Complex; + + inline + void clear() + { + m_plans.clear(); + } + + // complex-to-complex forward FFT + inline + void fwd( Complex * dst,const Complex *src,int nfft) + { + get_plan(nfft,false,dst,src).fwd(fftw_cast(dst), fftw_cast(src),nfft ); + } + + // real-to-complex forward FFT + inline + void fwd( Complex * dst,const Scalar * src,int nfft) + { + get_plan(nfft,false,dst,src).fwd(fftw_cast(dst), fftw_cast(src) ,nfft); + } + + // 2-d complex-to-complex + inline + void fwd2(Complex * dst, const Complex * src, int n0,int n1) + { + get_plan(n0,n1,false,dst,src).fwd2(fftw_cast(dst), fftw_cast(src) ,n0,n1); + } + + // inverse complex-to-complex + inline + void inv(Complex * dst,const Complex *src,int nfft) + { + get_plan(nfft,true,dst,src).inv(fftw_cast(dst), fftw_cast(src),nfft ); + } + + // half-complex to scalar + inline + void inv( Scalar * dst,const Complex * src,int nfft) + { + get_plan(nfft,true,dst,src).inv(fftw_cast(dst), fftw_cast(src),nfft ); + } + + // 2-d complex-to-complex + inline + void inv2(Complex * dst, const Complex * src, int n0,int n1) + { + get_plan(n0,n1,true,dst,src).inv2(fftw_cast(dst), fftw_cast(src) ,n0,n1); + } + + + protected: + typedef fftw_plan PlanData; + + typedef Eigen::numext::int64_t int64_t; + + typedef std::map PlanMap; + + PlanMap m_plans; + + inline + PlanData & get_plan(int nfft,bool inverse,void * dst,const void * src) + { + bool inplace = (dst==src); + bool aligned = ( (reinterpret_cast(src)&15) | (reinterpret_cast(dst)&15) ) == 0; + int64_t key = ( (nfft<<3 ) | (inverse<<2) | (inplace<<1) | aligned ) << 1; + return m_plans[key]; + } + + inline + PlanData & get_plan(int n0,int n1,bool inverse,void * dst,const void * src) + { + bool inplace = (dst==src); + bool aligned = ( (reinterpret_cast(src)&15) | (reinterpret_cast(dst)&15) ) == 0; + int64_t key = ( ( (((int64_t)n0) << 30)|(n1<<3 ) | (inverse<<2) | (inplace<<1) | aligned ) << 1 ) + 1; + return m_plans[key]; + } + }; + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_imklfft_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_imklfft_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..abfe20b4e16a48577f69f4644ead121eaaf43563 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_imklfft_impl.h @@ -0,0 +1,286 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include + +#include "./InternalHeaderCheck.h" + +#include +#include + +namespace Eigen { +namespace internal { +namespace imklfft { + +#define RUN_OR_ASSERT(EXPR, ERROR_MSG) \ + { \ + MKL_LONG status = (EXPR); \ + eigen_assert(status == DFTI_NO_ERROR && (ERROR_MSG)); \ + }; + +inline MKL_Complex16* complex_cast(const std::complex* p) { + return const_cast(reinterpret_cast(p)); +} + +inline MKL_Complex8* complex_cast(const std::complex* p) { + return const_cast(reinterpret_cast(p)); +} + +/* + * Parameters: + * precision: enum, Precision of the transform: DFTI_SINGLE or DFTI_DOUBLE. + * forward_domain: enum, Forward domain of the transform: DFTI_COMPLEX or + * DFTI_REAL. dimension: MKL_LONG Dimension of the transform. sizes: MKL_LONG if + * dimension = 1.Length of the transform for a one-dimensional transform. sizes: + * Array of type MKL_LONG otherwise. Lengths of each dimension for a + * multi-dimensional transform. + */ +inline void configure_descriptor(std::shared_ptr& handl, + enum DFTI_CONFIG_VALUE precision, + enum DFTI_CONFIG_VALUE forward_domain, + MKL_LONG dimension, MKL_LONG* sizes) { + eigen_assert(dimension == 1 || + dimension == 2 && + "Transformation dimension must be less than 3."); + + DFTI_DESCRIPTOR_HANDLE res = nullptr; + if (dimension == 1) { + RUN_OR_ASSERT(DftiCreateDescriptor(&res, precision, forward_domain, + dimension, *sizes), + "DftiCreateDescriptor failed.") + handl.reset(res, [](DFTI_DESCRIPTOR_HANDLE handle) { DftiFreeDescriptor(&handle); }); + if (forward_domain == DFTI_REAL) { + // Set CCE storage + RUN_OR_ASSERT(DftiSetValue(handl.get(), DFTI_CONJUGATE_EVEN_STORAGE, + DFTI_COMPLEX_COMPLEX), + "DftiSetValue failed.") + } + } else { + RUN_OR_ASSERT( + DftiCreateDescriptor(&res, precision, DFTI_COMPLEX, dimension, sizes), + "DftiCreateDescriptor failed.") + handl.reset(res, [](DFTI_DESCRIPTOR_HANDLE handle) { DftiFreeDescriptor(&handle); }); + } + + RUN_OR_ASSERT(DftiSetValue(handl.get(), DFTI_PLACEMENT, DFTI_NOT_INPLACE), + "DftiSetValue failed.") + RUN_OR_ASSERT(DftiCommitDescriptor(handl.get()), "DftiCommitDescriptor failed.") +} + +template +struct plan {}; + +template <> +struct plan { + typedef float scalar_type; + typedef MKL_Complex8 complex_type; + + std::shared_ptr m_plan; + + plan() = default; + + enum DFTI_CONFIG_VALUE precision = DFTI_SINGLE; + + inline void forward(complex_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse(complex_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } + + inline void forward(complex_type* dst, scalar_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_REAL, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse(scalar_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_REAL, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } + + inline void forward2(complex_type* dst, complex_type* src, int n0, int n1) { + if (m_plan == 0) { + MKL_LONG sizes[2] = {n0, n1}; + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 2, sizes); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse2(complex_type* dst, complex_type* src, int n0, int n1) { + if (m_plan == 0) { + MKL_LONG sizes[2] = {n0, n1}; + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 2, sizes); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } +}; + +template <> +struct plan { + typedef double scalar_type; + typedef MKL_Complex16 complex_type; + + std::shared_ptr m_plan; + + plan() = default; + + enum DFTI_CONFIG_VALUE precision = DFTI_DOUBLE; + + inline void forward(complex_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse(complex_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } + + inline void forward(complex_type* dst, scalar_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_REAL, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse(scalar_type* dst, complex_type* src, MKL_LONG nfft) { + if (m_plan == 0) { + configure_descriptor(m_plan, precision, DFTI_REAL, 1, &nfft); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } + + inline void forward2(complex_type* dst, complex_type* src, int n0, int n1) { + if (m_plan == 0) { + MKL_LONG sizes[2] = {n0, n1}; + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 2, sizes); + } + RUN_OR_ASSERT(DftiComputeForward(m_plan.get(), src, dst), + "DftiComputeForward failed.") + } + + inline void inverse2(complex_type* dst, complex_type* src, int n0, int n1) { + if (m_plan == 0) { + MKL_LONG sizes[2] = {n0, n1}; + configure_descriptor(m_plan, precision, DFTI_COMPLEX, 2, sizes); + } + RUN_OR_ASSERT(DftiComputeBackward(m_plan.get(), src, dst), + "DftiComputeBackward failed.") + } +}; + +template +struct imklfft_impl { + typedef Scalar_ Scalar; + typedef std::complex Complex; + + inline void clear() { m_plans.clear(); } + + // complex-to-complex forward FFT + inline void fwd(Complex* dst, const Complex* src, int nfft) { + MKL_LONG size = nfft; + get_plan(nfft, dst, src) + .forward(complex_cast(dst), complex_cast(src), size); + } + + // real-to-complex forward FFT + inline void fwd(Complex* dst, const Scalar* src, int nfft) { + MKL_LONG size = nfft; + get_plan(nfft, dst, src) + .forward(complex_cast(dst), const_cast(src), nfft); + } + + // 2-d complex-to-complex + inline void fwd2(Complex* dst, const Complex* src, int n0, int n1) { + get_plan(n0, n1, dst, src) + .forward2(complex_cast(dst), complex_cast(src), n0, n1); + } + + // inverse complex-to-complex + inline void inv(Complex* dst, const Complex* src, int nfft) { + MKL_LONG size = nfft; + get_plan(nfft, dst, src) + .inverse(complex_cast(dst), complex_cast(src), nfft); + } + + // half-complex to scalar + inline void inv(Scalar* dst, const Complex* src, int nfft) { + MKL_LONG size = nfft; + get_plan(nfft, dst, src) + .inverse(const_cast(dst), complex_cast(src), nfft); + } + + // 2-d complex-to-complex + inline void inv2(Complex* dst, const Complex* src, int n0, int n1) { + get_plan(n0, n1, dst, src) + .inverse2(complex_cast(dst), complex_cast(src), n0, n1); + } + + private: + std::map> m_plans; + + inline plan& get_plan(int nfft, void* dst, + const void* src) { + int inplace = dst == src ? 1 : 0; + int aligned = ((reinterpret_cast(src) & 15) | + (reinterpret_cast(dst) & 15)) == 0 + ? 1 + : 0; + int64_t key = ((nfft << 2) | (inplace << 1) | aligned) + << 1; + + // Create element if key does not exist. + return m_plans[key]; + } + + inline plan& get_plan(int n0, int n1, void* dst, + const void* src) { + int inplace = (dst == src) ? 1 : 0; + int aligned = ((reinterpret_cast(src) & 15) | + (reinterpret_cast(dst) & 15)) == 0 + ? 1 + : 0; + int64_t key = (((((int64_t)n0) << 31) | (n1 << 2) | + (inplace << 1) | aligned) + << 1) + + 1; + + // Create element if key does not exist. + return m_plans[key]; + } +}; + +#undef RUN_OR_ASSERT + +} // namespace imklfft +} // namespace internal +} // namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_kissfft_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_kissfft_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..90e6690969817e471155e605f6d70f423512e8e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_kissfft_impl.h @@ -0,0 +1,451 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Mark Borgerding mark a borgerding net +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + + // This FFT implementation was derived from kissfft http:sourceforge.net/projects/kissfft + // Copyright 2003-2009 Mark Borgerding + +template +struct kiss_cpx_fft +{ + typedef Scalar_ Scalar; + typedef std::complex Complex; + std::vector m_twiddles; + std::vector m_stageRadix; + std::vector m_stageRemainder; + std::vector m_scratchBuf; + bool m_inverse; + + inline void make_twiddles(int nfft, bool inverse) + { + using numext::sin; + using numext::cos; + m_inverse = inverse; + m_twiddles.resize(nfft); + double phinc = 0.25 * double(EIGEN_PI) / nfft; + Scalar flip = inverse ? Scalar(1) : Scalar(-1); + m_twiddles[0] = Complex(Scalar(1), Scalar(0)); + if ((nfft&1)==0) + m_twiddles[nfft/2] = Complex(Scalar(-1), Scalar(0)); + int i=1; + for (;i*8n) + p=n;// impossible to have a factor > sqrt(n) + } + n /= p; + m_stageRadix.push_back(p); + m_stageRemainder.push_back(n); + if ( p > 5 ) + m_scratchBuf.resize(p); // scratchbuf will be needed in bfly_generic + }while(n>1); + } + + template + inline + void work( int stage,Complex * xout, const Src_ * xin, size_t fstride,size_t in_stride) + { + int p = m_stageRadix[stage]; + int m = m_stageRemainder[stage]; + Complex * Fout_beg = xout; + Complex * Fout_end = xout + p*m; + + if (m>1) { + do{ + // recursive call: + // DFT of size m*p performed by doing + // p instances of smaller DFTs of size m, + // each one takes a decimated version of the input + work(stage+1, xout , xin, fstride*p,in_stride); + xin += fstride*in_stride; + }while( (xout += m) != Fout_end ); + }else{ + do{ + *xout = *xin; + xin += fstride*in_stride; + }while(++xout != Fout_end ); + } + xout=Fout_beg; + + // recombine the p smaller DFTs + switch (p) { + case 2: bfly2(xout,fstride,m); break; + case 3: bfly3(xout,fstride,m); break; + case 4: bfly4(xout,fstride,m); break; + case 5: bfly5(xout,fstride,m); break; + default: bfly_generic(xout,fstride,m,p); break; + } + } + + inline + void bfly2( Complex * Fout, const size_t fstride, int m) + { + for (int k=0;kreal() - Scalar(.5)*scratch[3].real() , Fout->imag() - Scalar(.5)*scratch[3].imag() ); + scratch[0] *= epi3.imag(); + *Fout += scratch[3]; + Fout[m2] = Complex( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() ); + Fout[m] += Complex( -scratch[0].imag(),scratch[0].real() ); + ++Fout; + }while(--k); + } + + inline + void bfly5( Complex * Fout, const size_t fstride, const size_t m) + { + Complex *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; + size_t u; + Complex scratch[13]; + Complex * twiddles = &m_twiddles[0]; + Complex *tw; + Complex ya,yb; + ya = twiddles[fstride*m]; + yb = twiddles[fstride*2*m]; + + Fout0=Fout; + Fout1=Fout0+m; + Fout2=Fout0+2*m; + Fout3=Fout0+3*m; + Fout4=Fout0+4*m; + + tw=twiddles; + for ( u=0; u(m_twiddles.size()); + Complex * scratchbuf = &m_scratchBuf[0]; + + for ( u=0; u(fstride) * k; + if (twidx>=Norig) twidx-=Norig; + t=scratchbuf[q] * twiddles[twidx]; + Fout[ k ] += t; + } + k += m; + } + } + } +}; + +template +struct kissfft_impl +{ + typedef Scalar_ Scalar; + typedef std::complex Complex; + + void clear() + { + m_plans.clear(); + m_realTwiddles.clear(); + } + + inline + void fwd( Complex * dst,const Complex *src,int nfft) + { + get_plan(nfft,false).work(0, dst, src, 1,1); + } + + inline + void fwd2( Complex * dst,const Complex *src,int n0,int n1) + { + EIGEN_UNUSED_VARIABLE(dst); + EIGEN_UNUSED_VARIABLE(src); + EIGEN_UNUSED_VARIABLE(n0); + EIGEN_UNUSED_VARIABLE(n1); + } + + inline + void inv2( Complex * dst,const Complex *src,int n0,int n1) + { + EIGEN_UNUSED_VARIABLE(dst); + EIGEN_UNUSED_VARIABLE(src); + EIGEN_UNUSED_VARIABLE(n0); + EIGEN_UNUSED_VARIABLE(n1); + } + + // real-to-complex forward FFT + // perform two FFTs of src even and src odd + // then twiddle to recombine them into the half-spectrum format + // then fill in the conjugate symmetric half + inline + void fwd( Complex * dst,const Scalar * src,int nfft) + { + if ( nfft&3 ) { + // use generic mode for odd + m_tmpBuf1.resize(nfft); + get_plan(nfft,false).work(0, &m_tmpBuf1[0], src, 1,1); + std::copy(m_tmpBuf1.begin(),m_tmpBuf1.begin()+(nfft>>1)+1,dst ); + }else{ + int ncfft = nfft>>1; + int ncfft2 = nfft>>2; + Complex * rtw = real_twiddles(ncfft2); + + // use optimized mode for even real + fwd( dst, reinterpret_cast (src), ncfft); + Complex dc(dst[0].real() + dst[0].imag()); + Complex nyquist(dst[0].real() - dst[0].imag()); + int k; + for ( k=1;k <= ncfft2 ; ++k ) { + Complex fpk = dst[k]; + Complex fpnk = conj(dst[ncfft-k]); + Complex f1k = fpk + fpnk; + Complex f2k = fpk - fpnk; + Complex tw= f2k * rtw[k-1]; + dst[k] = (f1k + tw) * Scalar(.5); + dst[ncfft-k] = conj(f1k -tw)*Scalar(.5); + } + dst[0] = dc; + dst[ncfft] = nyquist; + } + } + + // inverse complex-to-complex + inline + void inv(Complex * dst,const Complex *src,int nfft) + { + get_plan(nfft,true).work(0, dst, src, 1,1); + } + + // half-complex to scalar + inline + void inv( Scalar * dst,const Complex * src,int nfft) + { + if (nfft&3) { + m_tmpBuf1.resize(nfft); + m_tmpBuf2.resize(nfft); + std::copy(src,src+(nfft>>1)+1,m_tmpBuf1.begin() ); + for (int k=1;k<(nfft>>1)+1;++k) + m_tmpBuf1[nfft-k] = conj(m_tmpBuf1[k]); + inv(&m_tmpBuf2[0],&m_tmpBuf1[0],nfft); + for (int k=0;k>1; + int ncfft2 = nfft>>2; + Complex * rtw = real_twiddles(ncfft2); + m_tmpBuf1.resize(ncfft); + m_tmpBuf1[0] = Complex( src[0].real() + src[ncfft].real(), src[0].real() - src[ncfft].real() ); + for (int k = 1; k <= ncfft / 2; ++k) { + Complex fk = src[k]; + Complex fnkc = conj(src[ncfft-k]); + Complex fek = fk + fnkc; + Complex tmp = fk - fnkc; + Complex fok = tmp * conj(rtw[k-1]); + m_tmpBuf1[k] = fek + fok; + m_tmpBuf1[ncfft-k] = conj(fek - fok); + } + get_plan(ncfft,true).work(0, reinterpret_cast(dst), &m_tmpBuf1[0], 1,1); + } + } + + protected: + typedef kiss_cpx_fft PlanData; + typedef std::map PlanMap; + + PlanMap m_plans; + std::map > m_realTwiddles; + std::vector m_tmpBuf1; + std::vector m_tmpBuf2; + + inline + int PlanKey(int nfft, bool isinverse) const { return (nfft<<1) | int(isinverse); } + + inline + PlanData & get_plan(int nfft, bool inverse) + { + // TODO look for PlanKey(nfft, ! inverse) and conjugate the twiddles + PlanData & pd = m_plans[ PlanKey(nfft,inverse) ]; + if ( pd.m_twiddles.size() == 0 ) { + pd.make_twiddles(nfft,inverse); + pd.factorize(nfft); + } + return pd; + } + + inline + Complex * real_twiddles(int ncfft2) + { + using std::acos; + std::vector & twidref = m_realTwiddles[ncfft2];// creates new if not there + if ( (int)twidref.size() != ncfft2 ) { + twidref.resize(ncfft2); + int ncfft= ncfft2<<1; + Scalar pi = acos( Scalar(-1) ); + for (int k=1;k<=ncfft2;++k) + twidref[k-1] = exp( Complex(0,-pi * (Scalar(k) / ncfft + Scalar(.5)) ) ); + } + return &twidref[0]; + } +}; + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_pocketfft_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_pocketfft_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..f2da890c7e4de95873f0f6e7bd8d5d6a7e4087b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/FFT/ei_pocketfft_impl.h @@ -0,0 +1,69 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +using namespace pocketfft; +using namespace pocketfft::detail; + +namespace Eigen { + +namespace internal { + +template +struct pocketfft_impl +{ + typedef _Scalar Scalar; + typedef std::complex Complex; + + inline void clear() {} + + inline void fwd(Complex* dst, const Scalar* src, int nfft){ + const shape_t shape_{ static_cast(nfft) }; + const shape_t axes_{ 0 }; + const stride_t stride_in{ sizeof(Scalar) }; + const stride_t stride_out{ sizeof(Complex) }; + r2c(shape_, stride_in, stride_out, axes_, FORWARD, src, dst, static_cast(1)); + } + + inline void fwd(Complex* dst, const Complex* src, int nfft){ + const shape_t shape_{ static_cast(nfft) }; + const shape_t axes_{ 0 }; + const stride_t stride_{ sizeof(Complex) }; + c2c(shape_, stride_, stride_, axes_, FORWARD, src, dst, static_cast(1)); + } + + inline void inv(Scalar* dst, const Complex* src, int nfft){ + const shape_t shape_{ static_cast(nfft) }; + const shape_t axes_{ 0 }; + const stride_t stride_in{ sizeof(Complex) }; + const stride_t stride_out{ sizeof(Scalar) }; + c2r(shape_, stride_in, stride_out, axes_, BACKWARD, src, dst, static_cast(1)); + } + + inline void inv(Complex* dst, const Complex* src, int nfft){ + const shape_t shape_{ static_cast(nfft) }; + const shape_t axes_{ 0 }; + const stride_t stride_{ sizeof(Complex) }; + c2c(shape_, stride_, stride_, axes_, BACKWARD, src, dst, static_cast(1)); + } + + inline void fwd2(Complex* dst, const Complex* src, int nfft0, int nfft1){ + const shape_t shape_{ static_cast(nfft0), static_cast(nfft1) }; + const shape_t axes_{ 0, 1 }; + const stride_t stride_{ static_cast(sizeof(Complex)*nfft1), static_cast(sizeof(Complex)) }; + c2c(shape_, stride_, stride_, axes_, FORWARD, src, dst, static_cast(1)); + } + + inline void inv2(Complex* dst, const Complex* src, int nfft0, int nfft1){ + const shape_t shape_{ static_cast(nfft0), static_cast(nfft1) }; + const shape_t axes_{ 0, 1 }; + const stride_t stride_{ static_cast(sizeof(Complex)*nfft1), static_cast(sizeof(Complex)) }; + c2c(shape_, stride_, stride_, axes_, BACKWARD, src, dst, static_cast(1)); + } +}; + +} // namespace internal +} // namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/BiCGSTABL.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/BiCGSTABL.h new file mode 100644 index 0000000000000000000000000000000000000000..141d7056d6d980d8de62653f63ebde4783d0e5f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/BiCGSTABL.h @@ -0,0 +1,339 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2020 Chris Schoutrop +// Copyright (C) 2020 Jens Wehner +// Copyright (C) 2020 Jan van Dijk +// Copyright (C) 2020 Adithya Vijaykumar +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +/* + + This implementation of BiCGStab(L) is based on the papers + General algorithm: + 1. G.L.G. Sleijpen, D.R. Fokkema. (1993). BiCGstab(l) for linear equations + involving unsymmetric matrices with complex spectrum. Electronic Transactions + on Numerical Analysis. Polynomial step update: + 2. G.L.G. Sleijpen, M.B. Van Gijzen. (2010) Exploiting BiCGstab(l) + strategies to induce dimension reduction SIAM Journal on Scientific Computing. + 3. Fokkema, Diederik R. Enhanced implementation of BiCGstab (l) for + solving linear systems of equations. Universiteit Utrecht. Mathematisch + Instituut, 1996 + 4. Sleijpen, G. L., & van der Vorst, H. A. (1996). Reliable updated + residuals in hybrid Bi-CG methods. Computing, 56(2), 141-163. +*/ + +#ifndef EIGEN_BICGSTABL_H +#define EIGEN_BICGSTABL_H + +namespace Eigen { + +namespace internal { +/** \internal Low-level bi conjugate gradient stabilized algorithm with L + additional residual minimization steps \param mat The matrix A \param rhs The + right hand side vector b \param x On input and initial solution, on output + the computed solution. \param precond A preconditioner being able to + efficiently solve for an approximation of Ax=b (regardless of b) \param iters + On input the max number of iteration, on output the number of performed + iterations. \param tol_error On input the tolerance error, on output an + estimation of the relative error. \param L On input Number of additional + GMRES steps to take. If L is too large (~20) instabilities occur. \return + false in the case of numerical issue, for example a break down of BiCGSTABL. +*/ +template +bool bicgstabl(const MatrixType &mat, const Rhs &rhs, Dest &x, const Preconditioner &precond, Index &iters, + typename Dest::RealScalar &tol_error, Index L) { + using numext::abs; + using numext::sqrt; + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + const Index N = rhs.size(); + L = L < x.rows() ? L : x.rows(); + + Index k = 0; + + const RealScalar tol = tol_error; + const Index maxIters = iters; + + typedef Matrix VectorType; + typedef Matrix DenseMatrixType; + + DenseMatrixType rHat(N, L + 1); + DenseMatrixType uHat(N, L + 1); + + // We start with an initial guess x_0 and let us set r_0 as (residual + // calculated from x_0) + VectorType x0 = x; + rHat.col(0) = rhs - mat * x0; // r_0 + + x.setZero(); // This will contain the updates to the solution. + // rShadow is arbritary, but must never be orthogonal to any residual. + VectorType rShadow = VectorType::Random(N); + + VectorType x_prime = x; + + // Redundant: x is already set to 0 + // x.setZero(); + VectorType b_prime = rHat.col(0); + + // Other vectors and scalars initialization + Scalar rho0 = 1.0; + Scalar alpha = 0.0; + Scalar omega = 1.0; + + uHat.col(0).setZero(); + + bool bicg_convergence = false; + + const RealScalar normb = rhs.stableNorm(); + if (internal::isApprox(normb, RealScalar(0))) { + x.setZero(); + iters = 0; + return true; + } + RealScalar normr = rHat.col(0).stableNorm(); + RealScalar Mx = normr; + RealScalar Mr = normr; + + // Keep track of the solution with the lowest residual + RealScalar normr_min = normr; + VectorType x_min = x_prime + x; + + // Criterion for when to apply the group-wise update, conform ref 3. + const RealScalar delta = 0.01; + + bool compute_res = false; + bool update_app = false; + + while (normr > tol * normb && k < maxIters) { + rho0 *= -omega; + + for (Index j = 0; j < L; ++j) { + const Scalar rho1 = rShadow.dot(rHat.col(j)); + + if (!(numext::isfinite)(rho1) || rho0 == RealScalar(0.0)) { + // We cannot continue computing, return the best solution found. + x += x_prime; + + // Check if x is better than the best stored solution thus far. + normr = (rhs - mat * (precond.solve(x) + x0)).stableNorm(); + + if (normr > normr_min || !(numext::isfinite)(normr)) { + // x_min is a better solution than x, return x_min + x = x_min; + normr = normr_min; + } + tol_error = normr / normb; + iters = k; + // x contains the updates to x0, add those back to obtain the solution + x = precond.solve(x); + x += x0; + return (normr < tol * normb); + } + + const Scalar beta = alpha * (rho1 / rho0); + rho0 = rho1; + // Update search directions + uHat.leftCols(j + 1) = rHat.leftCols(j + 1) - beta * uHat.leftCols(j + 1); + uHat.col(j + 1) = mat * precond.solve(uHat.col(j)); + const Scalar sigma = rShadow.dot(uHat.col(j + 1)); + alpha = rho1 / sigma; + // Update residuals + rHat.leftCols(j + 1) -= alpha * uHat.middleCols(1, j + 1); + rHat.col(j + 1) = mat * precond.solve(rHat.col(j)); + // Complete BiCG iteration by updating x + x += alpha * uHat.col(0); + normr = rHat.col(0).stableNorm(); + // Check for early exit + if (normr < tol * normb) { + /* + Convergence was achieved during BiCG step. + Without this check BiCGStab(L) fails for trivial matrices, such as + when the preconditioner already is the inverse, or the input matrix is + identity. + */ + bicg_convergence = true; + break; + } else if (normr < normr_min) { + // We found an x with lower residual, keep this one. + x_min = x + x_prime; + normr_min = normr; + } + } + if (!bicg_convergence) { + /* + The polynomial/minimize residual step. + + QR Householder method for argmin is more stable than (modified) + Gram-Schmidt, in the sense that there is less loss of orthogonality. It + is more accurate than solving the normal equations, since the normal + equations scale with condition number squared. + */ + const VectorType gamma = rHat.rightCols(L).householderQr().solve(rHat.col(0)); + x += rHat.leftCols(L) * gamma; + rHat.col(0) -= rHat.rightCols(L) * gamma; + uHat.col(0) -= uHat.rightCols(L) * gamma; + normr = rHat.col(0).stableNorm(); + omega = gamma(L - 1); + } + if (normr < normr_min) { + // We found an x with lower residual, keep this one. + x_min = x + x_prime; + normr_min = normr; + } + + k++; + + /* + Reliable update part + + The recursively computed residual can deviate from the actual residual + after several iterations. However, computing the residual from the + definition costs extra MVs and should not be done at each iteration. The + reliable update strategy computes the true residual from the definition: + r=b-A*x at strategic intervals. Furthermore a "group wise update" strategy + is used to combine updates, which improves accuracy. + */ + + // Maximum norm of residuals since last update of x. + Mx = numext::maxi(Mx, normr); + // Maximum norm of residuals since last computation of the true residual. + Mr = numext::maxi(Mr, normr); + + if (normr < delta * normb && normb <= Mx) { + update_app = true; + } + + if (update_app || (normr < delta * Mr && normb <= Mr)) { + compute_res = true; + } + + if (bicg_convergence) { + update_app = true; + compute_res = true; + bicg_convergence = false; + } + + if (compute_res) { + // Explicitly compute residual from the definition + + // This is equivalent to the shifted version of rhs - mat * + // (precond.solve(x)+x0) + rHat.col(0) = b_prime - mat * precond.solve(x); + normr = rHat.col(0).stableNorm(); + Mr = normr; + + if (update_app) { + // After the group wise update, the original problem is translated to a + // shifted one. + x_prime += x; + x.setZero(); + b_prime = rHat.col(0); + Mx = normr; + } + } + if (normr < normr_min) { + // We found an x with lower residual, keep this one. + x_min = x + x_prime; + normr_min = normr; + } + + compute_res = false; + update_app = false; + } + + // Convert internal variable to the true solution vector x + x += x_prime; + + normr = (rhs - mat * (precond.solve(x) + x0)).stableNorm(); + if (normr > normr_min || !(numext::isfinite)(normr)) { + // x_min is a better solution than x, return x_min + x = x_min; + normr = normr_min; + } + tol_error = normr / normb; + iters = k; + + // x contains the updates to x0, add those back to obtain the solution + x = precond.solve(x); + x += x0; + return true; +} + +} // namespace internal + +template > +class BiCGSTABL; + +namespace internal { + +template +struct traits> { + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; +}; + +} // namespace internal + +template +class BiCGSTABL : public IterativeSolverBase> { + typedef IterativeSolverBase Base; + using Base::m_error; + using Base::m_info; + using Base::m_isInitialized; + using Base::m_iterations; + using Base::matrix; + Index m_L; + + public: + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + + /** Default constructor. */ + BiCGSTABL() : m_L(2) {} + + /** + Initialize the solver with matrix \a A for further \c Ax=b solving. + + This constructor is a shortcut for the default constructor followed + by a call to compute(). + + \warning this class stores a reference to the matrix A as well as some + precomputed values that depend on it. Therefore, if \a A is changed + this class becomes invalid. Call compute() to update it with the new + matrix A, or modify a copy of A. + */ + template + explicit BiCGSTABL(const EigenBase &A) : Base(A.derived()), m_L(2) {} + + /** \internal */ + /** Loops over the number of columns of b and does the following: + 1. sets the tolerence and maxIterations + 2. Calls the function that has the core solver routine + */ + template + void _solve_vector_with_guess_impl(const Rhs &b, Dest &x) const { + m_iterations = Base::maxIterations(); + + m_error = Base::m_tolerance; + + bool ret = internal::bicgstabl(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error, m_L); + m_info = (!ret) ? NumericalIssue : m_error <= Base::m_tolerance ? Success : NoConvergence; + } + + /** Sets the parameter L, indicating how many minimize residual steps are + * used. Default: 2 */ + void setL(Index L) { + eigen_assert(L >= 1 && "L needs to be positive"); + m_L = L; + } +}; + +} // namespace Eigen + +#endif /* EIGEN_BICGSTABL_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/DGMRES.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/DGMRES.h new file mode 100644 index 0000000000000000000000000000000000000000..0387ef3ce2ba15a706acb181c48d10550cf5226e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/DGMRES.h @@ -0,0 +1,513 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DGMRES_H +#define EIGEN_DGMRES_H + +#include "../../../../Eigen/Eigenvalues" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template< typename MatrixType_, + typename Preconditioner_ = DiagonalPreconditioner > +class DGMRES; + +namespace internal { + +template< typename MatrixType_, typename Preconditioner_> +struct traits > +{ + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; +}; + +/** \brief Computes a permutation vector to have a sorted sequence + * \param vec The vector to reorder. + * \param perm gives the sorted sequence on output. Must be initialized with 0..n-1 + * \param ncut Put the ncut smallest elements at the end of the vector + * WARNING This is an expensive sort, so should be used only + * for small size vectors + * TODO Use modified QuickSplit or std::nth_element to get the smallest values + */ +template +void sortWithPermutation (VectorType& vec, IndexType& perm, typename IndexType::Scalar& ncut) +{ + eigen_assert(vec.size() == perm.size()); + bool flag; + for (Index k = 0; k < ncut; k++) + { + flag = false; + for (Index j = 0; j < vec.size()-1; j++) + { + if ( vec(perm(j)) < vec(perm(j+1)) ) + { + std::swap(perm(j),perm(j+1)); + flag = true; + } + if (!flag) break; // The vector is in sorted order + } + } +} + +} +/** + * \ingroup IterativeLinearSolvers_Module + * \brief A Restarted GMRES with deflation. + * This class implements a modification of the GMRES solver for + * sparse linear systems. The basis is built with modified + * Gram-Schmidt. At each restart, a few approximated eigenvectors + * corresponding to the smallest eigenvalues are used to build a + * preconditioner for the next cycle. This preconditioner + * for deflation can be combined with any other preconditioner, + * the IncompleteLUT for instance. The preconditioner is applied + * at right of the matrix and the combination is multiplicative. + * + * \tparam MatrixType_ the type of the sparse matrix A, can be a dense or a sparse matrix. + * \tparam Preconditioner_ the type of the preconditioner. Default is DiagonalPreconditioner + * Typical usage : + * \code + * SparseMatrix A; + * VectorXd x, b; + * //Fill A and b ... + * DGMRES > solver; + * solver.set_restart(30); // Set restarting value + * solver.setEigenv(1); // Set the number of eigenvalues to deflate + * solver.compute(A); + * x = solver.solve(b); + * \endcode + * + * DGMRES can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * References : + * [1] D. NUENTSA WAKAM and F. PACULL, Memory Efficient Hybrid + * Algebraic Solvers for Linear Systems Arising from Compressible + * Flows, Computers and Fluids, In Press, + * https://doi.org/10.1016/j.compfluid.2012.03.023 + * [2] K. Burrage and J. Erhel, On the performance of various + * adaptive preconditioned GMRES strategies, 5(1998), 101-121. + * [3] J. Erhel, K. Burrage and B. Pohl, Restarted GMRES + * preconditioned by deflation,J. Computational and Applied + * Mathematics, 69(1996), 303-318. + + * + */ +template< typename MatrixType_, typename Preconditioner_> +class DGMRES : public IterativeSolverBase > +{ + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; + using Base::m_tolerance; + public: + using Base::_solve_impl; + using Base::_solve_with_guess_impl; + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::StorageIndex StorageIndex; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + typedef Matrix DenseMatrix; + typedef Matrix DenseRealMatrix; + typedef Matrix DenseVector; + typedef Matrix DenseRealVector; + typedef Matrix, Dynamic, 1> ComplexVector; + + + /** Default constructor. */ + DGMRES() : Base(),m_restart(30),m_neig(0),m_r(0),m_maxNeig(5),m_isDeflAllocated(false),m_isDeflInitialized(false) {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit DGMRES(const EigenBase& A) : Base(A.derived()), m_restart(30),m_neig(0),m_r(0),m_maxNeig(5),m_isDeflAllocated(false),m_isDeflInitialized(false) {} + + ~DGMRES() {} + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + EIGEN_STATIC_ASSERT(Rhs::ColsAtCompileTime==1 || Dest::ColsAtCompileTime==1, YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX); + + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + + dgmres(matrix(), b, x, Base::m_preconditioner); + } + + /** + * Get the restart value + */ + Index restart() { return m_restart; } + + /** + * Set the restart value (default is 30) + */ + void set_restart(const Index restart) { m_restart=restart; } + + /** + * Set the number of eigenvalues to deflate at each restart + */ + void setEigenv(const Index neig) + { + m_neig = neig; + if (neig+1 > m_maxNeig) m_maxNeig = neig+1; // To allow for complex conjugates + } + + /** + * Get the size of the deflation subspace size + */ + Index deflSize() {return m_r; } + + /** + * Set the maximum size of the deflation subspace + */ + void setMaxEigenv(const Index maxNeig) { m_maxNeig = maxNeig; } + + protected: + // DGMRES algorithm + template + void dgmres(const MatrixType& mat,const Rhs& rhs, Dest& x, const Preconditioner& precond) const; + // Perform one cycle of GMRES + template + Index dgmresCycle(const MatrixType& mat, const Preconditioner& precond, Dest& x, DenseVector& r0, RealScalar& beta, const RealScalar& normRhs, Index& nbIts) const; + // Compute data to use for deflation + Index dgmresComputeDeflationData(const MatrixType& mat, const Preconditioner& precond, const Index& it, StorageIndex& neig) const; + // Apply deflation to a vector + template + Index dgmresApplyDeflation(const RhsType& In, DestType& Out) const; + ComplexVector schurValues(const ComplexSchur& schurofH) const; + ComplexVector schurValues(const RealSchur& schurofH) const; + // Init data for deflation + void dgmresInitDeflation(Index& rows) const; + mutable DenseMatrix m_V; // Krylov basis vectors + mutable DenseMatrix m_H; // Hessenberg matrix + mutable DenseMatrix m_Hes; // Initial hessenberg matrix without Givens rotations applied + mutable Index m_restart; // Maximum size of the Krylov subspace + mutable DenseMatrix m_U; // Vectors that form the basis of the invariant subspace + mutable DenseMatrix m_MU; // matrix operator applied to m_U (for next cycles) + mutable DenseMatrix m_T; /* T=U^T*M^{-1}*A*U */ + mutable PartialPivLU m_luT; // LU factorization of m_T + mutable StorageIndex m_neig; //Number of eigenvalues to extract at each restart + mutable Index m_r; // Current number of deflated eigenvalues, size of m_U + mutable Index m_maxNeig; // Maximum number of eigenvalues to deflate + mutable RealScalar m_lambdaN; //Modulus of the largest eigenvalue of A + mutable bool m_isDeflAllocated; + mutable bool m_isDeflInitialized; + + //Adaptive strategy + mutable RealScalar m_smv; // Smaller multiple of the remaining number of steps allowed + mutable bool m_force; // Force the use of deflation at each restart + +}; +/** + * \brief Perform several cycles of restarted GMRES with modified Gram Schmidt, + * + * A right preconditioner is used combined with deflation. + * + */ +template< typename MatrixType_, typename Preconditioner_> +template +void DGMRES::dgmres(const MatrixType& mat,const Rhs& rhs, Dest& x, + const Preconditioner& precond) const +{ + const RealScalar considerAsZero = (std::numeric_limits::min)(); + + RealScalar normRhs = rhs.norm(); + if(normRhs <= considerAsZero) + { + x.setZero(); + m_error = 0; + return; + } + + //Initialization + m_isDeflInitialized = false; + Index n = mat.rows(); + DenseVector r0(n); + Index nbIts = 0; + m_H.resize(m_restart+1, m_restart); + m_Hes.resize(m_restart, m_restart); + m_V.resize(n,m_restart+1); + //Initial residual vector and initial norm + if(x.squaredNorm()==0) + x = precond.solve(rhs); + r0 = rhs - mat * x; + RealScalar beta = r0.norm(); + + m_error = beta/normRhs; + if(m_error < m_tolerance) + m_info = Success; + else + m_info = NoConvergence; + + // Iterative process + while (nbIts < m_iterations && m_info == NoConvergence) + { + dgmresCycle(mat, precond, x, r0, beta, normRhs, nbIts); + + // Compute the new residual vector for the restart + if (nbIts < m_iterations && m_info == NoConvergence) { + r0 = rhs - mat * x; + beta = r0.norm(); + } + } +} + +/** + * \brief Perform one restart cycle of DGMRES + * \param mat The coefficient matrix + * \param precond The preconditioner + * \param x the new approximated solution + * \param r0 The initial residual vector + * \param beta The norm of the residual computed so far + * \param normRhs The norm of the right hand side vector + * \param nbIts The number of iterations + */ +template< typename MatrixType_, typename Preconditioner_> +template +Index DGMRES::dgmresCycle(const MatrixType& mat, const Preconditioner& precond, Dest& x, DenseVector& r0, RealScalar& beta, const RealScalar& normRhs, Index& nbIts) const +{ + //Initialization + DenseVector g(m_restart+1); // Right hand side of the least square problem + g.setZero(); + g(0) = Scalar(beta); + m_V.col(0) = r0/beta; + m_info = NoConvergence; + std::vector >gr(m_restart); // Givens rotations + Index it = 0; // Number of inner iterations + Index n = mat.rows(); + DenseVector tv1(n), tv2(n); //Temporary vectors + while (m_info == NoConvergence && it < m_restart && nbIts < m_iterations) + { + // Apply preconditioner(s) at right + if (m_isDeflInitialized ) + { + dgmresApplyDeflation(m_V.col(it), tv1); // Deflation + tv2 = precond.solve(tv1); + } + else + { + tv2 = precond.solve(m_V.col(it)); // User's selected preconditioner + } + tv1 = mat * tv2; + + // Orthogonalize it with the previous basis in the basis using modified Gram-Schmidt + Scalar coef; + for (Index i = 0; i <= it; ++i) + { + coef = tv1.dot(m_V.col(i)); + tv1 = tv1 - coef * m_V.col(i); + m_H(i,it) = coef; + m_Hes(i,it) = coef; + } + // Normalize the vector + coef = tv1.norm(); + m_V.col(it+1) = tv1/coef; + m_H(it+1, it) = coef; +// m_Hes(it+1,it) = coef; + + // FIXME Check for happy breakdown + + // Update Hessenberg matrix with Givens rotations + for (Index i = 1; i <= it; ++i) + { + m_H.col(it).applyOnTheLeft(i-1,i,gr[i-1].adjoint()); + } + // Compute the new plane rotation + gr[it].makeGivens(m_H(it, it), m_H(it+1,it)); + // Apply the new rotation + m_H.col(it).applyOnTheLeft(it,it+1,gr[it].adjoint()); + g.applyOnTheLeft(it,it+1, gr[it].adjoint()); + + beta = std::abs(g(it+1)); + m_error = beta/normRhs; + // std::cerr << nbIts << " Relative Residual Norm " << m_error << std::endl; + it++; nbIts++; + + if (m_error < m_tolerance) + { + // The method has converged + m_info = Success; + break; + } + } + + // Compute the new coefficients by solving the least square problem +// it++; + //FIXME Check first if the matrix is singular ... zero diagonal + DenseVector nrs(m_restart); + nrs = m_H.topLeftCorner(it,it).template triangularView().solve(g.head(it)); + + // Form the new solution + if (m_isDeflInitialized) + { + tv1 = m_V.leftCols(it) * nrs; + dgmresApplyDeflation(tv1, tv2); + x = x + precond.solve(tv2); + } + else + x = x + precond.solve(m_V.leftCols(it) * nrs); + + // Go for a new cycle and compute data for deflation + if(nbIts < m_iterations && m_info == NoConvergence && m_neig > 0 && (m_r+m_neig) < m_maxNeig) + dgmresComputeDeflationData(mat, precond, it, m_neig); + return 0; + +} + + +template< typename MatrixType_, typename Preconditioner_> +void DGMRES::dgmresInitDeflation(Index& rows) const +{ + m_U.resize(rows, m_maxNeig); + m_MU.resize(rows, m_maxNeig); + m_T.resize(m_maxNeig, m_maxNeig); + m_lambdaN = 0.0; + m_isDeflAllocated = true; +} + +template< typename MatrixType_, typename Preconditioner_> +inline typename DGMRES::ComplexVector DGMRES::schurValues(const ComplexSchur& schurofH) const +{ + return schurofH.matrixT().diagonal(); +} + +template< typename MatrixType_, typename Preconditioner_> +inline typename DGMRES::ComplexVector DGMRES::schurValues(const RealSchur& schurofH) const +{ + const DenseMatrix& T = schurofH.matrixT(); + Index it = T.rows(); + ComplexVector eig(it); + Index j = 0; + while (j < it-1) + { + if (T(j+1,j) ==Scalar(0)) + { + eig(j) = std::complex(T(j,j),RealScalar(0)); + j++; + } + else + { + eig(j) = std::complex(T(j,j),T(j+1,j)); + eig(j+1) = std::complex(T(j,j+1),T(j+1,j+1)); + j++; + } + } + if (j < it-1) eig(j) = std::complex(T(j,j),RealScalar(0)); + return eig; +} + +template< typename MatrixType_, typename Preconditioner_> +Index DGMRES::dgmresComputeDeflationData(const MatrixType& mat, const Preconditioner& precond, const Index& it, StorageIndex& neig) const +{ + // First, find the Schur form of the Hessenberg matrix H + std::conditional_t::IsComplex, ComplexSchur, RealSchur > schurofH; + bool computeU = true; + DenseMatrix matrixQ(it,it); + matrixQ.setIdentity(); + schurofH.computeFromHessenberg(m_Hes.topLeftCorner(it,it), matrixQ, computeU); + + ComplexVector eig(it); + Matrixperm(it); + eig = this->schurValues(schurofH); + + // Reorder the absolute values of Schur values + DenseRealVector modulEig(it); + for (Index j=0; j(it-1)); + internal::sortWithPermutation(modulEig, perm, neig); + + if (!m_lambdaN) + { + m_lambdaN = (std::max)(modulEig.maxCoeff(), m_lambdaN); + } + //Count the real number of extracted eigenvalues (with complex conjugates) + Index nbrEig = 0; + while (nbrEig < neig) + { + if(eig(perm(it-nbrEig-1)).imag() == RealScalar(0)) nbrEig++; + else nbrEig += 2; + } + // Extract the Schur vectors corresponding to the smallest Ritz values + DenseMatrix Sr(it, nbrEig); + Sr.setZero(); + for (Index j = 0; j < nbrEig; j++) + { + Sr.col(j) = schurofH.matrixU().col(perm(it-j-1)); + } + + // Form the Schur vectors of the initial matrix using the Krylov basis + DenseMatrix X; + X = m_V.leftCols(it) * Sr; + if (m_r) + { + // Orthogonalize X against m_U using modified Gram-Schmidt + for (Index j = 0; j < nbrEig; j++) + for (Index k =0; k < m_r; k++) + X.col(j) = X.col(j) - (m_U.col(k).dot(X.col(j)))*m_U.col(k); + } + + // Compute m_MX = A * M^-1 * X + Index m = m_V.rows(); + if (!m_isDeflAllocated) + dgmresInitDeflation(m); + DenseMatrix MX(m, nbrEig); + DenseVector tv1(m); + for (Index j = 0; j < nbrEig; j++) + { + tv1 = mat * X.col(j); + MX.col(j) = precond.solve(tv1); + } + + //Update m_T = [U'MU U'MX; X'MU X'MX] + m_T.block(m_r, m_r, nbrEig, nbrEig) = X.transpose() * MX; + if(m_r) + { + m_T.block(0, m_r, m_r, nbrEig) = m_U.leftCols(m_r).transpose() * MX; + m_T.block(m_r, 0, nbrEig, m_r) = X.transpose() * m_MU.leftCols(m_r); + } + + // Save X into m_U and m_MX in m_MU + for (Index j = 0; j < nbrEig; j++) m_U.col(m_r+j) = X.col(j); + for (Index j = 0; j < nbrEig; j++) m_MU.col(m_r+j) = MX.col(j); + // Increase the size of the invariant subspace + m_r += nbrEig; + + // Factorize m_T into m_luT + m_luT.compute(m_T.topLeftCorner(m_r, m_r)); + + //FIXME CHeck if the factorization was correctly done (nonsingular matrix) + m_isDeflInitialized = true; + return 0; +} +template +template +Index DGMRES::dgmresApplyDeflation(const RhsType &x, DestType &y) const +{ + DenseVector x1 = m_U.leftCols(m_r).transpose() * x; + y = x + m_U.leftCols(m_r) * ( m_lambdaN * m_luT.solve(x1) - x1); + return 0; +} + +} // end namespace Eigen +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/GMRES.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/GMRES.h new file mode 100644 index 0000000000000000000000000000000000000000..741d9fe71ec7055766efb9e0474bb60a4a3ebab1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/GMRES.h @@ -0,0 +1,337 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Gael Guennebaud +// Copyright (C) 2012, 2014 Kolja Brix +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GMRES_H +#define EIGEN_GMRES_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** +* Generalized Minimal Residual Algorithm based on the +* Arnoldi algorithm implemented with Householder reflections. +* +* Parameters: +* \param mat matrix of linear system of equations +* \param rhs right hand side vector of linear system of equations +* \param x on input: initial guess, on output: solution +* \param precond preconditioner used +* \param iters on input: maximum number of iterations to perform +* on output: number of iterations performed +* \param restart number of iterations for a restart +* \param tol_error on input: relative residual tolerance +* on output: residuum achieved +* +* \sa IterativeMethods::bicgstab() +* +* +* For references, please see: +* +* Saad, Y. and Schultz, M. H. +* GMRES: A Generalized Minimal Residual Algorithm for Solving Nonsymmetric Linear Systems. +* SIAM J.Sci.Stat.Comp. 7, 1986, pp. 856 - 869. +* +* Saad, Y. +* Iterative Methods for Sparse Linear Systems. +* Society for Industrial and Applied Mathematics, Philadelphia, 2003. +* +* Walker, H. F. +* Implementations of the GMRES method. +* Comput.Phys.Comm. 53, 1989, pp. 311 - 320. +* +* Walker, H. F. +* Implementation of the GMRES Method using Householder Transformations. +* SIAM J.Sci.Stat.Comp. 9, 1988, pp. 152 - 163. +* +*/ +template +bool gmres(const MatrixType & mat, const Rhs & rhs, Dest & x, const Preconditioner & precond, + Index &iters, const Index &restart, typename Dest::RealScalar & tol_error) { + + using std::sqrt; + using std::abs; + + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix < Scalar, Dynamic, 1 > VectorType; + typedef Matrix < Scalar, Dynamic, Dynamic, ColMajor> FMatrixType; + + const RealScalar considerAsZero = (std::numeric_limits::min)(); + + if(rhs.norm() <= considerAsZero) + { + x.setZero(); + tol_error = 0; + return true; + } + + RealScalar tol = tol_error; + const Index maxIters = iters; + iters = 0; + + const Index m = mat.rows(); + + // residual and preconditioned residual + VectorType p0 = rhs - mat*x; + VectorType r0 = precond.solve(p0); + + const RealScalar r0Norm = r0.norm(); + + // is initial guess already good enough? + if(r0Norm == 0) + { + tol_error = 0; + return true; + } + + // storage for Hessenberg matrix and Householder data + FMatrixType H = FMatrixType::Zero(m, restart + 1); + VectorType w = VectorType::Zero(restart + 1); + VectorType tau = VectorType::Zero(restart + 1); + + // storage for Jacobi rotations + std::vector < JacobiRotation < Scalar > > G(restart); + + // storage for temporaries + VectorType t(m), v(m), workspace(m), x_new(m); + + // generate first Householder vector + Ref H0_tail = H.col(0).tail(m - 1); + RealScalar beta; + r0.makeHouseholder(H0_tail, tau.coeffRef(0), beta); + w(0) = Scalar(beta); + + for (Index k = 1; k <= restart; ++k) + { + ++iters; + + v = VectorType::Unit(m, k - 1); + + // apply Householder reflections H_{1} ... H_{k-1} to v + // TODO: use a HouseholderSequence + for (Index i = k - 1; i >= 0; --i) { + v.tail(m - i).applyHouseholderOnTheLeft(H.col(i).tail(m - i - 1), tau.coeffRef(i), workspace.data()); + } + + // apply matrix M to v: v = mat * v; + t.noalias() = mat * v; + v = precond.solve(t); + + // apply Householder reflections H_{k-1} ... H_{1} to v + // TODO: use a HouseholderSequence + for (Index i = 0; i < k; ++i) { + v.tail(m - i).applyHouseholderOnTheLeft(H.col(i).tail(m - i - 1), tau.coeffRef(i), workspace.data()); + } + + if (v.tail(m - k).norm() != 0.0) + { + if (k <= restart) + { + // generate new Householder vector + Ref Hk_tail = H.col(k).tail(m - k - 1); + v.tail(m - k).makeHouseholder(Hk_tail, tau.coeffRef(k), beta); + + // apply Householder reflection H_{k} to v + v.tail(m - k).applyHouseholderOnTheLeft(Hk_tail, tau.coeffRef(k), workspace.data()); + } + } + + if (k > 1) + { + for (Index i = 0; i < k - 1; ++i) + { + // apply old Givens rotations to v + v.applyOnTheLeft(i, i + 1, G[i].adjoint()); + } + } + + if (k y = w.head(k); + H.topLeftCorner(k, k).template triangularView ().solveInPlace(y); + + // use Horner-like scheme to calculate solution vector + x_new.setZero(); + for (Index i = k - 1; i >= 0; --i) + { + x_new(i) += y(i); + // apply Householder reflection H_{i} to x_new + x_new.tail(m - i).applyHouseholderOnTheLeft(H.col(i).tail(m - i - 1), tau.coeffRef(i), workspace.data()); + } + + x += x_new; + + if(stop) + { + return true; + } + else + { + k=0; + + // reset data for restart + p0.noalias() = rhs - mat*x; + r0 = precond.solve(p0); + + // clear Hessenberg matrix and Householder data + H.setZero(); + w.setZero(); + tau.setZero(); + + // generate first Householder vector + r0.makeHouseholder(H0_tail, tau.coeffRef(0), beta); + w(0) = Scalar(beta); + } + } + } + + return false; + +} + +} + +template< typename MatrixType_, + typename Preconditioner_ = DiagonalPreconditioner > +class GMRES; + +namespace internal { + +template< typename MatrixType_, typename Preconditioner_> +struct traits > +{ + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; +}; + +} + +/** \ingroup IterativeLinearSolvers_Module + * \brief A GMRES solver for sparse square problems + * + * This class allows to solve for A.x = b sparse linear problems using a generalized minimal + * residual method. The vectors x and b can be either dense or sparse. + * + * \tparam MatrixType_ the type of the sparse matrix A, can be a dense or a sparse matrix. + * \tparam Preconditioner_ the type of the preconditioner. Default is DiagonalPreconditioner + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * This class can be used as the direct solver classes. Here is a typical usage example: + * \code + * int n = 10000; + * VectorXd x(n), b(n); + * SparseMatrix A(n,n); + * // fill A and b + * GMRES > solver(A); + * x = solver.solve(b); + * std::cout << "#iterations: " << solver.iterations() << std::endl; + * std::cout << "estimated error: " << solver.error() << std::endl; + * // update b, and solve again + * x = solver.solve(b); + * \endcode + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * GMRES can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ +template< typename MatrixType_, typename Preconditioner_> +class GMRES : public IterativeSolverBase > +{ + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; + +private: + Index m_restart; + +public: + using Base::_solve_impl; + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + +public: + + /** Default constructor. */ + GMRES() : Base(), m_restart(30) {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit GMRES(const EigenBase& A) : Base(A.derived()), m_restart(30) {} + + ~GMRES() {} + + /** Get the number of iterations after that a restart is performed. + */ + Index get_restart() { return m_restart; } + + /** Set the number of iterations after that a restart is performed. + * \param restart number of iterations for a restarti, default is 30. + */ + void set_restart(const Index restart) { m_restart=restart; } + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + bool ret = internal::gmres(matrix(), b, x, Base::m_preconditioner, m_iterations, m_restart, m_error); + m_info = (!ret) ? NumericalIssue + : m_error <= Base::m_tolerance ? Success + : NoConvergence; + } + +protected: + +}; + +} // end namespace Eigen + +#endif // EIGEN_GMRES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRS.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRS.h new file mode 100644 index 0000000000000000000000000000000000000000..d8f7a32dc655c00c45ce204cc3bf722f1c59768e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRS.h @@ -0,0 +1,394 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2020 Chris Schoutrop +// Copyright (C) 2020 Jens Wehner +// Copyright (C) 2020 Jan van Dijk +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_IDRS_H +#define EIGEN_IDRS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { +/** \internal Low-level Induced Dimension Reduction algorithm + \param A The matrix A + \param b The right hand side vector b + \param x On input and initial solution, on output the computed solution. + \param precond A preconditioner being able to efficiently solve for an + approximation of Ax=b (regardless of b) + \param iter On input the max number of iteration, on output the number of performed iterations. + \param relres On input the tolerance error, on output an estimation of the relative error. + \param S On input Number of the dimension of the shadow space. + \param smoothing switches residual smoothing on. + \param angle small omega lead to faster convergence at the expense of numerical stability + \param replacement switches on a residual replacement strategy to increase accuracy of residual at the + expense of more Mat*vec products \return false in the case of numerical issue, for example a break down of IDRS. +*/ +template +typename Vector::Scalar omega(const Vector& t, const Vector& s, RealScalar angle) { + using numext::abs; + typedef typename Vector::Scalar Scalar; + const RealScalar ns = s.stableNorm(); + const RealScalar nt = t.stableNorm(); + const Scalar ts = t.dot(s); + const RealScalar rho = abs(ts / (nt * ns)); + + if (rho < angle) { + if (ts == Scalar(0)) { + return Scalar(0); + } + // Original relation for om is given by + // om = om * angle / rho; + // To alleviate potential (near) division by zero this can be rewritten as + // om = angle * (ns / nt) * (ts / abs(ts)) = angle * (ns / nt) * sgn(ts) + return angle * (ns / nt) * (ts / abs(ts)); + } + return ts / (nt * nt); +} + +template +bool idrs(const MatrixType& A, const Rhs& b, Dest& x, const Preconditioner& precond, Index& iter, + typename Dest::RealScalar& relres, Index S, bool smoothing, typename Dest::RealScalar angle, + bool replacement) { + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix VectorType; + typedef Matrix DenseMatrixType; + const Index N = b.size(); + S = S < x.rows() ? S : x.rows(); + const RealScalar tol = relres; + const Index maxit = iter; + + bool trueres = false; + + FullPivLU lu_solver; + + DenseMatrixType P; + { + HouseholderQR qr(DenseMatrixType::Random(N, S)); + P = (qr.householderQ() * DenseMatrixType::Identity(N, S)); + } + + const RealScalar normb = b.stableNorm(); + + if (internal::isApprox(normb, RealScalar(0))) { + // Solution is the zero vector + x.setZero(); + iter = 0; + relres = 0; + return true; + } + // from http://homepage.tudelft.nl/1w5b5/IDRS/manual.pdf + // A peak in the residual is considered dangerously high if‖ri‖/‖b‖> C(tol/epsilon). + // With epsilon the relative machine precision. The factor tol/epsilon corresponds + // to the size of a finite precision number that is so large that the absolute + // round-off error in this number, when propagated through the process, makes it + // impossible to achieve the required accuracy. The factor C accounts for the + // accumulation of round-off errors. This parameter has been set to 10^{-3}. + // mp is epsilon/C 10^3 * eps is very conservative, so normally no residual + // replacements will take place. It only happens if things go very wrong. Too many + // restarts may ruin the convergence. + const RealScalar mp = RealScalar(1e3) * NumTraits::epsilon(); + + // Compute initial residual + const RealScalar tolb = tol * normb; // Relative tolerance + VectorType r = b - A * x; + + VectorType x_s, r_s; + + if (smoothing) { + x_s = x; + r_s = r; + } + + RealScalar normr = r.stableNorm(); + + if (normr <= tolb) { + // Initial guess is a good enough solution + iter = 0; + relres = normr / normb; + return true; + } + + DenseMatrixType G = DenseMatrixType::Zero(N, S); + DenseMatrixType U = DenseMatrixType::Zero(N, S); + DenseMatrixType M = DenseMatrixType::Identity(S, S); + VectorType t(N), v(N); + Scalar om = 1.; + + // Main iteration loop, guild G-spaces: + iter = 0; + + while (normr > tolb && iter < maxit) { + // New right hand size for small system: + VectorType f = (r.adjoint() * P).adjoint(); + + for (Index k = 0; k < S; ++k) { + // Solve small system and make v orthogonal to P: + // c = M(k:s,k:s)\f(k:s); + lu_solver.compute(M.block(k, k, S - k, S - k)); + VectorType c = lu_solver.solve(f.segment(k, S - k)); + // v = r - G(:,k:s)*c; + v = r - G.rightCols(S - k) * c; + // Preconditioning + v = precond.solve(v); + + // Compute new U(:,k) and G(:,k), G(:,k) is in space G_j + U.col(k) = U.rightCols(S - k) * c + om * v; + G.col(k) = A * U.col(k); + + // Bi-Orthogonalise the new basis vectors: + for (Index i = 0; i < k - 1; ++i) { + // alpha = ( P(:,i)'*G(:,k) )/M(i,i); + Scalar alpha = P.col(i).dot(G.col(k)) / M(i, i); + G.col(k) = G.col(k) - alpha * G.col(i); + U.col(k) = U.col(k) - alpha * U.col(i); + } + + // New column of M = P'*G (first k-1 entries are zero) + // M(k:s,k) = (G(:,k)'*P(:,k:s))'; + M.block(k, k, S - k, 1) = (G.col(k).adjoint() * P.rightCols(S - k)).adjoint(); + + if (internal::isApprox(M(k, k), Scalar(0))) { + return false; + } + + // Make r orthogonal to q_i, i = 0..k-1 + Scalar beta = f(k) / M(k, k); + r = r - beta * G.col(k); + x = x + beta * U.col(k); + normr = r.stableNorm(); + + if (replacement && normr > tolb / mp) { + trueres = true; + } + + // Smoothing: + if (smoothing) { + t = r_s - r; + // gamma is a Scalar, but the conversion is not allowed + Scalar gamma = t.dot(r_s) / t.stableNorm(); + r_s = r_s - gamma * t; + x_s = x_s - gamma * (x_s - x); + normr = r_s.stableNorm(); + } + + if (normr < tolb || iter == maxit) { + break; + } + + // New f = P'*r (first k components are zero) + if (k < S - 1) { + f.segment(k + 1, S - (k + 1)) = f.segment(k + 1, S - (k + 1)) - beta * M.block(k + 1, k, S - (k + 1), 1); + } + } // end for + + if (normr < tolb || iter == maxit) { + break; + } + + // Now we have sufficient vectors in G_j to compute residual in G_j+1 + // Note: r is already perpendicular to P so v = r + // Preconditioning + v = r; + v = precond.solve(v); + + // Matrix-vector multiplication: + t = A * v; + + // Computation of a new omega + om = internal::omega(t, r, angle); + + if (om == RealScalar(0.0)) { + return false; + } + + r = r - om * t; + x = x + om * v; + normr = r.stableNorm(); + + if (replacement && normr > tolb / mp) { + trueres = true; + } + + // Residual replacement? + if (trueres && normr < normb) { + r = b - A * x; + trueres = false; + } + + // Smoothing: + if (smoothing) { + t = r_s - r; + Scalar gamma = t.dot(r_s) / t.stableNorm(); + r_s = r_s - gamma * t; + x_s = x_s - gamma * (x_s - x); + normr = r_s.stableNorm(); + } + + iter++; + + } // end while + + if (smoothing) { + x = x_s; + } + relres = normr / normb; + return true; +} + +} // namespace internal + +template > +class IDRS; + +namespace internal { + +template +struct traits > { + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; +}; + +} // namespace internal + +/** \ingroup IterativeLinearSolvers_Module + * \brief The Induced Dimension Reduction method (IDR(s)) is a short-recurrences Krylov method for sparse square + * problems. + * + * This class allows to solve for A.x = b sparse linear problems. The vectors x and b can be either dense or sparse. + * he Induced Dimension Reduction method, IDR(), is a robust and efficient short-recurrence Krylov subspace method for + * solving large nonsymmetric systems of linear equations. + * + * For indefinite systems IDR(S) outperforms both BiCGStab and BiCGStab(L). Additionally, IDR(S) can handle matrices + * with complex eigenvalues more efficiently than BiCGStab. + * + * Many problems that do not converge for BiCGSTAB converge for IDR(s) (for larger values of s). And if both methods + * converge the convergence for IDR(s) is typically much faster for difficult systems (for example indefinite problems). + * + * IDR(s) is a limited memory finite termination method. In exact arithmetic it converges in at most N+N/s iterations, + * with N the system size. It uses a fixed number of 4+3s vector. In comparison, BiCGSTAB terminates in 2N iterations + * and uses 7 vectors. GMRES terminates in at most N iterations, and uses I+3 vectors, with I the number of iterations. + * Restarting GMRES limits the memory consumption, but destroys the finite termination property. + * + * \tparam MatrixType_ the type of the sparse matrix A, can be a dense or a sparse matrix. + * \tparam Preconditioner_ the type of the preconditioner. Default is DiagonalPreconditioner + * + * \implsparsesolverconcept + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * The tolerance corresponds to the relative residual error: |Ax-b|/|b| + * + * \b Performance: when using sparse matrices, best performance is achied for a row-major sparse matrix format. + * Moreover, in this case multi-threading can be exploited if the user code is compiled with OpenMP enabled. + * See \ref TopicMultiThreading for details. + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * IDR(s) can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ +template +class IDRS : public IterativeSolverBase > { + public: + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + + private: + typedef IterativeSolverBase Base; + using Base::m_error; + using Base::m_info; + using Base::m_isInitialized; + using Base::m_iterations; + using Base::matrix; + Index m_S; + bool m_smoothing; + RealScalar m_angle; + bool m_residual; + + public: + /** Default constructor. */ + IDRS() : m_S(4), m_smoothing(false), m_angle(RealScalar(0.7)), m_residual(false) {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + + This constructor is a shortcut for the default constructor followed + by a call to compute(). + + \warning this class stores a reference to the matrix A as well as some + precomputed values that depend on it. Therefore, if \a A is changed + this class becomes invalid. Call compute() to update it with the new + matrix A, or modify a copy of A. + */ + template + explicit IDRS(const EigenBase& A) + : Base(A.derived()), m_S(4), m_smoothing(false), m_angle(RealScalar(0.7)), m_residual(false) {} + + /** \internal */ + /** Loops over the number of columns of b and does the following: + 1. sets the tolerance and maxIterations + 2. Calls the function that has the core solver routine + */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const { + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + + bool ret = internal::idrs(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error, m_S, m_smoothing, m_angle, + m_residual); + + m_info = (!ret) ? NumericalIssue : m_error <= Base::m_tolerance ? Success : NoConvergence; + } + + /** Sets the parameter S, indicating the dimension of the shadow space. Default is 4*/ + void setS(Index S) { + if (S < 1) { + S = 4; + } + + m_S = S; + } + + /** Switches off and on smoothing. + Residual smoothing results in monotonically decreasing residual norms at + the expense of two extra vectors of storage and a few extra vector + operations. Although monotonic decrease of the residual norms is a + desirable property, the rate of convergence of the unsmoothed process and + the smoothed process is basically the same. Default is off */ + void setSmoothing(bool smoothing) { m_smoothing = smoothing; } + + /** The angle must be a real scalar. In IDR(s), a value for the + iteration parameter omega must be chosen in every s+1th step. The most + natural choice is to select a value to minimize the norm of the next residual. + This corresponds to the parameter omega = 0. In practice, this may lead to + values of omega that are so small that the other iteration parameters + cannot be computed with sufficient accuracy. In such cases it is better to + increase the value of omega sufficiently such that a compromise is reached + between accurate computations and reduction of the residual norm. The + parameter angle =0.7 (”maintaining the convergence strategy”) + results in such a compromise. */ + void setAngle(RealScalar angle) { m_angle = angle; } + + /** The parameter replace is a logical that determines whether a + residual replacement strategy is employed to increase the accuracy of the + solution. */ + void setResidualUpdate(bool update) { m_residual = update; } +}; + +} // namespace Eigen + +#endif /* EIGEN_IDRS_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRSTABL.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRSTABL.h new file mode 100644 index 0000000000000000000000000000000000000000..712c17181b69f7819a32e76d43262005431bc690 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IDRSTABL.h @@ -0,0 +1,476 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2020 Chris Schoutrop +// Copyright (C) 2020 Mischa Senders +// Copyright (C) 2020 Lex Kuijpers +// Copyright (C) 2020 Jens Wehner +// Copyright (C) 2020 Jan van Dijk +// Copyright (C) 2020 Adithya Vijaykumar +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +/* + +The IDR(S)Stab(L) method is a combination of IDR(S) and BiCGStab(L) + +This implementation of IDRSTABL is based on +1. Aihara, K., Abe, K., & Ishiwata, E. (2014). A variant of IDRstab with +reliable update strategies for solving sparse linear systems. Journal of +Computational and Applied Mathematics, 259, 244-258. + doi:10.1016/j.cam.2013.08.028 + 2. Aihara, K., Abe, K., & Ishiwata, E. (2015). Preconditioned +IDRSTABL Algorithms for Solving Nonsymmetric Linear Systems. International +Journal of Applied Mathematics, 45(3). + 3. Saad, Y. (2003). Iterative Methods for Sparse Linear Systems: +Second Edition. Philadelphia, PA: SIAM. + 4. Sonneveld, P., & Van Gijzen, M. B. (2009). IDR(s): A Family +of Simple and Fast Algorithms for Solving Large Nonsymmetric Systems of Linear +Equations. SIAM Journal on Scientific Computing, 31(2), 1035-1062. + doi:10.1137/070685804 + 5. Sonneveld, P. (2012). On the convergence behavior of IDR (s) +and related methods. SIAM Journal on Scientific Computing, 34(5), A2576-A2598. + + Right-preconditioning based on Ref. 3 is implemented here. +*/ + +#ifndef EIGEN_IDRSTABL_H +#define EIGEN_IDRSTABL_H + +namespace Eigen { + +namespace internal { + +template +bool idrstabl(const MatrixType &mat, const Rhs &rhs, Dest &x, const Preconditioner &precond, Index &iters, + typename Dest::RealScalar &tol_error, Index L, Index S) { + /* + Setup and type definitions. + */ + using numext::abs; + using numext::sqrt; + typedef typename Dest::Scalar Scalar; + typedef typename Dest::RealScalar RealScalar; + typedef Matrix VectorType; + typedef Matrix DenseMatrixType; + + const Index N = x.rows(); + + Index k = 0; // Iteration counter + const Index maxIters = iters; + + const RealScalar rhs_norm = rhs.stableNorm(); + const RealScalar tol = tol_error * rhs_norm; + + if (rhs_norm == 0) { + /* + If b==0, then the exact solution is x=0. + rhs_norm is needed for other calculations anyways, this exit is a freebie. + */ + x.setZero(); + tol_error = 0.0; + return true; + } + // Construct decomposition objects beforehand. + FullPivLU lu_solver; + + if (S >= N || L >= N) { + /* + The matrix is very small, or the choice of L and S is very poor + in that case solving directly will be best. + */ + lu_solver.compute(DenseMatrixType(mat)); + x = lu_solver.solve(rhs); + tol_error = (rhs - mat * x).stableNorm() / rhs_norm; + return true; + } + + // Define maximum sizes to prevent any reallocation later on. + DenseMatrixType u(N, L + 1); + DenseMatrixType r(N, L + 1); + + DenseMatrixType V(N * (L + 1), S); + + VectorType alpha(S); + VectorType gamma(L); + VectorType update(N); + + /* + Main IDRSTABL algorithm + */ + // Set up the initial residual + VectorType x0 = x; + r.col(0) = rhs - mat * x; + x.setZero(); // The final solution will be x0+x + + tol_error = r.col(0).stableNorm(); + + // FOM = Full orthogonalisation method + DenseMatrixType h_FOM = DenseMatrixType::Zero(S, S - 1); + + // Construct an initial U matrix of size N x S + DenseMatrixType U(N * (L + 1), S); + for (Index col_index = 0; col_index < S; ++col_index) { + // Arnoldi-like process to generate a set of orthogonal vectors spanning + // {u,A*u,A*A*u,...,A^(S-1)*u}. This construction can be combined with the + // Full Orthogonalization Method (FOM) from Ref.3 to provide a possible + // early exit with no additional MV. + if (col_index != 0) { + /* + Modified Gram-Schmidt strategy: + */ + VectorType w = mat * precond.solve(u.col(0)); + for (Index i = 0; i < col_index; ++i) { + auto v = U.col(i).head(N); + h_FOM(i, col_index - 1) = v.dot(w); + w -= h_FOM(i, col_index - 1) * v; + } + u.col(0) = w; + h_FOM(col_index, col_index - 1) = u.col(0).stableNorm(); + + if (abs(h_FOM(col_index, col_index - 1)) != RealScalar(0)) { + /* + This only happens if u is NOT exactly zero. In case it is exactly zero + it would imply that that this u has no component in the direction of the + current residual. + + By then setting u to zero it will not contribute any further (as it + should). Whereas attempting to normalize results in division by zero. + + Such cases occur if: + 1. The basis of dimension 1) { + // Check for early FOM exit. + Scalar beta = r.col(0).stableNorm(); + VectorType e1 = VectorType::Zero(S - 1); + e1(0) = beta; + lu_solver.compute(h_FOM.topLeftCorner(S - 1, S - 1)); + VectorType y = lu_solver.solve(e1); + VectorType x2 = x + U.topLeftCorner(N, S - 1) * y; + + // Using proposition 6.7 in Saad, one MV can be saved to calculate the + // residual + RealScalar FOM_residual = (h_FOM(S - 1, S - 2) * y(S - 2) * U.col(S - 1).head(N)).stableNorm(); + + if (FOM_residual < tol) { + // Exit, the FOM algorithm was already accurate enough + iters = k; + // Convert back to the unpreconditioned solution + x = precond.solve(x2); + // x contains the updates to x0, add those back to obtain the solution + x += x0; + tol_error = FOM_residual / rhs_norm; + return true; + } + } + + /* + Select an initial (N x S) matrix R0. + 1. Generate random R0, orthonormalize the result. + 2. This results in R0, however to save memory and compute we only need the + adjoint of R0. This is given by the matrix R_T.\ Additionally, the matrix + (mat.adjoint()*R_tilde).adjoint()=R_tilde.adjoint()*mat by the + anti-distributivity property of the adjoint. This results in AR_T, which is + constant if R_T does not have to be regenerated and can be precomputed. + Based on reference 4, this has zero probability in exact arithmetic. + */ + + // Original IDRSTABL and Kensuke choose S random vectors: + const HouseholderQR qr(DenseMatrixType::Random(N, S)); + DenseMatrixType R_T = (qr.householderQ() * DenseMatrixType::Identity(N, S)).adjoint(); + DenseMatrixType AR_T = DenseMatrixType(R_T * mat); + + // Pre-allocate sigma. + DenseMatrixType sigma(S, S); + + bool reset_while = false; // Should the while loop be reset for some reason? + + while (k < maxIters) { + for (Index j = 1; j <= L; ++j) { + /* + The IDR Step + */ + // Construction of the sigma-matrix, and the decomposition of sigma. + for (Index i = 0; i < S; ++i) { + sigma.col(i).noalias() = AR_T * precond.solve(U.block(N * (j - 1), i, N, 1)); + } + + lu_solver.compute(sigma); + // Obtain the update coefficients alpha + if (j == 1) { + // alpha=inverse(sigma)*(R_T*r_0); + alpha.noalias() = lu_solver.solve(R_T * r.col(0)); + } else { + // alpha=inverse(sigma)*(AR_T*r_{j-2}) + alpha.noalias() = lu_solver.solve(AR_T * precond.solve(r.col(j - 2))); + } + + // Obtain new solution and residual from this update + update.noalias() = U.topRows(N) * alpha; + r.col(0) -= mat * precond.solve(update); + x += update; + + for (Index i = 1; i <= j - 2; ++i) { + // This only affects the case L>2 + r.col(i) -= U.block(N * (i + 1), 0, N, S) * alpha; + } + if (j > 1) { + // r=[r;A*r_{j-2}] + r.col(j - 1).noalias() = mat * precond.solve(r.col(j - 2)); + } + tol_error = r.col(0).stableNorm(); + + if (tol_error < tol) { + // If at this point the algorithm has converged, exit. + reset_while = true; + break; + } + + bool break_normalization = false; + for (Index q = 1; q <= S; ++q) { + if (q == 1) { + // u = r; + u.leftCols(j + 1) = r.leftCols(j + 1); + } else { + // u=[u_1;u_2;...;u_j] + u.leftCols(j) = u.middleCols(1, j); + } + + // Obtain the update coefficients beta implicitly + // beta=lu_sigma.solve(AR_T * u.block(N * (j - 1), 0, N, 1) + u.reshaped().head(u.rows() * j) -= U.topRows(N * j) * lu_solver.solve(AR_T * precond.solve(u.col(j - 1))); + + // u=[u;Au_{j-1}] + u.col(j).noalias() = mat * precond.solve(u.col(j - 1)); + + // Orthonormalize u_j to the columns of V_j(:,1:q-1) + if (q > 1) { + /* + Modified Gram-Schmidt-like procedure to make u orthogonal to the + columns of V from Ref. 1. + + The vector mu from Ref. 1 is obtained implicitly: + mu=V.block(N * j, 0, N, q - 1).adjoint() * u.block(N * j, 0, N, 1). + */ + for (Index i = 0; i <= q - 2; ++i) { + auto v = V.col(i).segment(N * j, N); + Scalar h = v.squaredNorm(); + h = v.dot(u.col(j)) / h; + u.reshaped().head(u.rows() * (j + 1)) -= h * V.block(0, i, N * (j + 1), 1); + } + } + // Normalize u and assign to a column of V + Scalar normalization_constant = u.col(j).stableNorm(); + // If u is exactly zero, this will lead to a NaN. Small, non-zero u is + // fine. + if (normalization_constant == RealScalar(0.0)) { + break_normalization = true; + break; + } else { + u.leftCols(j + 1) /= normalization_constant; + } + + V.block(0, q - 1, N * (j + 1), 1).noalias() = u.reshaped().head(u.rows() * (j + 1)); + } + + if (break_normalization == false) { + U = V; + } + } + if (reset_while) { + break; + } + + // r=[r;mat*r_{L-1}] + r.col(L).noalias() = mat * precond.solve(r.col(L - 1)); + + /* + The polynomial step + */ + ColPivHouseholderQR qr_solver(r.rightCols(L)); + gamma.noalias() = qr_solver.solve(r.col(0)); + + // Update solution and residual using the "minimized residual coefficients" + update.noalias() = r.leftCols(L) * gamma; + x += update; + r.col(0) -= mat * precond.solve(update); + + // Update iteration info + ++k; + tol_error = r.col(0).stableNorm(); + + if (tol_error < tol) { + // Slightly early exit by moving the criterion before the update of U, + // after the main while loop the result of that calculation would not be + // needed. + break; + } + + /* + U=U0-sum(gamma_j*U_j) + Consider the first iteration. Then U only contains U0, so at the start of + the while-loop U should be U0. Therefore only the first N rows of U have to + be updated. + */ + for (Index i = 1; i <= L; ++i) { + U.topRows(N) -= U.block(N * i, 0, N, S) * gamma(i - 1); + } + } + + /* + Exit after the while loop terminated. + */ + iters = k; + // Convert back to the unpreconditioned solution + x = precond.solve(x); + // x contains the updates to x0, add those back to obtain the solution + x += x0; + tol_error = tol_error / rhs_norm; + return true; +} + +} // namespace internal + +template > +class IDRSTABL; + +namespace internal { + +template +struct traits> { + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; +}; + +} // namespace internal + +/** \ingroup IterativeLinearSolvers_Module + * \brief The IDR(s)STAB(l) is a combination of IDR(s) and BiCGSTAB(l). It is a + * short-recurrences Krylov method for sparse square problems. It can outperform + * both IDR(s) and BiCGSTAB(l). IDR(s)STAB(l) generally closely follows the + * optimal GMRES convergence in terms of the number of Matrix-Vector products. + * However, without the increasing cost per iteration of GMRES. IDR(s)STAB(l) is + * suitable for both indefinite systems and systems with complex eigenvalues. + * + * This class allows solving for A.x = b sparse linear problems. The vectors x + * and b can be either dense or sparse. + * + * \tparam MatrixType_ the type of the sparse matrix A, can be a dense or a + * sparse matrix. \tparam Preconditioner_ the type of the preconditioner. + * Default is DiagonalPreconditioner + * + * \implsparsesolverconcept + * + * The maximum number of iterations and tolerance value can be controlled via + * the setMaxIterations() and setTolerance() methods. The defaults are the size + * of the problem for the maximum number of iterations and + * NumTraits::epsilon() for the tolerance. + * + * The tolerance is the maximum relative residual error: |Ax-b|/|b| for which + * the linear system is considered solved. + * + * \b Performance: When using sparse matrices, best performance is achieved for + * a row-major sparse matrix format. Moreover, in this case multi-threading can + * be exploited if the user code is compiled with OpenMP enabled. See \ref + * TopicMultiThreading for details. + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * IDR(s)STAB(l) can also be used in a matrix-free context, see the following + * \link MatrixfreeSolverExample example \endlink. + * + * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ + +template +class IDRSTABL : public IterativeSolverBase> { + typedef IterativeSolverBase Base; + using Base::m_error; + using Base::m_info; + using Base::m_isInitialized; + using Base::m_iterations; + using Base::matrix; + Index m_L; + Index m_S; + + public: + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + + public: + /** Default constructor. */ + IDRSTABL() : m_L(2), m_S(4) {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + + This constructor is a shortcut for the default constructor followed + by a call to compute(). + + \warning this class stores a reference to the matrix A as well as some + precomputed values that depend on it. Therefore, if \a A is changed + this class becomes invalid. Call compute() to update it with the new + matrix A, or modify a copy of A. + */ + template + explicit IDRSTABL(const EigenBase &A) : Base(A.derived()), m_L(2), m_S(4) {} + + /** \internal */ + /** Loops over the number of columns of b and does the following: + 1. sets the tolerance and maxIterations + 2. Calls the function that has the core solver + routine + */ + template + void _solve_vector_with_guess_impl(const Rhs &b, Dest &x) const { + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + bool ret = internal::idrstabl(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error, m_L, m_S); + + m_info = (!ret) ? NumericalIssue : m_error <= 10 * Base::m_tolerance ? Success : NoConvergence; + } + + /** Sets the parameter L, indicating the amount of minimize residual steps are + * used. */ + void setL(Index L) { + eigen_assert(L >= 1 && "L needs to be positive"); + m_L = L; + } + /** Sets the parameter S, indicating the dimension of the shadow residual + * space.. */ + void setS(Index S) { + eigen_assert(S >= 1 && "S needs to be positive"); + m_S = S; + } +}; + +} // namespace Eigen + +#endif /* EIGEN_IDRSTABL_H */ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h new file mode 100644 index 0000000000000000000000000000000000000000..3bf564c87f1043ad97f8d0dfa4caf02ef3464943 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h @@ -0,0 +1,92 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_INCOMPLETE_LU_H +#define EIGEN_INCOMPLETE_LU_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template +class IncompleteLU : public SparseSolverBase > +{ + protected: + typedef SparseSolverBase > Base; + using Base::m_isInitialized; + + typedef Scalar_ Scalar; + typedef Matrix Vector; + typedef typename Vector::Index Index; + typedef SparseMatrix FactorType; + + public: + typedef Matrix MatrixType; + + IncompleteLU() {} + + template + IncompleteLU(const MatrixType& mat) + { + compute(mat); + } + + Index rows() const { return m_lu.rows(); } + Index cols() const { return m_lu.cols(); } + + template + IncompleteLU& compute(const MatrixType& mat) + { + m_lu = mat; + int size = mat.cols(); + Vector diag(size); + for(int i=0; i + void _solve_impl(const Rhs& b, Dest& x) const + { + x = m_lu.template triangularView().solve(b); + x = m_lu.template triangularView().solve(x); + } + + protected: + FactorType m_lu; +}; + +} // end namespace Eigen + +#endif // EIGEN_INCOMPLETE_LU_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..679c7fab0044eace6e1c441153c62b39f8271751 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_ITERATIVE_SOLVERS_MODULE_H +#error "Please include unsupported/Eigen/IterativeSolvers instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/MINRES.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/MINRES.h new file mode 100644 index 0000000000000000000000000000000000000000..22827776cd994c64fdb839182a6bbd52c5c2fd49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/MINRES.h @@ -0,0 +1,269 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Giacomo Po +// Copyright (C) 2011-2014 Gael Guennebaud +// Copyright (C) 2018 David Hyde +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_MINRES_H +#define EIGEN_MINRES_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + + namespace internal { + + /** \internal Low-level MINRES algorithm + * \param mat The matrix A + * \param rhs The right hand side vector b + * \param x On input and initial solution, on output the computed solution. + * \param precond A right preconditioner being able to efficiently solve for an + * approximation of Ax=b (regardless of b) + * \param iters On input the max number of iteration, on output the number of performed iterations. + * \param tol_error On input the tolerance error, on output an estimation of the relative error. + */ + template + EIGEN_DONT_INLINE + void minres(const MatrixType& mat, const Rhs& rhs, Dest& x, + const Preconditioner& precond, Index& iters, + typename Dest::RealScalar& tol_error) + { + using std::sqrt; + typedef typename Dest::RealScalar RealScalar; + typedef typename Dest::Scalar Scalar; + typedef Matrix VectorType; + + // Check for zero rhs + const RealScalar rhsNorm2(rhs.squaredNorm()); + if(rhsNorm2 == 0) + { + x.setZero(); + iters = 0; + tol_error = 0; + return; + } + + // initialize + const Index maxIters(iters); // initialize maxIters to iters + const Index N(mat.cols()); // the size of the matrix + const RealScalar threshold2(tol_error*tol_error*rhsNorm2); // convergence threshold (compared to residualNorm2) + + // Initialize preconditioned Lanczos + VectorType v_old(N); // will be initialized inside loop + VectorType v( VectorType::Zero(N) ); //initialize v + VectorType v_new(rhs-mat*x); //initialize v_new + RealScalar residualNorm2(v_new.squaredNorm()); + VectorType w(N); // will be initialized inside loop + VectorType w_new(precond.solve(v_new)); // initialize w_new +// RealScalar beta; // will be initialized inside loop + RealScalar beta_new2(v_new.dot(w_new)); + eigen_assert(beta_new2 >= 0.0 && "PRECONDITIONER IS NOT POSITIVE DEFINITE"); + RealScalar beta_new(sqrt(beta_new2)); + const RealScalar beta_one(beta_new); + // Initialize other variables + RealScalar c(1.0); // the cosine of the Givens rotation + RealScalar c_old(1.0); + RealScalar s(0.0); // the sine of the Givens rotation + RealScalar s_old(0.0); // the sine of the Givens rotation + VectorType p_oold(N); // will be initialized in loop + VectorType p_old(VectorType::Zero(N)); // initialize p_old=0 + VectorType p(p_old); // initialize p=0 + RealScalar eta(1.0); + + iters = 0; // reset iters + while ( iters < maxIters ) + { + // Preconditioned Lanczos + /* Note that there are 4 variants on the Lanczos algorithm. These are + * described in Paige, C. C. (1972). Computational variants of + * the Lanczos method for the eigenproblem. IMA Journal of Applied + * Mathematics, 10(3), 373-381. The current implementation corresponds + * to the case A(2,7) in the paper. It also corresponds to + * algorithm 6.14 in Y. Saad, Iterative Methods for Sparse Linear + * Systems, 2003 p.173. For the preconditioned version see + * A. Greenbaum, Iterative Methods for Solving Linear Systems, SIAM (1987). + */ + const RealScalar beta(beta_new); + v_old = v; // update: at first time step, this makes v_old = 0 so value of beta doesn't matter + v_new /= beta_new; // overwrite v_new for next iteration + w_new /= beta_new; // overwrite w_new for next iteration + v = v_new; // update + w = w_new; // update + v_new.noalias() = mat*w - beta*v_old; // compute v_new + const RealScalar alpha = v_new.dot(w); + v_new -= alpha*v; // overwrite v_new + w_new = precond.solve(v_new); // overwrite w_new + beta_new2 = v_new.dot(w_new); // compute beta_new + eigen_assert(beta_new2 >= 0.0 && "PRECONDITIONER IS NOT POSITIVE DEFINITE"); + beta_new = sqrt(beta_new2); // compute beta_new + + // Givens rotation + const RealScalar r2 =s*alpha+c*c_old*beta; // s, s_old, c and c_old are still from previous iteration + const RealScalar r3 =s_old*beta; // s, s_old, c and c_old are still from previous iteration + const RealScalar r1_hat=c*alpha-c_old*s*beta; + const RealScalar r1 =sqrt( std::pow(r1_hat,2) + std::pow(beta_new,2) ); + c_old = c; // store for next iteration + s_old = s; // store for next iteration + c=r1_hat/r1; // new cosine + s=beta_new/r1; // new sine + + // Update solution + p_oold = p_old; + p_old = p; + p.noalias()=(w-r2*p_old-r3*p_oold) /r1; // IS NOALIAS REQUIRED? + x += beta_one*c*eta*p; + + /* Update the squared residual. Note that this is the estimated residual. + The real residual |Ax-b|^2 may be slightly larger */ + residualNorm2 *= s*s; + + if ( residualNorm2 < threshold2) + { + break; + } + + eta=-s*eta; // update eta + iters++; // increment iteration number (for output purposes) + } + + /* Compute error. Note that this is the estimated error. The real + error |Ax-b|/|b| may be slightly larger */ + tol_error = std::sqrt(residualNorm2 / rhsNorm2); + } + + } + + template< typename MatrixType_, int UpLo_=Lower, + typename Preconditioner_ = IdentityPreconditioner> + class MINRES; + + namespace internal { + + template< typename MatrixType_, int UpLo_, typename Preconditioner_> + struct traits > + { + typedef MatrixType_ MatrixType; + typedef Preconditioner_ Preconditioner; + }; + + } + + /** \ingroup IterativeLinearSolvers_Module + * \brief A minimal residual solver for sparse symmetric problems + * + * This class allows to solve for A.x = b sparse linear problems using the MINRES algorithm + * of Paige and Saunders (1975). The sparse matrix A must be symmetric (possibly indefinite). + * The vectors x and b can be either dense or sparse. + * + * \tparam MatrixType_ the type of the sparse matrix A, can be a dense or a sparse matrix. + * \tparam UpLo_ the triangular part that will be used for the computations. It can be Lower, + * Upper, or Lower|Upper in which the full matrix entries will be considered. Default is Lower. + * \tparam Preconditioner_ the type of the preconditioner. Default is DiagonalPreconditioner + * + * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations() + * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations + * and NumTraits::epsilon() for the tolerance. + * + * This class can be used as the direct solver classes. Here is a typical usage example: + * \code + * int n = 10000; + * VectorXd x(n), b(n); + * SparseMatrix A(n,n); + * // fill A and b + * MINRES > mr; + * mr.compute(A); + * x = mr.solve(b); + * std::cout << "#iterations: " << mr.iterations() << std::endl; + * std::cout << "estimated error: " << mr.error() << std::endl; + * // update b, and solve again + * x = mr.solve(b); + * \endcode + * + * By default the iterations start with x=0 as an initial guess of the solution. + * One can control the start using the solveWithGuess() method. + * + * MINRES can also be used in a matrix-free context, see the following \link MatrixfreeSolverExample example \endlink. + * + * \sa class ConjugateGradient, BiCGSTAB, SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner + */ + template< typename MatrixType_, int UpLo_, typename Preconditioner_> + class MINRES : public IterativeSolverBase > + { + + typedef IterativeSolverBase Base; + using Base::matrix; + using Base::m_error; + using Base::m_iterations; + using Base::m_info; + using Base::m_isInitialized; + public: + using Base::_solve_impl; + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef Preconditioner_ Preconditioner; + + enum {UpLo = UpLo_}; + + public: + + /** Default constructor. */ + MINRES() : Base() {} + + /** Initialize the solver with matrix \a A for further \c Ax=b solving. + * + * This constructor is a shortcut for the default constructor followed + * by a call to compute(). + * + * \warning this class stores a reference to the matrix A as well as some + * precomputed values that depend on it. Therefore, if \a A is changed + * this class becomes invalid. Call compute() to update it with the new + * matrix A, or modify a copy of A. + */ + template + explicit MINRES(const EigenBase& A) : Base(A.derived()) {} + + /** Destructor. */ + ~MINRES(){} + + /** \internal */ + template + void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const + { + typedef typename Base::MatrixWrapper MatrixWrapper; + typedef typename Base::ActualMatrixType ActualMatrixType; + enum { + TransposeInput = (!MatrixWrapper::MatrixFree) + && (UpLo==(Lower|Upper)) + && (!MatrixType::IsRowMajor) + && (!NumTraits::IsComplex) + }; + typedef std::conditional_t, ActualMatrixType const&> RowMajorWrapper; + EIGEN_STATIC_ASSERT(internal::check_implication(MatrixWrapper::MatrixFree, UpLo==(Lower|Upper)),MATRIX_FREE_CONJUGATE_GRADIENT_IS_COMPATIBLE_WITH_UPPER_UNION_LOWER_MODE_ONLY); + typedef std::conditional_t::Type + > SelfAdjointWrapper; + + m_iterations = Base::maxIterations(); + m_error = Base::m_tolerance; + RowMajorWrapper row_mat(matrix()); + internal::minres(SelfAdjointWrapper(row_mat), b, x, + Base::m_preconditioner, m_iterations, m_error); + m_info = m_error <= Base::m_tolerance ? Success : NoConvergence; + } + + protected: + + }; + +} // end namespace Eigen + +#endif // EIGEN_MINRES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/Scaling.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/Scaling.h new file mode 100644 index 0000000000000000000000000000000000000000..9400e81750575f2379c76ecfd37e08f09a05a5d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/IterativeSolvers/Scaling.h @@ -0,0 +1,195 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Desire NUENTSA WAKAM A; + * // fill A and b; + * IterScaling > scal; + * // Compute the left and right scaling vectors. The matrix is equilibrated at output + * scal.computeRef(A); + * // Scale the right hand side + * b = scal.LeftScaling().cwiseProduct(b); + * // Now, solve the equilibrated linear system with any available solver + * + * // Scale back the computed solution + * x = scal.RightScaling().cwiseProduct(x); + * \endcode + * + * \tparam MatrixType_ the type of the matrix. It should be a real square sparsematrix + * + * References : D. Ruiz and B. Ucar, A Symmetry Preserving Algorithm for Matrix Scaling, INRIA Research report RR-7552 + * + * \sa \ref IncompleteLUT + */ +template +class IterScaling +{ + public: + typedef MatrixType_ MatrixType; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::Index Index; + + public: + IterScaling() { init(); } + + IterScaling(const MatrixType& matrix) + { + init(); + compute(matrix); + } + + ~IterScaling() { } + + /** + * Compute the left and right diagonal matrices to scale the input matrix @p mat + * + * FIXME This algorithm will be modified such that the diagonal elements are permuted on the diagonal. + * + * \sa LeftScaling() RightScaling() + */ + void compute (const MatrixType& mat) + { + using std::abs; + int m = mat.rows(); + int n = mat.cols(); + eigen_assert((m>0 && m == n) && "Please give a non - empty matrix"); + m_left.resize(m); + m_right.resize(n); + m_left.setOnes(); + m_right.setOnes(); + m_matrix = mat; + VectorXd Dr, Dc, DrRes, DcRes; // Temporary Left and right scaling vectors + Dr.resize(m); Dc.resize(n); + DrRes.resize(m); DcRes.resize(n); + double EpsRow = 1.0, EpsCol = 1.0; + int its = 0; + do + { // Iterate until the infinite norm of each row and column is approximately 1 + // Get the maximum value in each row and column + Dr.setZero(); Dc.setZero(); + for (int k=0; km_tol || EpsCol > m_tol) && (its < m_maxits) ); + m_isInitialized = true; + } + /** Compute the left and right vectors to scale the vectors + * the input matrix is scaled with the computed vectors at output + * + * \sa compute() + */ + void computeRef (MatrixType& mat) + { + compute (mat); + mat = m_matrix; + } + /** Get the vector to scale the rows of the matrix + */ + VectorXd& LeftScaling() + { + return m_left; + } + + /** Get the vector to scale the columns of the matrix + */ + VectorXd& RightScaling() + { + return m_right; + } + + /** Set the tolerance for the convergence of the iterative scaling algorithm + */ + void setTolerance(double tol) + { + m_tol = tol; + } + + protected: + + void init() + { + m_tol = 1e-10; + m_maxits = 5; + m_isInitialized = false; + } + + MatrixType m_matrix; + mutable ComputationInfo m_info; + bool m_isInitialized; + VectorXd m_left; // Left scaling vector + VectorXd m_right; // m_right scaling vector + double m_tol; + int m_maxits; // Maximum number of iterations allowed +}; +} +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..3db2edc85c4bc848c47bd6f2b60655a562fc2dc1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_KRONECKER_PRODUCT_MODULE_H +#error "Please include unsupported/Eigen/KroneckerProduct instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/KroneckerTensorProduct.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/KroneckerTensorProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..01a75ef23af29c2fee73c7ae8108075fec281dd1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/KroneckerProduct/KroneckerTensorProduct.h @@ -0,0 +1,307 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Kolja Brix +// Copyright (C) 2011 Andreas Platen +// Copyright (C) 2012 Chen-Pang He +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef KRONECKER_TENSOR_PRODUCT_H +#define KRONECKER_TENSOR_PRODUCT_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/*! + * \ingroup KroneckerProduct_Module + * + * \brief The base class of dense and sparse Kronecker product. + * + * \tparam Derived is the derived type. + */ +template +class KroneckerProductBase : public ReturnByValue +{ + private: + typedef typename internal::traits Traits; + typedef typename Traits::Scalar Scalar; + + protected: + typedef typename Traits::Lhs Lhs; + typedef typename Traits::Rhs Rhs; + + public: + /*! \brief Constructor. */ + KroneckerProductBase(const Lhs& A, const Rhs& B) + : m_A(A), m_B(B) + {} + + inline Index rows() const { return m_A.rows() * m_B.rows(); } + inline Index cols() const { return m_A.cols() * m_B.cols(); } + + /*! + * This overrides ReturnByValue::coeff because this function is + * efficient enough. + */ + Scalar coeff(Index row, Index col) const + { + return m_A.coeff(row / m_B.rows(), col / m_B.cols()) * + m_B.coeff(row % m_B.rows(), col % m_B.cols()); + } + + /*! + * This overrides ReturnByValue::coeff because this function is + * efficient enough. + */ + Scalar coeff(Index i) const + { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived); + return m_A.coeff(i / m_A.size()) * m_B.coeff(i % m_A.size()); + } + + protected: + typename Lhs::Nested m_A; + typename Rhs::Nested m_B; +}; + +/*! + * \ingroup KroneckerProduct_Module + * + * \brief Kronecker tensor product helper class for dense matrices + * + * This class is the return value of kroneckerProduct(MatrixBase, + * MatrixBase). Use the function rather than construct this class + * directly to avoid specifying template prarameters. + * + * \tparam Lhs Type of the left-hand side, a matrix expression. + * \tparam Rhs Type of the rignt-hand side, a matrix expression. + */ +template +class KroneckerProduct : public KroneckerProductBase > +{ + private: + typedef KroneckerProductBase Base; + using Base::m_A; + using Base::m_B; + + public: + /*! \brief Constructor. */ + KroneckerProduct(const Lhs& A, const Rhs& B) + : Base(A, B) + {} + + /*! \brief Evaluate the Kronecker tensor product. */ + template void evalTo(Dest& dst) const; +}; + +/*! + * \ingroup KroneckerProduct_Module + * + * \brief Kronecker tensor product helper class for sparse matrices + * + * If at least one of the operands is a sparse matrix expression, + * then this class is returned and evaluates into a sparse matrix. + * + * This class is the return value of kroneckerProduct(EigenBase, + * EigenBase). Use the function rather than construct this class + * directly to avoid specifying template prarameters. + * + * \tparam Lhs Type of the left-hand side, a matrix expression. + * \tparam Rhs Type of the rignt-hand side, a matrix expression. + */ +template +class KroneckerProductSparse : public KroneckerProductBase > +{ + private: + typedef KroneckerProductBase Base; + using Base::m_A; + using Base::m_B; + + public: + /*! \brief Constructor. */ + KroneckerProductSparse(const Lhs& A, const Rhs& B) + : Base(A, B) + {} + + /*! \brief Evaluate the Kronecker tensor product. */ + template void evalTo(Dest& dst) const; +}; + +template +template +void KroneckerProduct::evalTo(Dest& dst) const +{ + const int BlockRows = Rhs::RowsAtCompileTime, + BlockCols = Rhs::ColsAtCompileTime; + const Index Br = m_B.rows(), + Bc = m_B.cols(); + for (Index i=0; i < m_A.rows(); ++i) + for (Index j=0; j < m_A.cols(); ++j) + Block(dst,i*Br,j*Bc,Br,Bc) = m_A.coeff(i,j) * m_B; +} + +template +template +void KroneckerProductSparse::evalTo(Dest& dst) const +{ + Index Br = m_B.rows(), Bc = m_B.cols(); + dst.resize(this->rows(), this->cols()); + dst.resizeNonZeros(0); + + // 1 - evaluate the operands if needed: + typedef typename internal::nested_eval::type Lhs1; + typedef internal::remove_all_t Lhs1Cleaned; + const Lhs1 lhs1(m_A); + typedef typename internal::nested_eval::type Rhs1; + typedef internal::remove_all_t Rhs1Cleaned; + const Rhs1 rhs1(m_B); + + // 2 - construct respective iterators + typedef Eigen::InnerIterator LhsInnerIterator; + typedef Eigen::InnerIterator RhsInnerIterator; + + // compute number of non-zeros per innervectors of dst + { + // TODO VectorXi is not necessarily big enough! + VectorXi nnzA = VectorXi::Zero(Dest::IsRowMajor ? m_A.rows() : m_A.cols()); + for (Index kA=0; kA < m_A.outerSize(); ++kA) + for (LhsInnerIterator itA(lhs1,kA); itA; ++itA) + nnzA(Dest::IsRowMajor ? itA.row() : itA.col())++; + + VectorXi nnzB = VectorXi::Zero(Dest::IsRowMajor ? m_B.rows() : m_B.cols()); + for (Index kB=0; kB < m_B.outerSize(); ++kB) + for (RhsInnerIterator itB(rhs1,kB); itB; ++itB) + nnzB(Dest::IsRowMajor ? itB.row() : itB.col())++; + + Matrix nnzAB = nnzB * nnzA.transpose(); + dst.reserve(VectorXi::Map(nnzAB.data(), nnzAB.size())); + } + + for (Index kA=0; kA < m_A.outerSize(); ++kA) + { + for (Index kB=0; kB < m_B.outerSize(); ++kB) + { + for (LhsInnerIterator itA(lhs1,kA); itA; ++itA) + { + for (RhsInnerIterator itB(rhs1,kB); itB; ++itB) + { + Index i = itA.row() * Br + itB.row(), + j = itA.col() * Bc + itB.col(); + dst.insert(i,j) = itA.value() * itB.value(); + } + } + } + } +} + +namespace internal { + +template +struct traits > +{ + typedef remove_all_t Lhs; + typedef remove_all_t Rhs; + typedef typename ScalarBinaryOpTraits::ReturnType Scalar; + typedef typename promote_index_type::type StorageIndex; + + enum { + Rows = size_at_compile_time(traits::RowsAtCompileTime, traits::RowsAtCompileTime), + Cols = size_at_compile_time(traits::ColsAtCompileTime, traits::ColsAtCompileTime), + MaxRows = size_at_compile_time(traits::MaxRowsAtCompileTime, traits::MaxRowsAtCompileTime), + MaxCols = size_at_compile_time(traits::MaxColsAtCompileTime, traits::MaxColsAtCompileTime) + }; + + typedef Matrix ReturnType; +}; + +template +struct traits > +{ + typedef MatrixXpr XprKind; + typedef remove_all_t Lhs; + typedef remove_all_t Rhs; + typedef typename ScalarBinaryOpTraits::ReturnType Scalar; + typedef typename cwise_promote_storage_type::StorageKind, typename traits::StorageKind, scalar_product_op >::ret StorageKind; + typedef typename promote_index_type::type StorageIndex; + + enum { + LhsFlags = Lhs::Flags, + RhsFlags = Rhs::Flags, + + RowsAtCompileTime = size_at_compile_time(traits::RowsAtCompileTime, traits::RowsAtCompileTime), + ColsAtCompileTime = size_at_compile_time(traits::ColsAtCompileTime, traits::ColsAtCompileTime), + MaxRowsAtCompileTime = size_at_compile_time(traits::MaxRowsAtCompileTime, traits::MaxRowsAtCompileTime), + MaxColsAtCompileTime = size_at_compile_time(traits::MaxColsAtCompileTime, traits::MaxColsAtCompileTime), + + EvalToRowMajor = (int(LhsFlags) & int(RhsFlags) & RowMajorBit), + RemovedBits = ~(EvalToRowMajor ? 0 : RowMajorBit), + + Flags = ((int(LhsFlags) | int(RhsFlags)) & HereditaryBits & RemovedBits) + | EvalBeforeNestingBit, + CoeffReadCost = HugeCost + }; + + typedef SparseMatrix ReturnType; +}; + +} // end namespace internal + +/*! + * \ingroup KroneckerProduct_Module + * + * Computes Kronecker tensor product of two dense matrices + * + * \warning If you want to replace a matrix by its Kronecker product + * with some matrix, do \b NOT do this: + * \code + * A = kroneckerProduct(A,B); // bug!!! caused by aliasing effect + * \endcode + * instead, use eval() to work around this: + * \code + * A = kroneckerProduct(A,B).eval(); + * \endcode + * + * \param a Dense matrix a + * \param b Dense matrix b + * \return Kronecker tensor product of a and b + */ +template +KroneckerProduct kroneckerProduct(const MatrixBase& a, const MatrixBase& b) +{ + return KroneckerProduct(a.derived(), b.derived()); +} + +/*! + * \ingroup KroneckerProduct_Module + * + * Computes Kronecker tensor product of two matrices, at least one of + * which is sparse + * + * \warning If you want to replace a matrix by its Kronecker product + * with some matrix, do \b NOT do this: + * \code + * A = kroneckerProduct(A,B); // bug!!! caused by aliasing effect + * \endcode + * instead, use eval() to work around this: + * \code + * A = kroneckerProduct(A,B).eval(); + * \endcode + * + * \param a Dense/sparse matrix a + * \param b Dense/sparse matrix b + * \return Kronecker tensor product of a and b, stored in a sparse + * matrix + */ +template +KroneckerProductSparse kroneckerProduct(const EigenBase& a, const EigenBase& b) +{ + return KroneckerProductSparse(a.derived(), b.derived()); +} + +} // end namespace Eigen + +#endif // KRONECKER_TENSOR_PRODUCT_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..bc76f4e98059eef907085e9aa8f408b6dd47702d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_LEVENBERGMARQUARDT_MODULE_H +#error "Please include unsupported/Eigen/LevenbergMarquardt instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h new file mode 100644 index 0000000000000000000000000000000000000000..344c22e499a19a76786bf61d5a4738c78080a9fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h @@ -0,0 +1,86 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This code initially comes from MINPACK whose original authors are: +// Copyright Jorge More - Argonne National Laboratory +// Copyright Burt Garbow - Argonne National Laboratory +// Copyright Ken Hillstrom - Argonne National Laboratory +// +// This Source Code Form is subject to the terms of the Minpack license +// (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. + +#ifndef EIGEN_LMCOVAR_H +#define EIGEN_LMCOVAR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void covar( + Matrix< Scalar, Dynamic, Dynamic > &r, + const VectorXi& ipvt, + Scalar tol = std::sqrt(NumTraits::epsilon()) ) +{ + using std::abs; + /* Local variables */ + Index i, j, k, l, ii, jj; + bool sing; + Scalar temp; + + /* Function Body */ + const Index n = r.cols(); + const Scalar tolr = tol * abs(r(0,0)); + Matrix< Scalar, Dynamic, 1 > wa(n); + eigen_assert(ipvt.size()==n); + + /* form the inverse of r in the full upper triangle of r. */ + l = -1; + for (k = 0; k < n; ++k) + if (abs(r(k,k)) > tolr) { + r(k,k) = 1. / r(k,k); + for (j = 0; j <= k-1; ++j) { + temp = r(k,k) * r(j,k); + r(j,k) = 0.; + r.col(k).head(j+1) -= r.col(j).head(j+1) * temp; + } + l = k; + } + + /* form the full upper triangle of the inverse of (r transpose)*r */ + /* in the full upper triangle of r. */ + for (k = 0; k <= l; ++k) { + for (j = 0; j <= k-1; ++j) + r.col(j).head(j+1) += r.col(k).head(j+1) * r(j,k); + r.col(k).head(k+1) *= r(k,k); + } + + /* form the full lower triangle of the covariance matrix */ + /* in the strict lower triangle of r and in wa. */ + for (j = 0; j < n; ++j) { + jj = ipvt[j]; + sing = j > l; + for (i = 0; i <= j; ++i) { + if (sing) + r(i,j) = 0.; + ii = ipvt[i]; + if (ii > jj) + r(ii,jj) = r(i,j); + if (ii < jj) + r(jj,ii) = r(i,j); + } + wa[jj] = r(j,j); + } + + /* symmetrize the covariance matrix in r. */ + r.topLeftCorner(n,n).template triangularView() = r.topLeftCorner(n,n).transpose(); + r.diagonal() = wa; +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_LMCOVAR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMonestep.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMonestep.h new file mode 100644 index 0000000000000000000000000000000000000000..92cb6f64dbce82e28c0fec08a93e12e7e51191d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMonestep.h @@ -0,0 +1,204 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This code initially comes from MINPACK whose original authors are: +// Copyright Jorge More - Argonne National Laboratory +// Copyright Burt Garbow - Argonne National Laboratory +// Copyright Ken Hillstrom - Argonne National Laboratory +// +// This Source Code Form is subject to the terms of the Minpack license +// (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. + +#ifndef EIGEN_LMONESTEP_H +#define EIGEN_LMONESTEP_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeOneStep(FVectorType &x) +{ + using std::abs; + using std::sqrt; + RealScalar temp, temp1,temp2; + RealScalar ratio; + RealScalar pnorm, xnorm, fnorm1, actred, dirder, prered; + eigen_assert(x.size()==n); // check the caller is not cheating us + + temp = 0.0; xnorm = 0.0; + /* calculate the jacobian matrix. */ + Index df_ret = m_functor.df(x, m_fjac); + if (df_ret<0) + return LevenbergMarquardtSpace::UserAsked; + if (df_ret>0) + // numerical diff, we evaluated the function df_ret times + m_nfev += df_ret; + else m_njev++; + + /* compute the qr factorization of the jacobian. */ + for (int j = 0; j < x.size(); ++j) + m_wa2(j) = m_fjac.col(j).blueNorm(); + QRSolver qrfac(m_fjac); + if(qrfac.info() != Success) { + m_info = NumericalIssue; + return LevenbergMarquardtSpace::ImproperInputParameters; + } + // Make a copy of the first factor with the associated permutation + m_rfactor = qrfac.matrixR(); + m_permutation = (qrfac.colsPermutation()); + + /* on the first iteration and if external scaling is not used, scale according */ + /* to the norms of the columns of the initial jacobian. */ + if (m_iter == 1) { + if (!m_useExternalScaling) + for (Index j = 0; j < n; ++j) + m_diag[j] = (m_wa2[j]==0.)? 1. : m_wa2[j]; + + /* on the first iteration, calculate the norm of the scaled x */ + /* and initialize the step bound m_delta. */ + xnorm = m_diag.cwiseProduct(x).stableNorm(); + m_delta = m_factor * xnorm; + if (m_delta == 0.) + m_delta = m_factor; + } + + /* form (q transpose)*m_fvec and store the first n components in */ + /* m_qtf. */ + m_wa4 = m_fvec; + m_wa4 = qrfac.matrixQ().adjoint() * m_fvec; + m_qtf = m_wa4.head(n); + + /* compute the norm of the scaled gradient. */ + m_gnorm = 0.; + if (m_fnorm != 0.) + for (Index j = 0; j < n; ++j) + if (m_wa2[m_permutation.indices()[j]] != 0.) + m_gnorm = (std::max)(m_gnorm, abs( m_rfactor.col(j).head(j+1).dot(m_qtf.head(j+1)/m_fnorm) / m_wa2[m_permutation.indices()[j]])); + + /* test for convergence of the gradient norm. */ + if (m_gnorm <= m_gtol) { + m_info = Success; + return LevenbergMarquardtSpace::CosinusTooSmall; + } + + /* rescale if necessary. */ + if (!m_useExternalScaling) + m_diag = m_diag.cwiseMax(m_wa2); + + do { + /* determine the levenberg-marquardt parameter. */ + internal::lmpar2(qrfac, m_diag, m_qtf, m_delta, m_par, m_wa1); + + /* store the direction p and x + p. calculate the norm of p. */ + m_wa1 = -m_wa1; + m_wa2 = x + m_wa1; + pnorm = m_diag.cwiseProduct(m_wa1).stableNorm(); + + /* on the first iteration, adjust the initial step bound. */ + if (m_iter == 1) + m_delta = (std::min)(m_delta,pnorm); + + /* evaluate the function at x + p and calculate its norm. */ + if ( m_functor(m_wa2, m_wa4) < 0) + return LevenbergMarquardtSpace::UserAsked; + ++m_nfev; + fnorm1 = m_wa4.stableNorm(); + + /* compute the scaled actual reduction. */ + actred = -1.; + if (Scalar(.1) * fnorm1 < m_fnorm) + actred = 1. - numext::abs2(fnorm1 / m_fnorm); + + /* compute the scaled predicted reduction and */ + /* the scaled directional derivative. */ + m_wa3 = m_rfactor.template triangularView() * (m_permutation.inverse() *m_wa1); + temp1 = numext::abs2(m_wa3.stableNorm() / m_fnorm); + temp2 = numext::abs2(sqrt(m_par) * pnorm / m_fnorm); + prered = temp1 + temp2 / Scalar(.5); + dirder = -(temp1 + temp2); + + /* compute the ratio of the actual to the predicted */ + /* reduction. */ + ratio = 0.; + if (prered != 0.) + ratio = actred / prered; + + /* update the step bound. */ + if (ratio <= Scalar(.25)) { + if (actred >= 0.) + temp = RealScalar(.5); + if (actred < 0.) + temp = RealScalar(.5) * dirder / (dirder + RealScalar(.5) * actred); + if (RealScalar(.1) * fnorm1 >= m_fnorm || temp < RealScalar(.1)) + temp = Scalar(.1); + /* Computing MIN */ + m_delta = temp * (std::min)(m_delta, pnorm / RealScalar(.1)); + m_par /= temp; + } else if (!(m_par != 0. && ratio < RealScalar(.75))) { + m_delta = pnorm / RealScalar(.5); + m_par = RealScalar(.5) * m_par; + } + + /* test for successful iteration. */ + if (ratio >= RealScalar(1e-4)) { + /* successful iteration. update x, m_fvec, and their norms. */ + x = m_wa2; + m_wa2 = m_diag.cwiseProduct(x); + m_fvec = m_wa4; + xnorm = m_wa2.stableNorm(); + m_fnorm = fnorm1; + ++m_iter; + } + + /* tests for convergence. */ + if (abs(actred) <= m_ftol && prered <= m_ftol && Scalar(.5) * ratio <= 1. && m_delta <= m_xtol * xnorm) + { + m_info = Success; + return LevenbergMarquardtSpace::RelativeErrorAndReductionTooSmall; + } + if (abs(actred) <= m_ftol && prered <= m_ftol && Scalar(.5) * ratio <= 1.) + { + m_info = Success; + return LevenbergMarquardtSpace::RelativeReductionTooSmall; + } + if (m_delta <= m_xtol * xnorm) + { + m_info = Success; + return LevenbergMarquardtSpace::RelativeErrorTooSmall; + } + + /* tests for termination and stringent tolerances. */ + if (m_nfev >= m_maxfev) + { + m_info = NoConvergence; + return LevenbergMarquardtSpace::TooManyFunctionEvaluation; + } + if (abs(actred) <= NumTraits::epsilon() && prered <= NumTraits::epsilon() && Scalar(.5) * ratio <= 1.) + { + m_info = Success; + return LevenbergMarquardtSpace::FtolTooSmall; + } + if (m_delta <= NumTraits::epsilon() * xnorm) + { + m_info = Success; + return LevenbergMarquardtSpace::XtolTooSmall; + } + if (m_gnorm <= NumTraits::epsilon()) + { + m_info = Success; + return LevenbergMarquardtSpace::GtolTooSmall; + } + + } while (ratio < Scalar(1e-4)); + + return LevenbergMarquardtSpace::Running; +} + + +} // end namespace Eigen + +#endif // EIGEN_LMONESTEP_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMpar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMpar.h new file mode 100644 index 0000000000000000000000000000000000000000..74acc9a960d7223ace1020ce9fa0410db2eb4bfd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMpar.h @@ -0,0 +1,162 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This code initially comes from MINPACK whose original authors are: +// Copyright Jorge More - Argonne National Laboratory +// Copyright Burt Garbow - Argonne National Laboratory +// Copyright Ken Hillstrom - Argonne National Laboratory +// +// This Source Code Form is subject to the terms of the Minpack license +// (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. + +#ifndef EIGEN_LMPAR_H +#define EIGEN_LMPAR_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + + template + void lmpar2( + const QRSolver &qr, + const VectorType &diag, + const VectorType &qtb, + typename VectorType::Scalar m_delta, + typename VectorType::Scalar &par, + VectorType &x) + + { + using std::sqrt; + using std::abs; + typedef typename QRSolver::MatrixType MatrixType; + typedef typename QRSolver::Scalar Scalar; +// typedef typename QRSolver::StorageIndex StorageIndex; + + /* Local variables */ + Index j; + Scalar fp; + Scalar parc, parl; + Index iter; + Scalar temp, paru; + Scalar gnorm; + Scalar dxnorm; + + // Make a copy of the triangular factor. + // This copy is modified during call the qrsolv + MatrixType s; + s = qr.matrixR(); + + /* Function Body */ + const Scalar dwarf = (std::numeric_limits::min)(); + const Index n = qr.matrixR().cols(); + eigen_assert(n==diag.size()); + eigen_assert(n==qtb.size()); + + VectorType wa1, wa2; + + /* compute and store in x the gauss-newton direction. if the */ + /* jacobian is rank-deficient, obtain a least squares solution. */ + + // const Index rank = qr.nonzeroPivots(); // exactly double(0.) + const Index rank = qr.rank(); // use a threshold + wa1 = qtb; + wa1.tail(n-rank).setZero(); + //FIXME There is no solve in place for sparse triangularView + wa1.head(rank) = s.topLeftCorner(rank,rank).template triangularView().solve(qtb.head(rank)); + + x = qr.colsPermutation()*wa1; + + /* initialize the iteration counter. */ + /* evaluate the function at the origin, and test */ + /* for acceptance of the gauss-newton direction. */ + iter = 0; + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + fp = dxnorm - m_delta; + if (fp <= Scalar(0.1) * m_delta) { + par = 0; + return; + } + + /* if the jacobian is not rank deficient, the newton */ + /* step provides a lower bound, parl, for the zero of */ + /* the function. otherwise set this bound to zero. */ + parl = 0.; + if (rank==n) { + wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2)/dxnorm; + s.topLeftCorner(n,n).transpose().template triangularView().solveInPlace(wa1); + temp = wa1.blueNorm(); + parl = fp / m_delta / temp / temp; + } + + /* calculate an upper bound, paru, for the zero of the function. */ + for (j = 0; j < n; ++j) + wa1[j] = s.col(j).head(j+1).dot(qtb.head(j+1)) / diag[qr.colsPermutation().indices()(j)]; + + gnorm = wa1.stableNorm(); + paru = gnorm / m_delta; + if (paru == 0.) + paru = dwarf / (std::min)(m_delta,Scalar(0.1)); + + /* if the input par lies outside of the interval (parl,paru), */ + /* set par to the closer endpoint. */ + par = (std::max)(par,parl); + par = (std::min)(par,paru); + if (par == 0.) + par = gnorm / dxnorm; + + /* beginning of an iteration. */ + while (true) { + ++iter; + + /* evaluate the function at the current value of par. */ + if (par == 0.) + par = (std::max)(dwarf,Scalar(.001) * paru); /* Computing MAX */ + wa1 = sqrt(par)* diag; + + VectorType sdiag(n); + lmqrsolv(s, qr.colsPermutation(), wa1, qtb, x, sdiag); + + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + temp = fp; + fp = dxnorm - m_delta; + + /* if the function is small enough, accept the current value */ + /* of par. also test for the exceptional cases where parl */ + /* is zero or the number of iterations has reached 10. */ + if (abs(fp) <= Scalar(0.1) * m_delta || (parl == 0. && fp <= temp && temp < 0.) || iter == 10) + break; + + /* compute the newton correction. */ + wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2/dxnorm); + // we could almost use this here, but the diagonal is outside qr, in sdiag[] + for (j = 0; j < n; ++j) { + wa1[j] /= sdiag[j]; + temp = wa1[j]; + for (Index i = j+1; i < n; ++i) + wa1[i] -= s.coeff(i,j) * temp; + } + temp = wa1.blueNorm(); + parc = fp / m_delta / temp / temp; + + /* depending on the sign of the function, update parl or paru. */ + if (fp > 0.) + parl = (std::max)(parl,par); + if (fp < 0.) + paru = (std::min)(paru,par); + + /* compute an improved estimate for par. */ + par = (std::max)(parl,par+parc); + } + if (iter == 0) + par = 0.; + return; + } +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_LMPAR_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h new file mode 100644 index 0000000000000000000000000000000000000000..385b7b53476e3e73b830eb6f3cc5a3c3433a99ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h @@ -0,0 +1,190 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// Copyright (C) 2012 Desire Nuentsa +// +// This code initially comes from MINPACK whose original authors are: +// Copyright Jorge More - Argonne National Laboratory +// Copyright Burt Garbow - Argonne National Laboratory +// Copyright Ken Hillstrom - Argonne National Laboratory +// +// This Source Code Form is subject to the terms of the Minpack license +// (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. + +#ifndef EIGEN_LMQRSOLV_H +#define EIGEN_LMQRSOLV_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void lmqrsolv( + Matrix &s, + const PermutationMatrix &iPerm, + const Matrix &diag, + const Matrix &qtb, + Matrix &x, + Matrix &sdiag) +{ + /* Local variables */ + Index i, j, k; + Scalar temp; + Index n = s.cols(); + Matrix wa(n); + JacobiRotation givens; + + /* Function Body */ + // the following will only change the lower triangular part of s, including + // the diagonal, though the diagonal is restored afterward + + /* copy r and (q transpose)*b to preserve input and initialize s. */ + /* in particular, save the diagonal elements of r in x. */ + x = s.diagonal(); + wa = qtb; + + + s.topLeftCorner(n,n).template triangularView() = s.topLeftCorner(n,n).transpose(); + /* eliminate the diagonal matrix d using a givens rotation. */ + for (j = 0; j < n; ++j) { + + /* prepare the row of d to be eliminated, locating the */ + /* diagonal element using p from the qr factorization. */ + const PermIndex l = iPerm.indices()(j); + if (diag[l] == 0.) + break; + sdiag.tail(n-j).setZero(); + sdiag[j] = diag[l]; + + /* the transformations to eliminate the row of d */ + /* modify only a single element of (q transpose)*b */ + /* beyond the first n, which is initially zero. */ + Scalar qtbpj = 0.; + for (k = j; k < n; ++k) { + /* determine a givens rotation which eliminates the */ + /* appropriate element in the current row of d. */ + givens.makeGivens(-s(k,k), sdiag[k]); + + /* compute the modified diagonal element of r and */ + /* the modified element of ((q transpose)*b,0). */ + s(k,k) = givens.c() * s(k,k) + givens.s() * sdiag[k]; + temp = givens.c() * wa[k] + givens.s() * qtbpj; + qtbpj = -givens.s() * wa[k] + givens.c() * qtbpj; + wa[k] = temp; + + /* accumulate the transformation in the row of s. */ + for (i = k+1; i().solveInPlace(wa.head(nsing)); + + // restore + sdiag = s.diagonal(); + s.diagonal() = x; + + /* permute the components of z back to components of x. */ + x = iPerm * wa; +} + +template +void lmqrsolv( + SparseMatrix &s, + const PermutationMatrix &iPerm, + const Matrix &diag, + const Matrix &qtb, + Matrix &x, + Matrix &sdiag) +{ + /* Local variables */ + typedef SparseMatrix FactorType; + Index i, j, k, l; + Scalar temp; + Index n = s.cols(); + Matrix wa(n); + JacobiRotation givens; + + /* Function Body */ + // the following will only change the lower triangular part of s, including + // the diagonal, though the diagonal is restored afterward + + /* copy r and (q transpose)*b to preserve input and initialize R. */ + wa = qtb; + FactorType R(s); + // Eliminate the diagonal matrix d using a givens rotation + for (j = 0; j < n; ++j) + { + // Prepare the row of d to be eliminated, locating the + // diagonal element using p from the qr factorization + l = iPerm.indices()(j); + if (diag(l) == Scalar(0)) + break; + sdiag.tail(n-j).setZero(); + sdiag[j] = diag[l]; + // the transformations to eliminate the row of d + // modify only a single element of (q transpose)*b + // beyond the first n, which is initially zero. + + Scalar qtbpj = 0; + // Browse the nonzero elements of row j of the upper triangular s + for (k = j; k < n; ++k) + { + typename FactorType::InnerIterator itk(R,k); + for (; itk; ++itk){ + if (itk.index() < k) continue; + else break; + } + //At this point, we have the diagonal element R(k,k) + // Determine a givens rotation which eliminates + // the appropriate element in the current row of d + givens.makeGivens(-itk.value(), sdiag(k)); + + // Compute the modified diagonal element of r and + // the modified element of ((q transpose)*b,0). + itk.valueRef() = givens.c() * itk.value() + givens.s() * sdiag(k); + temp = givens.c() * wa(k) + givens.s() * qtbpj; + qtbpj = -givens.s() * wa(k) + givens.c() * qtbpj; + wa(k) = temp; + + // Accumulate the transformation in the remaining k row/column of R + for (++itk; itk; ++itk) + { + i = itk.index(); + temp = givens.c() * itk.value() + givens.s() * sdiag(i); + sdiag(i) = -givens.s() * itk.value() + givens.c() * sdiag(i); + itk.valueRef() = temp; + } + } + } + + // Solve the triangular system for z. If the system is + // singular, then obtain a least squares solution + Index nsing; + for(nsing = 0; nsing().solve/*InPlace*/(wa.head(nsing)); + + sdiag = R.diagonal(); + // Permute the components of z back to components of x + x = iPerm * wa; +} +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_LMQRSOLV_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h new file mode 100644 index 0000000000000000000000000000000000000000..f823ae0f37dee1939cc4f8953ed791ecd3f2cc4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h @@ -0,0 +1,398 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// Copyright (C) 2012 Desire Nuentsa +// +// The algorithm of this class initially comes from MINPACK whose original authors are: +// Copyright Jorge More - Argonne National Laboratory +// Copyright Burt Garbow - Argonne National Laboratory +// Copyright Ken Hillstrom - Argonne National Laboratory +// +// This Source Code Form is subject to the terms of the Minpack license +// (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LEVENBERGMARQUARDT_H +#define EIGEN_LEVENBERGMARQUARDT_H + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace LevenbergMarquardtSpace { + enum Status { + NotStarted = -2, + Running = -1, + ImproperInputParameters = 0, + RelativeReductionTooSmall = 1, + RelativeErrorTooSmall = 2, + RelativeErrorAndReductionTooSmall = 3, + CosinusTooSmall = 4, + TooManyFunctionEvaluation = 5, + FtolTooSmall = 6, + XtolTooSmall = 7, + GtolTooSmall = 8, + UserAsked = 9 + }; +} + +template +struct DenseFunctor +{ + typedef Scalar_ Scalar; + enum { + InputsAtCompileTime = NX, + ValuesAtCompileTime = NY + }; + typedef Matrix InputType; + typedef Matrix ValueType; + typedef Matrix JacobianType; + typedef ColPivHouseholderQR QRSolver; + const int m_inputs, m_values; + + DenseFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {} + DenseFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {} + + int inputs() const { return m_inputs; } + int values() const { return m_values; } + + //int operator()(const InputType &x, ValueType& fvec) { } + // should be defined in derived classes + + //int df(const InputType &x, JacobianType& fjac) { } + // should be defined in derived classes +}; + +template +struct SparseFunctor +{ + typedef Scalar_ Scalar; + typedef Index_ Index; + typedef Matrix InputType; + typedef Matrix ValueType; + typedef SparseMatrix JacobianType; + typedef SparseQR > QRSolver; + enum { + InputsAtCompileTime = Dynamic, + ValuesAtCompileTime = Dynamic + }; + + SparseFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {} + + int inputs() const { return m_inputs; } + int values() const { return m_values; } + + const int m_inputs, m_values; + //int operator()(const InputType &x, ValueType& fvec) { } + // to be defined in the functor + + //int df(const InputType &x, JacobianType& fjac) { } + // to be defined in the functor if no automatic differentiation + +}; +namespace internal { +template +void lmpar2(const QRSolver &qr, const VectorType &diag, const VectorType &qtb, + typename VectorType::Scalar m_delta, typename VectorType::Scalar &par, + VectorType &x); + } +/** + * \ingroup NonLinearOptimization_Module + * \brief Performs non linear optimization over a non-linear function, + * using a variant of the Levenberg Marquardt algorithm. + * + * Check wikipedia for more information. + * http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm + */ +template +class LevenbergMarquardt : internal::no_assignment_operator +{ + public: + typedef FunctorType_ FunctorType; + typedef typename FunctorType::QRSolver QRSolver; + typedef typename FunctorType::JacobianType JacobianType; + typedef typename JacobianType::Scalar Scalar; + typedef typename JacobianType::RealScalar RealScalar; + typedef typename QRSolver::StorageIndex PermIndex; + typedef Matrix FVectorType; + typedef PermutationMatrix PermutationType; + public: + LevenbergMarquardt(FunctorType& functor) + : m_functor(functor),m_nfev(0),m_njev(0),m_fnorm(0.0),m_gnorm(0), + m_isInitialized(false),m_info(InvalidInput) + { + resetParameters(); + m_useExternalScaling=false; + } + + LevenbergMarquardtSpace::Status minimize(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeInit(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeOneStep(FVectorType &x); + LevenbergMarquardtSpace::Status lmder1( + FVectorType &x, + const Scalar tol = std::sqrt(NumTraits::epsilon()) + ); + static LevenbergMarquardtSpace::Status lmdif1( + FunctorType &functor, + FVectorType &x, + Index *nfev, + const Scalar tol = std::sqrt(NumTraits::epsilon()) + ); + + /** Sets the default parameters */ + void resetParameters() + { + using std::sqrt; + + m_factor = 100.; + m_maxfev = 400; + m_ftol = sqrt(NumTraits::epsilon()); + m_xtol = sqrt(NumTraits::epsilon()); + m_gtol = 0. ; + m_epsfcn = 0. ; + } + + /** Sets the tolerance for the norm of the solution vector*/ + void setXtol(RealScalar xtol) { m_xtol = xtol; } + + /** Sets the tolerance for the norm of the vector function*/ + void setFtol(RealScalar ftol) { m_ftol = ftol; } + + /** Sets the tolerance for the norm of the gradient of the error vector*/ + void setGtol(RealScalar gtol) { m_gtol = gtol; } + + /** Sets the step bound for the diagonal shift */ + void setFactor(RealScalar factor) { m_factor = factor; } + + /** Sets the error precision */ + void setEpsilon (RealScalar epsfcn) { m_epsfcn = epsfcn; } + + /** Sets the maximum number of function evaluation */ + void setMaxfev(Index maxfev) {m_maxfev = maxfev; } + + /** Use an external Scaling. If set to true, pass a nonzero diagonal to diag() */ + void setExternalScaling(bool value) {m_useExternalScaling = value; } + + /** \returns the tolerance for the norm of the solution vector */ + RealScalar xtol() const {return m_xtol; } + + /** \returns the tolerance for the norm of the vector function */ + RealScalar ftol() const {return m_ftol; } + + /** \returns the tolerance for the norm of the gradient of the error vector */ + RealScalar gtol() const {return m_gtol; } + + /** \returns the step bound for the diagonal shift */ + RealScalar factor() const {return m_factor; } + + /** \returns the error precision */ + RealScalar epsilon() const {return m_epsfcn; } + + /** \returns the maximum number of function evaluation */ + Index maxfev() const {return m_maxfev; } + + /** \returns a reference to the diagonal of the jacobian */ + FVectorType& diag() {return m_diag; } + + /** \returns the number of iterations performed */ + Index iterations() { return m_iter; } + + /** \returns the number of functions evaluation */ + Index nfev() { return m_nfev; } + + /** \returns the number of jacobian evaluation */ + Index njev() { return m_njev; } + + /** \returns the norm of current vector function */ + RealScalar fnorm() {return m_fnorm; } + + /** \returns the norm of the gradient of the error */ + RealScalar gnorm() {return m_gnorm; } + + /** \returns the LevenbergMarquardt parameter */ + RealScalar lm_param(void) { return m_par; } + + /** \returns a reference to the current vector function + */ + FVectorType& fvec() {return m_fvec; } + + /** \returns a reference to the matrix where the current Jacobian matrix is stored + */ + JacobianType& jacobian() {return m_fjac; } + + /** \returns a reference to the triangular matrix R from the QR of the jacobian matrix. + * \sa jacobian() + */ + JacobianType& matrixR() {return m_rfactor; } + + /** the permutation used in the QR factorization + */ + PermutationType permutation() {return m_permutation; } + + /** + * \brief Reports whether the minimization was successful + * \returns \c Success if the minimization was successful, + * \c NumericalIssue if a numerical problem arises during the + * minimization process, for example during the QR factorization + * \c NoConvergence if the minimization did not converge after + * the maximum number of function evaluation allowed + * \c InvalidInput if the input matrix is invalid + */ + ComputationInfo info() const + { + + return m_info; + } + private: + JacobianType m_fjac; + JacobianType m_rfactor; // The triangular matrix R from the QR of the jacobian matrix m_fjac + FunctorType &m_functor; + FVectorType m_fvec, m_qtf, m_diag; + Index n; + Index m; + Index m_nfev; + Index m_njev; + RealScalar m_fnorm; // Norm of the current vector function + RealScalar m_gnorm; //Norm of the gradient of the error + RealScalar m_factor; // + Index m_maxfev; // Maximum number of function evaluation + RealScalar m_ftol; //Tolerance in the norm of the vector function + RealScalar m_xtol; // + RealScalar m_gtol; //tolerance of the norm of the error gradient + RealScalar m_epsfcn; // + Index m_iter; // Number of iterations performed + RealScalar m_delta; + bool m_useExternalScaling; + PermutationType m_permutation; + FVectorType m_wa1, m_wa2, m_wa3, m_wa4; //Temporary vectors + RealScalar m_par; + bool m_isInitialized; // Check whether the minimization step has been called + ComputationInfo m_info; +}; + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimize(FVectorType &x) +{ + LevenbergMarquardtSpace::Status status = minimizeInit(x); + if (status==LevenbergMarquardtSpace::ImproperInputParameters) { + m_isInitialized = true; + return status; + } + do { +// std::cout << " uv " << x.transpose() << "\n"; + status = minimizeOneStep(x); + } while (status==LevenbergMarquardtSpace::Running); + m_isInitialized = true; + return status; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeInit(FVectorType &x) +{ + n = x.size(); + m = m_functor.values(); + + m_wa1.resize(n); m_wa2.resize(n); m_wa3.resize(n); + m_wa4.resize(m); + m_fvec.resize(m); + //FIXME Sparse Case : Allocate space for the jacobian + m_fjac.resize(m, n); +// m_fjac.reserve(VectorXi::Constant(n,5)); // FIXME Find a better alternative + if (!m_useExternalScaling) + m_diag.resize(n); + eigen_assert( (!m_useExternalScaling || m_diag.size()==n) && "When m_useExternalScaling is set, the caller must provide a valid 'm_diag'"); + m_qtf.resize(n); + + /* Function Body */ + m_nfev = 0; + m_njev = 0; + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || m_ftol < 0. || m_xtol < 0. || m_gtol < 0. || m_maxfev <= 0 || m_factor <= 0.){ + m_info = InvalidInput; + return LevenbergMarquardtSpace::ImproperInputParameters; + } + + if (m_useExternalScaling) + for (Index j = 0; j < n; ++j) + if (m_diag[j] <= 0.) + { + m_info = InvalidInput; + return LevenbergMarquardtSpace::ImproperInputParameters; + } + + /* evaluate the function at the starting point */ + /* and calculate its norm. */ + m_nfev = 1; + if ( m_functor(x, m_fvec) < 0) + return LevenbergMarquardtSpace::UserAsked; + m_fnorm = m_fvec.stableNorm(); + + /* initialize levenberg-marquardt parameter and iteration counter. */ + m_par = 0.; + m_iter = 1; + + return LevenbergMarquardtSpace::NotStarted; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::lmder1( + FVectorType &x, + const Scalar tol + ) +{ + n = x.size(); + m = m_functor.values(); + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || tol < 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + resetParameters(); + m_ftol = tol; + m_xtol = tol; + m_maxfev = 100*(n+1); + + return minimize(x); +} + + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::lmdif1( + FunctorType &functor, + FVectorType &x, + Index *nfev, + const Scalar tol + ) +{ + Index n = x.size(); + Index m = functor.values(); + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || tol < 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + NumericalDiff numDiff(functor); + // embedded LevenbergMarquardt + LevenbergMarquardt > lm(numDiff); + lm.setFtol(tol); + lm.setXtol(tol); + lm.setMaxfev(200*(n+1)); + + LevenbergMarquardtSpace::Status info = LevenbergMarquardtSpace::Status(lm.minimize(x)); + if (nfev) + * nfev = lm.nfev(); + return info; +} + +} // end namespace Eigen + +#endif // EIGEN_LEVENBERGMARQUARDT_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..b737f3cfe2f946a513e8528c4eae5750adc4e9d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_MATRIX_FUNCTIONS_MODULE_H +#error "Please include unsupported/Eigen/MatrixFunctions instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h new file mode 100644 index 0000000000000000000000000000000000000000..ab6284a3ee33bd63c7600c1bf0bda20ee8d02647 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h @@ -0,0 +1,443 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009, 2010, 2013 Jitse Niesen +// Copyright (C) 2011, 2013 Chen-Pang He +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_EXPONENTIAL +#define EIGEN_MATRIX_EXPONENTIAL + +#include "StemFunction.h" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +/** \brief Scaling operator. + * + * This struct is used by CwiseUnaryOp to scale a matrix by \f$ 2^{-s} \f$. + */ +template +struct MatrixExponentialScalingOp +{ + /** \brief Constructor. + * + * \param[in] squarings The integer \f$ s \f$ in this document. + */ + MatrixExponentialScalingOp(int squarings) : m_squarings(squarings) { } + + + /** \brief Scale a matrix coefficient. + * + * \param[in,out] x The scalar to be scaled, becoming \f$ 2^{-s} x \f$. + */ + inline const RealScalar operator() (const RealScalar& x) const + { + using std::ldexp; + return ldexp(x, -m_squarings); + } + + typedef std::complex ComplexScalar; + + /** \brief Scale a matrix coefficient. + * + * \param[in,out] x The scalar to be scaled, becoming \f$ 2^{-s} x \f$. + */ + inline const ComplexScalar operator() (const ComplexScalar& x) const + { + using std::ldexp; + return ComplexScalar(ldexp(x.real(), -m_squarings), ldexp(x.imag(), -m_squarings)); + } + + private: + int m_squarings; +}; + +/** \brief Compute the (3,3)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + */ +template +void matrix_exp_pade3(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {120.L, 60.L, 12.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType tmp = b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + V = b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); +} + +/** \brief Compute the (5,5)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + */ +template +void matrix_exp_pade5(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {30240.L, 15120.L, 3360.L, 420.L, 30.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType A4 = A2 * A2; + const MatrixType tmp = b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + V = b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); +} + +/** \brief Compute the (7,7)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + */ +template +void matrix_exp_pade7(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {17297280.L, 8648640.L, 1995840.L, 277200.L, 25200.L, 1512.L, 56.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType A4 = A2 * A2; + const MatrixType A6 = A4 * A2; + const MatrixType tmp = b[7] * A6 + b[5] * A4 + b[3] * A2 + + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + V = b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); + +} + +/** \brief Compute the (9,9)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + */ +template +void matrix_exp_pade9(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {17643225600.L, 8821612800.L, 2075673600.L, 302702400.L, 30270240.L, + 2162160.L, 110880.L, 3960.L, 90.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType A4 = A2 * A2; + const MatrixType A6 = A4 * A2; + const MatrixType A8 = A6 * A2; + const MatrixType tmp = b[9] * A8 + b[7] * A6 + b[5] * A4 + b[3] * A2 + + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + V = b[8] * A8 + b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); +} + +/** \brief Compute the (13,13)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + */ +template +void matrix_exp_pade13(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {64764752532480000.L, 32382376266240000.L, 7771770303897600.L, + 1187353796428800.L, 129060195264000.L, 10559470521600.L, 670442572800.L, + 33522128640.L, 1323241920.L, 40840800.L, 960960.L, 16380.L, 182.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType A4 = A2 * A2; + const MatrixType A6 = A4 * A2; + V = b[13] * A6 + b[11] * A4 + b[9] * A2; // used for temporary storage + MatrixType tmp = A6 * V; + tmp += b[7] * A6 + b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + tmp = b[12] * A6 + b[10] * A4 + b[8] * A2; + V.noalias() = A6 * tmp; + V += b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); +} + +/** \brief Compute the (17,17)-Padé approximant to the exponential. + * + * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Padé + * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. + * + * This function activates only if your long double is double-double or quadruple. + */ +#if LDBL_MANT_DIG > 64 +template +void matrix_exp_pade17(const MatA& A, MatU& U, MatV& V) +{ + typedef typename MatA::PlainObject MatrixType; + typedef typename NumTraits::Scalar>::Real RealScalar; + const RealScalar b[] = {830034394580628357120000.L, 415017197290314178560000.L, + 100610229646136770560000.L, 15720348382208870400000.L, + 1774878043152614400000.L, 153822763739893248000.L, 10608466464820224000.L, + 595373117923584000.L, 27563570274240000.L, 1060137318240000.L, + 33924394183680.L, 899510451840.L, 19554575040.L, 341863200.L, 4651200.L, + 46512.L, 306.L, 1.L}; + const MatrixType A2 = A * A; + const MatrixType A4 = A2 * A2; + const MatrixType A6 = A4 * A2; + const MatrixType A8 = A4 * A4; + V = b[17] * A8 + b[15] * A6 + b[13] * A4 + b[11] * A2; // used for temporary storage + MatrixType tmp = A8 * V; + tmp += b[9] * A8 + b[7] * A6 + b[5] * A4 + b[3] * A2 + + b[1] * MatrixType::Identity(A.rows(), A.cols()); + U.noalias() = A * tmp; + tmp = b[16] * A8 + b[14] * A6 + b[12] * A4 + b[10] * A2; + V.noalias() = tmp * A8; + V += b[8] * A8 + b[6] * A6 + b[4] * A4 + b[2] * A2 + + b[0] * MatrixType::Identity(A.rows(), A.cols()); +} +#endif + +template ::Scalar>::Real> +struct matrix_exp_computeUV +{ + /** \brief Compute Padé approximant to the exponential. + * + * Computes \c U, \c V and \c squarings such that \f$ (V+U)(V-U)^{-1} \f$ is a Padé + * approximant of \f$ \exp(2^{-\mbox{squarings}}M) \f$ around \f$ M = 0 \f$, where \f$ M \f$ + * denotes the matrix \c arg. The degree of the Padé approximant and the value of squarings + * are chosen such that the approximation error is no more than the round-off error. + */ + static void run(const MatrixType& arg, MatrixType& U, MatrixType& V, int& squarings); +}; + +template +struct matrix_exp_computeUV +{ + template + static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) + { + using std::frexp; + using std::pow; + const float l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); + squarings = 0; + if (l1norm < 4.258730016922831e-001f) { + matrix_exp_pade3(arg, U, V); + } else if (l1norm < 1.880152677804762e+000f) { + matrix_exp_pade5(arg, U, V); + } else { + const float maxnorm = 3.925724783138660f; + frexp(l1norm / maxnorm, &squarings); + if (squarings < 0) squarings = 0; + MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp(squarings)); + matrix_exp_pade7(A, U, V); + } + } +}; + +template +struct matrix_exp_computeUV +{ + typedef typename NumTraits::Scalar>::Real RealScalar; + template + static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) + { + using std::frexp; + using std::pow; + const RealScalar l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); + squarings = 0; + if (l1norm < 1.495585217958292e-002) { + matrix_exp_pade3(arg, U, V); + } else if (l1norm < 2.539398330063230e-001) { + matrix_exp_pade5(arg, U, V); + } else if (l1norm < 9.504178996162932e-001) { + matrix_exp_pade7(arg, U, V); + } else if (l1norm < 2.097847961257068e+000) { + matrix_exp_pade9(arg, U, V); + } else { + const RealScalar maxnorm = 5.371920351148152; + frexp(l1norm / maxnorm, &squarings); + if (squarings < 0) squarings = 0; + MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp(squarings)); + matrix_exp_pade13(A, U, V); + } + } +}; + +template +struct matrix_exp_computeUV +{ + template + static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) + { +#if LDBL_MANT_DIG == 53 // double precision + matrix_exp_computeUV::run(arg, U, V, squarings); + +#else + + using std::frexp; + using std::pow; + const long double l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); + squarings = 0; + +#if LDBL_MANT_DIG <= 64 // extended precision + + if (l1norm < 4.1968497232266989671e-003L) { + matrix_exp_pade3(arg, U, V); + } else if (l1norm < 1.1848116734693823091e-001L) { + matrix_exp_pade5(arg, U, V); + } else if (l1norm < 5.5170388480686700274e-001L) { + matrix_exp_pade7(arg, U, V); + } else if (l1norm < 1.3759868875587845383e+000L) { + matrix_exp_pade9(arg, U, V); + } else { + const long double maxnorm = 4.0246098906697353063L; + frexp(l1norm / maxnorm, &squarings); + if (squarings < 0) squarings = 0; + MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp(squarings)); + matrix_exp_pade13(A, U, V); + } + +#elif LDBL_MANT_DIG <= 106 // double-double + + if (l1norm < 3.2787892205607026992947488108213e-005L) { + matrix_exp_pade3(arg, U, V); + } else if (l1norm < 6.4467025060072760084130906076332e-003L) { + matrix_exp_pade5(arg, U, V); + } else if (l1norm < 6.8988028496595374751374122881143e-002L) { + matrix_exp_pade7(arg, U, V); + } else if (l1norm < 2.7339737518502231741495857201670e-001L) { + matrix_exp_pade9(arg, U, V); + } else if (l1norm < 1.3203382096514474905666448850278e+000L) { + matrix_exp_pade13(arg, U, V); + } else { + const long double maxnorm = 3.2579440895405400856599663723517L; + frexp(l1norm / maxnorm, &squarings); + if (squarings < 0) squarings = 0; + MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp(squarings)); + matrix_exp_pade17(A, U, V); + } + +#elif LDBL_MANT_DIG <= 113 // quadruple precision + + if (l1norm < 1.639394610288918690547467954466970e-005L) { + matrix_exp_pade3(arg, U, V); + } else if (l1norm < 4.253237712165275566025884344433009e-003L) { + matrix_exp_pade5(arg, U, V); + } else if (l1norm < 5.125804063165764409885122032933142e-002L) { + matrix_exp_pade7(arg, U, V); + } else if (l1norm < 2.170000765161155195453205651889853e-001L) { + matrix_exp_pade9(arg, U, V); + } else if (l1norm < 1.125358383453143065081397882891878e+000L) { + matrix_exp_pade13(arg, U, V); + } else { + const long double maxnorm = 2.884233277829519311757165057717815L; + frexp(l1norm / maxnorm, &squarings); + if (squarings < 0) squarings = 0; + MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp(squarings)); + matrix_exp_pade17(A, U, V); + } + +#else + + // this case should be handled in compute() + eigen_assert(false && "Bug in MatrixExponential"); + +#endif +#endif // LDBL_MANT_DIG + } +}; + +template struct is_exp_known_type : false_type {}; +template<> struct is_exp_known_type : true_type {}; +template<> struct is_exp_known_type : true_type {}; +#if LDBL_MANT_DIG <= 113 +template<> struct is_exp_known_type : true_type {}; +#endif + +template +void matrix_exp_compute(const ArgType& arg, ResultType &result, true_type) // natively supported scalar type +{ + typedef typename ArgType::PlainObject MatrixType; + MatrixType U, V; + int squarings; + matrix_exp_computeUV::run(arg, U, V, squarings); // Pade approximant is (U+V) / (-U+V) + MatrixType numer = U + V; + MatrixType denom = -U + V; + result = denom.partialPivLu().solve(numer); + for (int i=0; i +void matrix_exp_compute(const ArgType& arg, ResultType &result, false_type) // default +{ + typedef typename ArgType::PlainObject MatrixType; + typedef typename traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef typename std::complex ComplexScalar; + result = arg.matrixFunction(internal::stem_function_exp); +} + +} // end namespace Eigen::internal + +/** \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix exponential of some matrix (expression). + * + * \tparam Derived Type of the argument to the matrix exponential. + * + * This class holds the argument to the matrix exponential until it is assigned or evaluated for + * some other reason (so the argument should not be changed in the meantime). It is the return type + * of MatrixBase::exp() and most of the time this is the only way it is used. + */ +template struct MatrixExponentialReturnValue +: public ReturnByValue > +{ + public: + /** \brief Constructor. + * + * \param src %Matrix (expression) forming the argument of the matrix exponential. + */ + MatrixExponentialReturnValue(const Derived& src) : m_src(src) { } + + /** \brief Compute the matrix exponential. + * + * \param result the matrix exponential of \p src in the constructor. + */ + template + inline void evalTo(ResultType& result) const + { + const typename internal::nested_eval::type tmp(m_src); + internal::matrix_exp_compute(tmp, result, internal::is_exp_known_type()); + } + + Index rows() const { return m_src.rows(); } + Index cols() const { return m_src.cols(); } + + protected: + const typename internal::ref_selector::type m_src; +}; + +namespace internal { +template +struct traits > +{ + typedef typename Derived::PlainObject ReturnType; +}; +} + +template +const MatrixExponentialReturnValue MatrixBase::exp() const +{ + eigen_assert(rows() == cols()); + return MatrixExponentialReturnValue(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_EXPONENTIAL diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixFunction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..8076bf5ab924b998c09ef2a709ac4ae751d47601 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixFunction.h @@ -0,0 +1,571 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2011, 2013 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_FUNCTION_H +#define EIGEN_MATRIX_FUNCTION_H + +#include "StemFunction.h" + + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \brief Maximum distance allowed between eigenvalues to be considered "close". */ +static const float matrix_function_separation = 0.1f; + +/** \ingroup MatrixFunctions_Module + * \class MatrixFunctionAtomic + * \brief Helper class for computing matrix functions of atomic matrices. + * + * Here, an atomic matrix is a triangular matrix whose diagonal entries are close to each other. + */ +template +class MatrixFunctionAtomic +{ + public: + + typedef typename MatrixType::Scalar Scalar; + typedef typename stem_function::type StemFunction; + + /** \brief Constructor + * \param[in] f matrix function to compute. + */ + MatrixFunctionAtomic(StemFunction f) : m_f(f) { } + + /** \brief Compute matrix function of atomic matrix + * \param[in] A argument of matrix function, should be upper triangular and atomic + * \returns f(A), the matrix function evaluated at the given matrix + */ + MatrixType compute(const MatrixType& A); + + private: + StemFunction* m_f; +}; + +template +typename NumTraits::Real matrix_function_compute_mu(const MatrixType& A) +{ + typedef typename plain_col_type::type VectorType; + Index rows = A.rows(); + const MatrixType N = MatrixType::Identity(rows, rows) - A; + VectorType e = VectorType::Ones(rows); + N.template triangularView().solveInPlace(e); + return e.cwiseAbs().maxCoeff(); +} + +template +MatrixType MatrixFunctionAtomic::compute(const MatrixType& A) +{ + // TODO: Use that A is upper triangular + typedef typename NumTraits::Real RealScalar; + Index rows = A.rows(); + Scalar avgEival = A.trace() / Scalar(RealScalar(rows)); + MatrixType Ashifted = A - avgEival * MatrixType::Identity(rows, rows); + RealScalar mu = matrix_function_compute_mu(Ashifted); + MatrixType F = m_f(avgEival, 0) * MatrixType::Identity(rows, rows); + MatrixType P = Ashifted; + MatrixType Fincr; + for (Index s = 1; double(s) < 1.1 * double(rows) + 10.0; s++) { // upper limit is fairly arbitrary + Fincr = m_f(avgEival, static_cast(s)) * P; + F += Fincr; + P = Scalar(RealScalar(1)/RealScalar(s + 1)) * P * Ashifted; + + // test whether Taylor series converged + const RealScalar F_norm = F.cwiseAbs().rowwise().sum().maxCoeff(); + const RealScalar Fincr_norm = Fincr.cwiseAbs().rowwise().sum().maxCoeff(); + if (Fincr_norm < NumTraits::epsilon() * F_norm) { + RealScalar delta = 0; + RealScalar rfactorial = 1; + for (Index r = 0; r < rows; r++) { + RealScalar mx = 0; + for (Index i = 0; i < rows; i++) + mx = (std::max)(mx, std::abs(m_f(Ashifted(i, i) + avgEival, static_cast(s+r)))); + if (r != 0) + rfactorial *= RealScalar(r); + delta = (std::max)(delta, mx / rfactorial); + } + const RealScalar P_norm = P.cwiseAbs().rowwise().sum().maxCoeff(); + if (mu * delta * P_norm < NumTraits::epsilon() * F_norm) // series converged + break; + } + } + return F; +} + +/** \brief Find cluster in \p clusters containing some value + * \param[in] key Value to find + * \returns Iterator to cluster containing \p key, or \c clusters.end() if no cluster in \p m_clusters + * contains \p key. + */ +template +typename ListOfClusters::iterator matrix_function_find_cluster(Index key, ListOfClusters& clusters) +{ + typename std::list::iterator j; + for (typename ListOfClusters::iterator i = clusters.begin(); i != clusters.end(); ++i) { + j = std::find(i->begin(), i->end(), key); + if (j != i->end()) + return i; + } + return clusters.end(); +} + +/** \brief Partition eigenvalues in clusters of ei'vals close to each other + * + * \param[in] eivals Eigenvalues + * \param[out] clusters Resulting partition of eigenvalues + * + * The partition satisfies the following two properties: + * # Any eigenvalue in a certain cluster is at most matrix_function_separation() away from another eigenvalue + * in the same cluster. + * # The distance between two eigenvalues in different clusters is more than matrix_function_separation(). + * The implementation follows Algorithm 4.1 in the paper of Davies and Higham. + */ +template +void matrix_function_partition_eigenvalues(const EivalsType& eivals, std::list& clusters) +{ + typedef typename EivalsType::RealScalar RealScalar; + for (Index i=0; i::iterator qi = matrix_function_find_cluster(i, clusters); + if (qi == clusters.end()) { + Cluster l; + l.push_back(i); + clusters.push_back(l); + qi = clusters.end(); + --qi; + } + + // Look for other element to add to the set + for (Index j=i+1; jbegin(), qi->end(), j) == qi->end()) { + typename std::list::iterator qj = matrix_function_find_cluster(j, clusters); + if (qj == clusters.end()) { + qi->push_back(j); + } else { + qi->insert(qi->end(), qj->begin(), qj->end()); + clusters.erase(qj); + } + } + } + } +} + +/** \brief Compute size of each cluster given a partitioning */ +template +void matrix_function_compute_cluster_size(const ListOfClusters& clusters, Matrix& clusterSize) +{ + const Index numClusters = static_cast(clusters.size()); + clusterSize.setZero(numClusters); + Index clusterIndex = 0; + for (typename ListOfClusters::const_iterator cluster = clusters.begin(); cluster != clusters.end(); ++cluster) { + clusterSize[clusterIndex] = cluster->size(); + ++clusterIndex; + } +} + +/** \brief Compute start of each block using clusterSize */ +template +void matrix_function_compute_block_start(const VectorType& clusterSize, VectorType& blockStart) +{ + blockStart.resize(clusterSize.rows()); + blockStart(0) = 0; + for (Index i = 1; i < clusterSize.rows(); i++) { + blockStart(i) = blockStart(i-1) + clusterSize(i-1); + } +} + +/** \brief Compute mapping of eigenvalue indices to cluster indices */ +template +void matrix_function_compute_map(const EivalsType& eivals, const ListOfClusters& clusters, VectorType& eivalToCluster) +{ + eivalToCluster.resize(eivals.rows()); + Index clusterIndex = 0; + for (typename ListOfClusters::const_iterator cluster = clusters.begin(); cluster != clusters.end(); ++cluster) { + for (Index i = 0; i < eivals.rows(); ++i) { + if (std::find(cluster->begin(), cluster->end(), i) != cluster->end()) { + eivalToCluster[i] = clusterIndex; + } + } + ++clusterIndex; + } +} + +/** \brief Compute permutation which groups ei'vals in same cluster together */ +template +void matrix_function_compute_permutation(const DynVectorType& blockStart, const DynVectorType& eivalToCluster, VectorType& permutation) +{ + DynVectorType indexNextEntry = blockStart; + permutation.resize(eivalToCluster.rows()); + for (Index i = 0; i < eivalToCluster.rows(); i++) { + Index cluster = eivalToCluster[i]; + permutation[i] = indexNextEntry[cluster]; + ++indexNextEntry[cluster]; + } +} + +/** \brief Permute Schur decomposition in U and T according to permutation */ +template +void matrix_function_permute_schur(VectorType& permutation, MatrixType& U, MatrixType& T) +{ + for (Index i = 0; i < permutation.rows() - 1; i++) { + Index j; + for (j = i; j < permutation.rows(); j++) { + if (permutation(j) == i) break; + } + eigen_assert(permutation(j) == i); + for (Index k = j-1; k >= i; k--) { + JacobiRotation rotation; + rotation.makeGivens(T(k, k+1), T(k+1, k+1) - T(k, k)); + T.applyOnTheLeft(k, k+1, rotation.adjoint()); + T.applyOnTheRight(k, k+1, rotation); + U.applyOnTheRight(k, k+1, rotation); + std::swap(permutation.coeffRef(k), permutation.coeffRef(k+1)); + } + } +} + +/** \brief Compute block diagonal part of matrix function. + * + * This routine computes the matrix function applied to the block diagonal part of \p T (which should be + * upper triangular), with the blocking given by \p blockStart and \p clusterSize. The matrix function of + * each diagonal block is computed by \p atomic. The off-diagonal parts of \p fT are set to zero. + */ +template +void matrix_function_compute_block_atomic(const MatrixType& T, AtomicType& atomic, const VectorType& blockStart, const VectorType& clusterSize, MatrixType& fT) +{ + fT.setZero(T.rows(), T.cols()); + for (Index i = 0; i < clusterSize.rows(); ++i) { + fT.block(blockStart(i), blockStart(i), clusterSize(i), clusterSize(i)) + = atomic.compute(T.block(blockStart(i), blockStart(i), clusterSize(i), clusterSize(i))); + } +} + +/** \brief Solve a triangular Sylvester equation AX + XB = C + * + * \param[in] A the matrix A; should be square and upper triangular + * \param[in] B the matrix B; should be square and upper triangular + * \param[in] C the matrix C; should have correct size. + * + * \returns the solution X. + * + * If A is m-by-m and B is n-by-n, then both C and X are m-by-n. The (i,j)-th component of the Sylvester + * equation is + * \f[ + * \sum_{k=i}^m A_{ik} X_{kj} + \sum_{k=1}^j X_{ik} B_{kj} = C_{ij}. + * \f] + * This can be re-arranged to yield: + * \f[ + * X_{ij} = \frac{1}{A_{ii} + B_{jj}} \Bigl( C_{ij} + * - \sum_{k=i+1}^m A_{ik} X_{kj} - \sum_{k=1}^{j-1} X_{ik} B_{kj} \Bigr). + * \f] + * It is assumed that A and B are such that the numerator is never zero (otherwise the Sylvester equation + * does not have a unique solution). In that case, these equations can be evaluated in the order + * \f$ i=m,\ldots,1 \f$ and \f$ j=1,\ldots,n \f$. + */ +template +MatrixType matrix_function_solve_triangular_sylvester(const MatrixType& A, const MatrixType& B, const MatrixType& C) +{ + eigen_assert(A.rows() == A.cols()); + eigen_assert(A.isUpperTriangular()); + eigen_assert(B.rows() == B.cols()); + eigen_assert(B.isUpperTriangular()); + eigen_assert(C.rows() == A.rows()); + eigen_assert(C.cols() == B.rows()); + + typedef typename MatrixType::Scalar Scalar; + + Index m = A.rows(); + Index n = B.rows(); + MatrixType X(m, n); + + for (Index i = m - 1; i >= 0; --i) { + for (Index j = 0; j < n; ++j) { + + // Compute AX = \sum_{k=i+1}^m A_{ik} X_{kj} + Scalar AX; + if (i == m - 1) { + AX = 0; + } else { + Matrix AXmatrix = A.row(i).tail(m-1-i) * X.col(j).tail(m-1-i); + AX = AXmatrix(0,0); + } + + // Compute XB = \sum_{k=1}^{j-1} X_{ik} B_{kj} + Scalar XB; + if (j == 0) { + XB = 0; + } else { + Matrix XBmatrix = X.row(i).head(j) * B.col(j).head(j); + XB = XBmatrix(0,0); + } + + X(i,j) = (C(i,j) - AX - XB) / (A(i,i) + B(j,j)); + } + } + return X; +} + +/** \brief Compute part of matrix function above block diagonal. + * + * This routine completes the computation of \p fT, denoting a matrix function applied to the triangular + * matrix \p T. It assumes that the block diagonal part of \p fT has already been computed. The part below + * the diagonal is zero, because \p T is upper triangular. + */ +template +void matrix_function_compute_above_diagonal(const MatrixType& T, const VectorType& blockStart, const VectorType& clusterSize, MatrixType& fT) +{ + typedef internal::traits Traits; + typedef typename MatrixType::Scalar Scalar; + static const int Options = MatrixType::Options; + typedef Matrix DynMatrixType; + + for (Index k = 1; k < clusterSize.rows(); k++) { + for (Index i = 0; i < clusterSize.rows() - k; i++) { + // compute (i, i+k) block + DynMatrixType A = T.block(blockStart(i), blockStart(i), clusterSize(i), clusterSize(i)); + DynMatrixType B = -T.block(blockStart(i+k), blockStart(i+k), clusterSize(i+k), clusterSize(i+k)); + DynMatrixType C = fT.block(blockStart(i), blockStart(i), clusterSize(i), clusterSize(i)) + * T.block(blockStart(i), blockStart(i+k), clusterSize(i), clusterSize(i+k)); + C -= T.block(blockStart(i), blockStart(i+k), clusterSize(i), clusterSize(i+k)) + * fT.block(blockStart(i+k), blockStart(i+k), clusterSize(i+k), clusterSize(i+k)); + for (Index m = i + 1; m < i + k; m++) { + C += fT.block(blockStart(i), blockStart(m), clusterSize(i), clusterSize(m)) + * T.block(blockStart(m), blockStart(i+k), clusterSize(m), clusterSize(i+k)); + C -= T.block(blockStart(i), blockStart(m), clusterSize(i), clusterSize(m)) + * fT.block(blockStart(m), blockStart(i+k), clusterSize(m), clusterSize(i+k)); + } + fT.block(blockStart(i), blockStart(i+k), clusterSize(i), clusterSize(i+k)) + = matrix_function_solve_triangular_sylvester(A, B, C); + } + } +} + +/** \ingroup MatrixFunctions_Module + * \brief Class for computing matrix functions. + * \tparam MatrixType type of the argument of the matrix function, + * expected to be an instantiation of the Matrix class template. + * \tparam AtomicType type for computing matrix function of atomic blocks. + * \tparam IsComplex used internally to select correct specialization. + * + * This class implements the Schur-Parlett algorithm for computing matrix functions. The spectrum of the + * matrix is divided in clustered of eigenvalues that lies close together. This class delegates the + * computation of the matrix function on every block corresponding to these clusters to an object of type + * \p AtomicType and uses these results to compute the matrix function of the whole matrix. The class + * \p AtomicType should have a \p compute() member function for computing the matrix function of a block. + * + * \sa class MatrixFunctionAtomic, class MatrixLogarithmAtomic + */ +template ::Scalar>::IsComplex> +struct matrix_function_compute +{ + /** \brief Compute the matrix function. + * + * \param[in] A argument of matrix function, should be a square matrix. + * \param[in] atomic class for computing matrix function of atomic blocks. + * \param[out] result the function \p f applied to \p A, as + * specified in the constructor. + * + * See MatrixBase::matrixFunction() for details on how this computation + * is implemented. + */ + template + static void run(const MatrixType& A, AtomicType& atomic, ResultType &result); +}; + +/** \internal \ingroup MatrixFunctions_Module + * \brief Partial specialization of MatrixFunction for real matrices + * + * This converts the real matrix to a complex matrix, compute the matrix function of that matrix, and then + * converts the result back to a real matrix. + */ +template +struct matrix_function_compute +{ + template + static void run(const MatA& A, AtomicType& atomic, ResultType &result) + { + typedef internal::traits Traits; + typedef typename Traits::Scalar Scalar; + static const int Rows = Traits::RowsAtCompileTime, Cols = Traits::ColsAtCompileTime; + static const int MaxRows = Traits::MaxRowsAtCompileTime, MaxCols = Traits::MaxColsAtCompileTime; + + typedef std::complex ComplexScalar; + typedef Matrix ComplexMatrix; + + ComplexMatrix CA = A.template cast(); + ComplexMatrix Cresult; + matrix_function_compute::run(CA, atomic, Cresult); + result = Cresult.real(); + } +}; + +/** \internal \ingroup MatrixFunctions_Module + * \brief Partial specialization of MatrixFunction for complex matrices + */ +template +struct matrix_function_compute +{ + template + static void run(const MatA& A, AtomicType& atomic, ResultType &result) + { + typedef internal::traits Traits; + + // compute Schur decomposition of A + const ComplexSchur schurOfA(A); + eigen_assert(schurOfA.info()==Success); + MatrixType T = schurOfA.matrixT(); + MatrixType U = schurOfA.matrixU(); + + // partition eigenvalues into clusters of ei'vals "close" to each other + std::list > clusters; + matrix_function_partition_eigenvalues(T.diagonal(), clusters); + + // compute size of each cluster + Matrix clusterSize; + matrix_function_compute_cluster_size(clusters, clusterSize); + + // blockStart[i] is row index at which block corresponding to i-th cluster starts + Matrix blockStart; + matrix_function_compute_block_start(clusterSize, blockStart); + + // compute map so that eivalToCluster[i] = j means that i-th ei'val is in j-th cluster + Matrix eivalToCluster; + matrix_function_compute_map(T.diagonal(), clusters, eivalToCluster); + + // compute permutation which groups ei'vals in same cluster together + Matrix permutation; + matrix_function_compute_permutation(blockStart, eivalToCluster, permutation); + + // permute Schur decomposition + matrix_function_permute_schur(permutation, U, T); + + // compute result + MatrixType fT; // matrix function applied to T + matrix_function_compute_block_atomic(T, atomic, blockStart, clusterSize, fT); + matrix_function_compute_above_diagonal(T, blockStart, clusterSize, fT); + result = U * (fT.template triangularView() * U.adjoint()); + } +}; + +} // end of namespace internal + +/** \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix function of some matrix (expression). + * + * \tparam Derived Type of the argument to the matrix function. + * + * This class holds the argument to the matrix function until it is assigned or evaluated for some other + * reason (so the argument should not be changed in the meantime). It is the return type of + * matrixBase::matrixFunction() and related functions and most of the time this is the only way it is used. + */ +template class MatrixFunctionReturnValue +: public ReturnByValue > +{ + public: + typedef typename Derived::Scalar Scalar; + typedef typename internal::stem_function::type StemFunction; + + protected: + typedef typename internal::ref_selector::type DerivedNested; + + public: + + /** \brief Constructor. + * + * \param[in] A %Matrix (expression) forming the argument of the matrix function. + * \param[in] f Stem function for matrix function under consideration. + */ + MatrixFunctionReturnValue(const Derived& A, StemFunction f) : m_A(A), m_f(f) { } + + /** \brief Compute the matrix function. + * + * \param[out] result \p f applied to \p A, where \p f and \p A are as in the constructor. + */ + template + inline void evalTo(ResultType& result) const + { + typedef typename internal::nested_eval::type NestedEvalType; + typedef internal::remove_all_t NestedEvalTypeClean; + typedef internal::traits Traits; + typedef std::complex::Real> ComplexScalar; + typedef Matrix DynMatrixType; + + typedef internal::MatrixFunctionAtomic AtomicType; + AtomicType atomic(m_f); + + internal::matrix_function_compute::run(m_A, atomic, result); + } + + Index rows() const { return m_A.rows(); } + Index cols() const { return m_A.cols(); } + + private: + const DerivedNested m_A; + StemFunction *m_f; +}; + +namespace internal { +template +struct traits > +{ + typedef typename Derived::PlainObject ReturnType; +}; +} + + +/********** MatrixBase methods **********/ + + +template +const MatrixFunctionReturnValue MatrixBase::matrixFunction(typename internal::stem_function::Scalar>::type f) const +{ + eigen_assert(rows() == cols()); + return MatrixFunctionReturnValue(derived(), f); +} + +template +const MatrixFunctionReturnValue MatrixBase::sin() const +{ + eigen_assert(rows() == cols()); + typedef typename internal::stem_function::ComplexScalar ComplexScalar; + return MatrixFunctionReturnValue(derived(), internal::stem_function_sin); +} + +template +const MatrixFunctionReturnValue MatrixBase::cos() const +{ + eigen_assert(rows() == cols()); + typedef typename internal::stem_function::ComplexScalar ComplexScalar; + return MatrixFunctionReturnValue(derived(), internal::stem_function_cos); +} + +template +const MatrixFunctionReturnValue MatrixBase::sinh() const +{ + eigen_assert(rows() == cols()); + typedef typename internal::stem_function::ComplexScalar ComplexScalar; + return MatrixFunctionReturnValue(derived(), internal::stem_function_sinh); +} + +template +const MatrixFunctionReturnValue MatrixBase::cosh() const +{ + eigen_assert(rows() == cols()); + typedef typename internal::stem_function::ComplexScalar ComplexScalar; + return MatrixFunctionReturnValue(derived(), internal::stem_function_cosh); +} + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_FUNCTION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h new file mode 100644 index 0000000000000000000000000000000000000000..2036fe471656a5bd8110a4b9573573c8e2300d8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h @@ -0,0 +1,375 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011, 2013 Jitse Niesen +// Copyright (C) 2011 Chen-Pang He +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_LOGARITHM +#define EIGEN_MATRIX_LOGARITHM + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +struct matrix_log_min_pade_degree +{ + static const int value = 3; +}; + +template +struct matrix_log_max_pade_degree +{ + typedef typename NumTraits::Real RealScalar; + static const int value = std::numeric_limits::digits<= 24? 5: // single precision + std::numeric_limits::digits<= 53? 7: // double precision + std::numeric_limits::digits<= 64? 8: // extended precision + std::numeric_limits::digits<=106? 10: // double-double + 11; // quadruple precision +}; + +/** \brief Compute logarithm of 2x2 triangular matrix. */ +template +void matrix_log_compute_2x2(const MatrixType& A, MatrixType& result) +{ + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + using std::abs; + using std::ceil; + using std::imag; + using std::log; + + Scalar logA00 = log(A(0,0)); + Scalar logA11 = log(A(1,1)); + + result(0,0) = logA00; + result(1,0) = Scalar(0); + result(1,1) = logA11; + + Scalar y = A(1,1) - A(0,0); + if (y==Scalar(0)) + { + result(0,1) = A(0,1) / A(0,0); + } + else if ((abs(A(0,0)) < RealScalar(0.5)*abs(A(1,1))) || (abs(A(0,0)) > 2*abs(A(1,1)))) + { + result(0,1) = A(0,1) * (logA11 - logA00) / y; + } + else + { + // computation in previous branch is inaccurate if A(1,1) \approx A(0,0) + RealScalar unwindingNumber = ceil((imag(logA11 - logA00) - RealScalar(EIGEN_PI)) / RealScalar(2*EIGEN_PI)); + result(0,1) = A(0,1) * (numext::log1p(y/A(0,0)) + Scalar(0,RealScalar(2*EIGEN_PI)*unwindingNumber)) / y; + } +} + +/* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = float) */ +inline int matrix_log_get_pade_degree(float normTminusI) +{ + const float maxNormForPade[] = { 2.5111573934555054e-1 /* degree = 3 */ , 4.0535837411880493e-1, + 5.3149729967117310e-1 }; + const int minPadeDegree = matrix_log_min_pade_degree::value; + const int maxPadeDegree = matrix_log_max_pade_degree::value; + int degree = minPadeDegree; + for (; degree <= maxPadeDegree; ++degree) + if (normTminusI <= maxNormForPade[degree - minPadeDegree]) + break; + return degree; +} + +/* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = double) */ +inline int matrix_log_get_pade_degree(double normTminusI) +{ + const double maxNormForPade[] = { 1.6206284795015624e-2 /* degree = 3 */ , 5.3873532631381171e-2, + 1.1352802267628681e-1, 1.8662860613541288e-1, 2.642960831111435e-1 }; + const int minPadeDegree = matrix_log_min_pade_degree::value; + const int maxPadeDegree = matrix_log_max_pade_degree::value; + int degree = minPadeDegree; + for (; degree <= maxPadeDegree; ++degree) + if (normTminusI <= maxNormForPade[degree - minPadeDegree]) + break; + return degree; +} + +/* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = long double) */ +inline int matrix_log_get_pade_degree(long double normTminusI) +{ +#if LDBL_MANT_DIG == 53 // double precision + const long double maxNormForPade[] = { 1.6206284795015624e-2L /* degree = 3 */ , 5.3873532631381171e-2L, + 1.1352802267628681e-1L, 1.8662860613541288e-1L, 2.642960831111435e-1L }; +#elif LDBL_MANT_DIG <= 64 // extended precision + const long double maxNormForPade[] = { 5.48256690357782863103e-3L /* degree = 3 */, 2.34559162387971167321e-2L, + 5.84603923897347449857e-2L, 1.08486423756725170223e-1L, 1.68385767881294446649e-1L, + 2.32777776523703892094e-1L }; +#elif LDBL_MANT_DIG <= 106 // double-double + const long double maxNormForPade[] = { 8.58970550342939562202529664318890e-5L /* degree = 3 */, + 9.34074328446359654039446552677759e-4L, 4.26117194647672175773064114582860e-3L, + 1.21546224740281848743149666560464e-2L, 2.61100544998339436713088248557444e-2L, + 4.66170074627052749243018566390567e-2L, 7.32585144444135027565872014932387e-2L, + 1.05026503471351080481093652651105e-1L }; +#else // quadruple precision + const long double maxNormForPade[] = { 4.7419931187193005048501568167858103e-5L /* degree = 3 */, + 5.8853168473544560470387769480192666e-4L, 2.9216120366601315391789493628113520e-3L, + 8.8415758124319434347116734705174308e-3L, 1.9850836029449446668518049562565291e-2L, + 3.6688019729653446926585242192447447e-2L, 5.9290962294020186998954055264528393e-2L, + 8.6998436081634343903250580992127677e-2L, 1.1880960220216759245467951592883642e-1L }; +#endif + const int minPadeDegree = matrix_log_min_pade_degree::value; + const int maxPadeDegree = matrix_log_max_pade_degree::value; + int degree = minPadeDegree; + for (; degree <= maxPadeDegree; ++degree) + if (normTminusI <= maxNormForPade[degree - minPadeDegree]) + break; + return degree; +} + +/* \brief Compute Pade approximation to matrix logarithm */ +template +void matrix_log_compute_pade(MatrixType& result, const MatrixType& T, int degree) +{ + typedef typename NumTraits::Real RealScalar; + const int minPadeDegree = 3; + const int maxPadeDegree = 11; + eigen_assert(degree >= minPadeDegree && degree <= maxPadeDegree); + // FIXME this creates float-conversion-warnings if these are enabled. + // Either manually convert each value, or disable the warning locally + const RealScalar nodes[][maxPadeDegree] = { + { 0.1127016653792583114820734600217600L, 0.5000000000000000000000000000000000L, // degree 3 + 0.8872983346207416885179265399782400L }, + { 0.0694318442029737123880267555535953L, 0.3300094782075718675986671204483777L, // degree 4 + 0.6699905217924281324013328795516223L, 0.9305681557970262876119732444464048L }, + { 0.0469100770306680036011865608503035L, 0.2307653449471584544818427896498956L, // degree 5 + 0.5000000000000000000000000000000000L, 0.7692346550528415455181572103501044L, + 0.9530899229693319963988134391496965L }, + { 0.0337652428984239860938492227530027L, 0.1693953067668677431693002024900473L, // degree 6 + 0.3806904069584015456847491391596440L, 0.6193095930415984543152508608403560L, + 0.8306046932331322568306997975099527L, 0.9662347571015760139061507772469973L }, + { 0.0254460438286207377369051579760744L, 0.1292344072003027800680676133596058L, // degree 7 + 0.2970774243113014165466967939615193L, 0.5000000000000000000000000000000000L, + 0.7029225756886985834533032060384807L, 0.8707655927996972199319323866403942L, + 0.9745539561713792622630948420239256L }, + { 0.0198550717512318841582195657152635L, 0.1016667612931866302042230317620848L, // degree 8 + 0.2372337950418355070911304754053768L, 0.4082826787521750975302619288199080L, + 0.5917173212478249024697380711800920L, 0.7627662049581644929088695245946232L, + 0.8983332387068133697957769682379152L, 0.9801449282487681158417804342847365L }, + { 0.0159198802461869550822118985481636L, 0.0819844463366821028502851059651326L, // degree 9 + 0.1933142836497048013456489803292629L, 0.3378732882980955354807309926783317L, + 0.5000000000000000000000000000000000L, 0.6621267117019044645192690073216683L, + 0.8066857163502951986543510196707371L, 0.9180155536633178971497148940348674L, + 0.9840801197538130449177881014518364L }, + { 0.0130467357414141399610179939577740L, 0.0674683166555077446339516557882535L, // degree 10 + 0.1602952158504877968828363174425632L, 0.2833023029353764046003670284171079L, + 0.4255628305091843945575869994351400L, 0.5744371694908156054424130005648600L, + 0.7166976970646235953996329715828921L, 0.8397047841495122031171636825574368L, + 0.9325316833444922553660483442117465L, 0.9869532642585858600389820060422260L }, + { 0.0108856709269715035980309994385713L, 0.0564687001159523504624211153480364L, // degree 11 + 0.1349239972129753379532918739844233L, 0.2404519353965940920371371652706952L, + 0.3652284220238275138342340072995692L, 0.5000000000000000000000000000000000L, + 0.6347715779761724861657659927004308L, 0.7595480646034059079628628347293048L, + 0.8650760027870246620467081260155767L, 0.9435312998840476495375788846519636L, + 0.9891143290730284964019690005614287L } }; + + const RealScalar weights[][maxPadeDegree] = { + { 0.2777777777777777777777777777777778L, 0.4444444444444444444444444444444444L, // degree 3 + 0.2777777777777777777777777777777778L }, + { 0.1739274225687269286865319746109997L, 0.3260725774312730713134680253890003L, // degree 4 + 0.3260725774312730713134680253890003L, 0.1739274225687269286865319746109997L }, + { 0.1184634425280945437571320203599587L, 0.2393143352496832340206457574178191L, // degree 5 + 0.2844444444444444444444444444444444L, 0.2393143352496832340206457574178191L, + 0.1184634425280945437571320203599587L }, + { 0.0856622461895851725201480710863665L, 0.1803807865240693037849167569188581L, // degree 6 + 0.2339569672863455236949351719947755L, 0.2339569672863455236949351719947755L, + 0.1803807865240693037849167569188581L, 0.0856622461895851725201480710863665L }, + { 0.0647424830844348466353057163395410L, 0.1398526957446383339507338857118898L, // degree 7 + 0.1909150252525594724751848877444876L, 0.2089795918367346938775510204081633L, + 0.1909150252525594724751848877444876L, 0.1398526957446383339507338857118898L, + 0.0647424830844348466353057163395410L }, + { 0.0506142681451881295762656771549811L, 0.1111905172266872352721779972131204L, // degree 8 + 0.1568533229389436436689811009933007L, 0.1813418916891809914825752246385978L, + 0.1813418916891809914825752246385978L, 0.1568533229389436436689811009933007L, + 0.1111905172266872352721779972131204L, 0.0506142681451881295762656771549811L }, + { 0.0406371941807872059859460790552618L, 0.0903240803474287020292360156214564L, // degree 9 + 0.1303053482014677311593714347093164L, 0.1561735385200014200343152032922218L, + 0.1651196775006298815822625346434870L, 0.1561735385200014200343152032922218L, + 0.1303053482014677311593714347093164L, 0.0903240803474287020292360156214564L, + 0.0406371941807872059859460790552618L }, + { 0.0333356721543440687967844049466659L, 0.0747256745752902965728881698288487L, // degree 10 + 0.1095431812579910219977674671140816L, 0.1346333596549981775456134607847347L, + 0.1477621123573764350869464973256692L, 0.1477621123573764350869464973256692L, + 0.1346333596549981775456134607847347L, 0.1095431812579910219977674671140816L, + 0.0747256745752902965728881698288487L, 0.0333356721543440687967844049466659L }, + { 0.0278342835580868332413768602212743L, 0.0627901847324523123173471496119701L, // degree 11 + 0.0931451054638671257130488207158280L, 0.1165968822959952399592618524215876L, + 0.1314022722551233310903444349452546L, 0.1364625433889503153572417641681711L, + 0.1314022722551233310903444349452546L, 0.1165968822959952399592618524215876L, + 0.0931451054638671257130488207158280L, 0.0627901847324523123173471496119701L, + 0.0278342835580868332413768602212743L } }; + + MatrixType TminusI = T - MatrixType::Identity(T.rows(), T.rows()); + result.setZero(T.rows(), T.rows()); + for (int k = 0; k < degree; ++k) { + RealScalar weight = weights[degree-minPadeDegree][k]; + RealScalar node = nodes[degree-minPadeDegree][k]; + result += weight * (MatrixType::Identity(T.rows(), T.rows()) + node * TminusI) + .template triangularView().solve(TminusI); + } +} + +/** \brief Compute logarithm of triangular matrices with size > 2. + * \details This uses a inverse scale-and-square algorithm. */ +template +void matrix_log_compute_big(const MatrixType& A, MatrixType& result) +{ + typedef typename MatrixType::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + using std::pow; + + int numberOfSquareRoots = 0; + int numberOfExtraSquareRoots = 0; + int degree; + MatrixType T = A, sqrtT; + + const int maxPadeDegree = matrix_log_max_pade_degree::value; + const RealScalar maxNormForPade = RealScalar( + maxPadeDegree<= 5? 5.3149729967117310e-1L: // single precision + maxPadeDegree<= 7? 2.6429608311114350e-1L: // double precision + maxPadeDegree<= 8? 2.32777776523703892094e-1L: // extended precision + maxPadeDegree<=10? 1.05026503471351080481093652651105e-1L: // double-double + 1.1880960220216759245467951592883642e-1L); // quadruple precision + + while (true) { + RealScalar normTminusI = (T - MatrixType::Identity(T.rows(), T.rows())).cwiseAbs().colwise().sum().maxCoeff(); + if (normTminusI < maxNormForPade) { + degree = matrix_log_get_pade_degree(normTminusI); + int degree2 = matrix_log_get_pade_degree(normTminusI / RealScalar(2)); + if ((degree - degree2 <= 1) || (numberOfExtraSquareRoots == 1)) + break; + ++numberOfExtraSquareRoots; + } + matrix_sqrt_triangular(T, sqrtT); + T = sqrtT.template triangularView(); + ++numberOfSquareRoots; + } + + matrix_log_compute_pade(result, T, degree); + result *= pow(RealScalar(2), RealScalar(numberOfSquareRoots)); // TODO replace by bitshift if possible +} + +/** \ingroup MatrixFunctions_Module + * \class MatrixLogarithmAtomic + * \brief Helper class for computing matrix logarithm of atomic matrices. + * + * Here, an atomic matrix is a triangular matrix whose diagonal entries are close to each other. + * + * \sa class MatrixFunctionAtomic, MatrixBase::log() + */ +template +class MatrixLogarithmAtomic +{ +public: + /** \brief Compute matrix logarithm of atomic matrix + * \param[in] A argument of matrix logarithm, should be upper triangular and atomic + * \returns The logarithm of \p A. + */ + MatrixType compute(const MatrixType& A); +}; + +template +MatrixType MatrixLogarithmAtomic::compute(const MatrixType& A) +{ + using std::log; + MatrixType result(A.rows(), A.rows()); + if (A.rows() == 1) + result(0,0) = log(A(0,0)); + else if (A.rows() == 2) + matrix_log_compute_2x2(A, result); + else + matrix_log_compute_big(A, result); + return result; +} + +} // end of namespace internal + +/** \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix logarithm of some matrix (expression). + * + * \tparam Derived Type of the argument to the matrix function. + * + * This class holds the argument to the matrix function until it is + * assigned or evaluated for some other reason (so the argument + * should not be changed in the meantime). It is the return type of + * MatrixBase::log() and most of the time this is the only way it + * is used. + */ +template class MatrixLogarithmReturnValue +: public ReturnByValue > +{ +public: + typedef typename Derived::Scalar Scalar; + typedef typename Derived::Index Index; + +protected: + typedef typename internal::ref_selector::type DerivedNested; + +public: + + /** \brief Constructor. + * + * \param[in] A %Matrix (expression) forming the argument of the matrix logarithm. + */ + explicit MatrixLogarithmReturnValue(const Derived& A) : m_A(A) { } + + /** \brief Compute the matrix logarithm. + * + * \param[out] result Logarithm of \c A, where \c A is as specified in the constructor. + */ + template + inline void evalTo(ResultType& result) const + { + typedef typename internal::nested_eval::type DerivedEvalType; + typedef internal::remove_all_t DerivedEvalTypeClean; + typedef internal::traits Traits; + typedef std::complex::Real> ComplexScalar; + typedef Matrix DynMatrixType; + typedef internal::MatrixLogarithmAtomic AtomicType; + AtomicType atomic; + + internal::matrix_function_compute::run(m_A, atomic, result); + } + + Index rows() const { return m_A.rows(); } + Index cols() const { return m_A.cols(); } + +private: + const DerivedNested m_A; +}; + +namespace internal { + template + struct traits > + { + typedef typename Derived::PlainObject ReturnType; + }; +} + + +/********** MatrixBase method **********/ + + +template +const MatrixLogarithmReturnValue MatrixBase::log() const +{ + eigen_assert(rows() == cols()); + return MatrixLogarithmReturnValue(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_LOGARITHM diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixPower.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixPower.h new file mode 100644 index 0000000000000000000000000000000000000000..aca717b4d03871fc4b087154367bdb7db258df3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixPower.h @@ -0,0 +1,707 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012, 2013 Chen-Pang He +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_POWER +#define EIGEN_MATRIX_POWER + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template class MatrixPower; + +/** + * \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix power of some matrix. + * + * \tparam MatrixType type of the base, a matrix. + * + * This class holds the arguments to the matrix power until it is + * assigned or evaluated for some other reason (so the argument + * should not be changed in the meantime). It is the return type of + * MatrixPower::operator() and related functions and most of the + * time this is the only way it is used. + */ +/* TODO This class is only used by MatrixPower, so it should be nested + * into MatrixPower, like MatrixPower::ReturnValue. However, my + * compiler complained about unused template parameter in the + * following declaration in namespace internal. + * + * template + * struct traits::ReturnValue>; + */ +template +class MatrixPowerParenthesesReturnValue : public ReturnByValue< MatrixPowerParenthesesReturnValue > +{ + public: + typedef typename MatrixType::RealScalar RealScalar; + + /** + * \brief Constructor. + * + * \param[in] pow %MatrixPower storing the base. + * \param[in] p scalar, the exponent of the matrix power. + */ + MatrixPowerParenthesesReturnValue(MatrixPower& pow, RealScalar p) : m_pow(pow), m_p(p) + { } + + /** + * \brief Compute the matrix power. + * + * \param[out] result + */ + template + inline void evalTo(ResultType& result) const + { m_pow.compute(result, m_p); } + + Index rows() const { return m_pow.rows(); } + Index cols() const { return m_pow.cols(); } + + private: + MatrixPower& m_pow; + const RealScalar m_p; +}; + +/** + * \ingroup MatrixFunctions_Module + * + * \brief Class for computing matrix powers. + * + * \tparam MatrixType type of the base, expected to be an instantiation + * of the Matrix class template. + * + * This class is capable of computing triangular real/complex matrices + * raised to a power in the interval \f$ (-1, 1) \f$. + * + * \note Currently this class is only used by MatrixPower. One may + * insist that this be nested into MatrixPower. This class is here to + * facilitate future development of triangular matrix functions. + */ +template +class MatrixPowerAtomic : internal::noncopyable +{ + private: + enum { + RowsAtCompileTime = MatrixType::RowsAtCompileTime, + MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime + }; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef std::complex ComplexScalar; + typedef Block ResultType; + + const MatrixType& m_A; + RealScalar m_p; + + void computePade(int degree, const MatrixType& IminusT, ResultType& res) const; + void compute2x2(ResultType& res, RealScalar p) const; + void computeBig(ResultType& res) const; + static int getPadeDegree(float normIminusT); + static int getPadeDegree(double normIminusT); + static int getPadeDegree(long double normIminusT); + static ComplexScalar computeSuperDiag(const ComplexScalar&, const ComplexScalar&, RealScalar p); + static RealScalar computeSuperDiag(RealScalar, RealScalar, RealScalar p); + + public: + /** + * \brief Constructor. + * + * \param[in] T the base of the matrix power. + * \param[in] p the exponent of the matrix power, should be in + * \f$ (-1, 1) \f$. + * + * The class stores a reference to T, so it should not be changed + * (or destroyed) before evaluation. Only the upper triangular + * part of T is read. + */ + MatrixPowerAtomic(const MatrixType& T, RealScalar p); + + /** + * \brief Compute the matrix power. + * + * \param[out] res \f$ A^p \f$ where A and p are specified in the + * constructor. + */ + void compute(ResultType& res) const; +}; + +template +MatrixPowerAtomic::MatrixPowerAtomic(const MatrixType& T, RealScalar p) : + m_A(T), m_p(p) +{ + eigen_assert(T.rows() == T.cols()); + eigen_assert(p > -1 && p < 1); +} + +template +void MatrixPowerAtomic::compute(ResultType& res) const +{ + using std::pow; + switch (m_A.rows()) { + case 0: + break; + case 1: + res(0,0) = pow(m_A(0,0), m_p); + break; + case 2: + compute2x2(res, m_p); + break; + default: + computeBig(res); + } +} + +template +void MatrixPowerAtomic::computePade(int degree, const MatrixType& IminusT, ResultType& res) const +{ + int i = 2*degree; + res = (m_p-RealScalar(degree)) / RealScalar(2*i-2) * IminusT; + + for (--i; i; --i) { + res = (MatrixType::Identity(IminusT.rows(), IminusT.cols()) + res).template triangularView() + .solve((i==1 ? -m_p : i&1 ? (-m_p-RealScalar(i/2))/RealScalar(2*i) : (m_p-RealScalar(i/2))/RealScalar(2*i-2)) * IminusT).eval(); + } + res += MatrixType::Identity(IminusT.rows(), IminusT.cols()); +} + +// This function assumes that res has the correct size (see bug 614) +template +void MatrixPowerAtomic::compute2x2(ResultType& res, RealScalar p) const +{ + using std::abs; + using std::pow; + res.coeffRef(0,0) = pow(m_A.coeff(0,0), p); + + for (Index i=1; i < m_A.cols(); ++i) { + res.coeffRef(i,i) = pow(m_A.coeff(i,i), p); + if (m_A.coeff(i-1,i-1) == m_A.coeff(i,i)) + res.coeffRef(i-1,i) = p * pow(m_A.coeff(i,i), p-1); + else if (2*abs(m_A.coeff(i-1,i-1)) < abs(m_A.coeff(i,i)) || 2*abs(m_A.coeff(i,i)) < abs(m_A.coeff(i-1,i-1))) + res.coeffRef(i-1,i) = (res.coeff(i,i)-res.coeff(i-1,i-1)) / (m_A.coeff(i,i)-m_A.coeff(i-1,i-1)); + else + res.coeffRef(i-1,i) = computeSuperDiag(m_A.coeff(i,i), m_A.coeff(i-1,i-1), p); + res.coeffRef(i-1,i) *= m_A.coeff(i-1,i); + } +} + +template +void MatrixPowerAtomic::computeBig(ResultType& res) const +{ + using std::ldexp; + const int digits = std::numeric_limits::digits; + const RealScalar maxNormForPade = RealScalar( + digits <= 24? 4.3386528e-1L // single precision + : digits <= 53? 2.789358995219730e-1L // double precision + : digits <= 64? 2.4471944416607995472e-1L // extended precision + : digits <= 106? 1.1016843812851143391275867258512e-1L // double-double + : 9.134603732914548552537150753385375e-2L); // quadruple precision + MatrixType IminusT, sqrtT, T = m_A.template triangularView(); + RealScalar normIminusT; + int degree, degree2, numberOfSquareRoots = 0; + bool hasExtraSquareRoot = false; + + for (Index i=0; i < m_A.cols(); ++i) + eigen_assert(m_A(i,i) != RealScalar(0)); + + while (true) { + IminusT = MatrixType::Identity(m_A.rows(), m_A.cols()) - T; + normIminusT = IminusT.cwiseAbs().colwise().sum().maxCoeff(); + if (normIminusT < maxNormForPade) { + degree = getPadeDegree(normIminusT); + degree2 = getPadeDegree(normIminusT/2); + if (degree - degree2 <= 1 || hasExtraSquareRoot) + break; + hasExtraSquareRoot = true; + } + matrix_sqrt_triangular(T, sqrtT); + T = sqrtT.template triangularView(); + ++numberOfSquareRoots; + } + computePade(degree, IminusT, res); + + for (; numberOfSquareRoots; --numberOfSquareRoots) { + compute2x2(res, ldexp(m_p, -numberOfSquareRoots)); + res = res.template triangularView() * res; + } + compute2x2(res, m_p); +} + +template +inline int MatrixPowerAtomic::getPadeDegree(float normIminusT) +{ + const float maxNormForPade[] = { 2.8064004e-1f /* degree = 3 */ , 4.3386528e-1f }; + int degree = 3; + for (; degree <= 4; ++degree) + if (normIminusT <= maxNormForPade[degree - 3]) + break; + return degree; +} + +template +inline int MatrixPowerAtomic::getPadeDegree(double normIminusT) +{ + const double maxNormForPade[] = { 1.884160592658218e-2 /* degree = 3 */ , 6.038881904059573e-2, 1.239917516308172e-1, + 1.999045567181744e-1, 2.789358995219730e-1 }; + int degree = 3; + for (; degree <= 7; ++degree) + if (normIminusT <= maxNormForPade[degree - 3]) + break; + return degree; +} + +template +inline int MatrixPowerAtomic::getPadeDegree(long double normIminusT) +{ +#if LDBL_MANT_DIG == 53 + const int maxPadeDegree = 7; + const double maxNormForPade[] = { 1.884160592658218e-2L /* degree = 3 */ , 6.038881904059573e-2L, 1.239917516308172e-1L, + 1.999045567181744e-1L, 2.789358995219730e-1L }; +#elif LDBL_MANT_DIG <= 64 + const int maxPadeDegree = 8; + const long double maxNormForPade[] = { 6.3854693117491799460e-3L /* degree = 3 */ , 2.6394893435456973676e-2L, + 6.4216043030404063729e-2L, 1.1701165502926694307e-1L, 1.7904284231268670284e-1L, 2.4471944416607995472e-1L }; +#elif LDBL_MANT_DIG <= 106 + const int maxPadeDegree = 10; + const double maxNormForPade[] = { 1.0007161601787493236741409687186e-4L /* degree = 3 */ , + 1.0007161601787493236741409687186e-3L, 4.7069769360887572939882574746264e-3L, 1.3220386624169159689406653101695e-2L, + 2.8063482381631737920612944054906e-2L, 4.9625993951953473052385361085058e-2L, 7.7367040706027886224557538328171e-2L, + 1.1016843812851143391275867258512e-1L }; +#else + const int maxPadeDegree = 10; + const double maxNormForPade[] = { 5.524506147036624377378713555116378e-5L /* degree = 3 */ , + 6.640600568157479679823602193345995e-4L, 3.227716520106894279249709728084626e-3L, + 9.619593944683432960546978734646284e-3L, 2.134595382433742403911124458161147e-2L, + 3.908166513900489428442993794761185e-2L, 6.266780814639442865832535460550138e-2L, + 9.134603732914548552537150753385375e-2L }; +#endif + int degree = 3; + for (; degree <= maxPadeDegree; ++degree) + if (normIminusT <= static_cast(maxNormForPade[degree - 3])) + break; + return degree; +} + +template +inline typename MatrixPowerAtomic::ComplexScalar +MatrixPowerAtomic::computeSuperDiag(const ComplexScalar& curr, const ComplexScalar& prev, RealScalar p) +{ + using std::ceil; + using std::exp; + using std::log; + using std::sinh; + + ComplexScalar logCurr = log(curr); + ComplexScalar logPrev = log(prev); + RealScalar unwindingNumber = ceil((numext::imag(logCurr - logPrev) - RealScalar(EIGEN_PI)) / RealScalar(2*EIGEN_PI)); + ComplexScalar w = numext::log1p((curr-prev)/prev)/RealScalar(2) + ComplexScalar(0, RealScalar(EIGEN_PI)*unwindingNumber); + return RealScalar(2) * exp(RealScalar(0.5) * p * (logCurr + logPrev)) * sinh(p * w) / (curr - prev); +} + +template +inline typename MatrixPowerAtomic::RealScalar +MatrixPowerAtomic::computeSuperDiag(RealScalar curr, RealScalar prev, RealScalar p) +{ + using std::exp; + using std::log; + using std::sinh; + + RealScalar w = numext::log1p((curr-prev)/prev)/RealScalar(2); + return 2 * exp(p * (log(curr) + log(prev)) / 2) * sinh(p * w) / (curr - prev); +} + +/** + * \ingroup MatrixFunctions_Module + * + * \brief Class for computing matrix powers. + * + * \tparam MatrixType type of the base, expected to be an instantiation + * of the Matrix class template. + * + * This class is capable of computing real/complex matrices raised to + * an arbitrary real power. Meanwhile, it saves the result of Schur + * decomposition if an non-integral power has even been calculated. + * Therefore, if you want to compute multiple (>= 2) matrix powers + * for the same matrix, using the class directly is more efficient than + * calling MatrixBase::pow(). + * + * Example: + * \include MatrixPower_optimal.cpp + * Output: \verbinclude MatrixPower_optimal.out + */ +template +class MatrixPower : internal::noncopyable +{ + private: + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + + public: + /** + * \brief Constructor. + * + * \param[in] A the base of the matrix power. + * + * The class stores a reference to A, so it should not be changed + * (or destroyed) before evaluation. + */ + explicit MatrixPower(const MatrixType& A) : + m_A(A), + m_conditionNumber(0), + m_rank(A.cols()), + m_nulls(0) + { eigen_assert(A.rows() == A.cols()); } + + /** + * \brief Returns the matrix power. + * + * \param[in] p exponent, a real scalar. + * \return The expression \f$ A^p \f$, where A is specified in the + * constructor. + */ + const MatrixPowerParenthesesReturnValue operator()(RealScalar p) + { return MatrixPowerParenthesesReturnValue(*this, p); } + + /** + * \brief Compute the matrix power. + * + * \param[in] p exponent, a real scalar. + * \param[out] res \f$ A^p \f$ where A is specified in the + * constructor. + */ + template + void compute(ResultType& res, RealScalar p); + + Index rows() const { return m_A.rows(); } + Index cols() const { return m_A.cols(); } + + private: + typedef std::complex ComplexScalar; + typedef Matrix ComplexMatrix; + + /** \brief Reference to the base of matrix power. */ + typename MatrixType::Nested m_A; + + /** \brief Temporary storage. */ + MatrixType m_tmp; + + /** \brief Store the result of Schur decomposition. */ + ComplexMatrix m_T, m_U; + + /** \brief Store fractional power of m_T. */ + ComplexMatrix m_fT; + + /** + * \brief Condition number of m_A. + * + * It is initialized as 0 to avoid performing unnecessary Schur + * decomposition, which is the bottleneck. + */ + RealScalar m_conditionNumber; + + /** \brief Rank of m_A. */ + Index m_rank; + + /** \brief Rank deficiency of m_A. */ + Index m_nulls; + + /** + * \brief Split p into integral part and fractional part. + * + * \param[in] p The exponent. + * \param[out] p The fractional part ranging in \f$ (-1, 1) \f$. + * \param[out] intpart The integral part. + * + * Only if the fractional part is nonzero, it calls initialize(). + */ + void split(RealScalar& p, RealScalar& intpart); + + /** \brief Perform Schur decomposition for fractional power. */ + void initialize(); + + template + void computeIntPower(ResultType& res, RealScalar p); + + template + void computeFracPower(ResultType& res, RealScalar p); + + template + static void revertSchur( + Matrix& res, + const ComplexMatrix& T, + const ComplexMatrix& U); + + template + static void revertSchur( + Matrix& res, + const ComplexMatrix& T, + const ComplexMatrix& U); +}; + +template +template +void MatrixPower::compute(ResultType& res, RealScalar p) +{ + using std::pow; + switch (cols()) { + case 0: + break; + case 1: + res(0,0) = pow(m_A.coeff(0,0), p); + break; + default: + RealScalar intpart; + split(p, intpart); + + res = MatrixType::Identity(rows(), cols()); + computeIntPower(res, intpart); + if (p) computeFracPower(res, p); + } +} + +template +void MatrixPower::split(RealScalar& p, RealScalar& intpart) +{ + using std::floor; + using std::pow; + + intpart = floor(p); + p -= intpart; + + // Perform Schur decomposition if it is not yet performed and the power is + // not an integer. + if (!m_conditionNumber && p) + initialize(); + + // Choose the more stable of intpart = floor(p) and intpart = ceil(p). + if (p > RealScalar(0.5) && p > (1-p) * pow(m_conditionNumber, p)) { + --p; + ++intpart; + } +} + +template +void MatrixPower::initialize() +{ + const ComplexSchur schurOfA(m_A); + JacobiRotation rot; + ComplexScalar eigenvalue; + + m_fT.resizeLike(m_A); + m_T = schurOfA.matrixT(); + m_U = schurOfA.matrixU(); + m_conditionNumber = m_T.diagonal().array().abs().maxCoeff() / m_T.diagonal().array().abs().minCoeff(); + + // Move zero eigenvalues to the bottom right corner. + for (Index i = cols()-1; i>=0; --i) { + if (m_rank <= 2) + return; + if (m_T.coeff(i,i) == RealScalar(0)) { + for (Index j=i+1; j < m_rank; ++j) { + eigenvalue = m_T.coeff(j,j); + rot.makeGivens(m_T.coeff(j-1,j), eigenvalue); + m_T.applyOnTheRight(j-1, j, rot); + m_T.applyOnTheLeft(j-1, j, rot.adjoint()); + m_T.coeffRef(j-1,j-1) = eigenvalue; + m_T.coeffRef(j,j) = RealScalar(0); + m_U.applyOnTheRight(j-1, j, rot); + } + --m_rank; + } + } + + m_nulls = rows() - m_rank; + if (m_nulls) { + eigen_assert(m_T.bottomRightCorner(m_nulls, m_nulls).isZero() + && "Base of matrix power should be invertible or with a semisimple zero eigenvalue."); + m_fT.bottomRows(m_nulls).fill(RealScalar(0)); + } +} + +template +template +void MatrixPower::computeIntPower(ResultType& res, RealScalar p) +{ + using std::abs; + using std::fmod; + RealScalar pp = abs(p); + + if (p<0) + m_tmp = m_A.inverse(); + else + m_tmp = m_A; + + while (true) { + if (fmod(pp, 2) >= 1) + res = m_tmp * res; + pp /= 2; + if (pp < 1) + break; + m_tmp *= m_tmp; + } +} + +template +template +void MatrixPower::computeFracPower(ResultType& res, RealScalar p) +{ + Block blockTp(m_fT, 0, 0, m_rank, m_rank); + eigen_assert(m_conditionNumber); + eigen_assert(m_rank + m_nulls == rows()); + + MatrixPowerAtomic(m_T.topLeftCorner(m_rank, m_rank), p).compute(blockTp); + if (m_nulls) { + m_fT.topRightCorner(m_rank, m_nulls) = m_T.topLeftCorner(m_rank, m_rank).template triangularView() + .solve(blockTp * m_T.topRightCorner(m_rank, m_nulls)); + } + revertSchur(m_tmp, m_fT, m_U); + res = m_tmp * res; +} + +template +template +inline void MatrixPower::revertSchur( + Matrix& res, + const ComplexMatrix& T, + const ComplexMatrix& U) +{ res.noalias() = U * (T.template triangularView() * U.adjoint()); } + +template +template +inline void MatrixPower::revertSchur( + Matrix& res, + const ComplexMatrix& T, + const ComplexMatrix& U) +{ res.noalias() = (U * (T.template triangularView() * U.adjoint())).real(); } + +/** + * \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix power of some matrix (expression). + * + * \tparam Derived type of the base, a matrix (expression). + * + * This class holds the arguments to the matrix power until it is + * assigned or evaluated for some other reason (so the argument + * should not be changed in the meantime). It is the return type of + * MatrixBase::pow() and related functions and most of the + * time this is the only way it is used. + */ +template +class MatrixPowerReturnValue : public ReturnByValue< MatrixPowerReturnValue > +{ + public: + typedef typename Derived::PlainObject PlainObject; + typedef typename Derived::RealScalar RealScalar; + + /** + * \brief Constructor. + * + * \param[in] A %Matrix (expression), the base of the matrix power. + * \param[in] p real scalar, the exponent of the matrix power. + */ + MatrixPowerReturnValue(const Derived& A, RealScalar p) : m_A(A), m_p(p) + { } + + /** + * \brief Compute the matrix power. + * + * \param[out] result \f$ A^p \f$ where \p A and \p p are as in the + * constructor. + */ + template + inline void evalTo(ResultType& result) const + { MatrixPower(m_A.eval()).compute(result, m_p); } + + Index rows() const { return m_A.rows(); } + Index cols() const { return m_A.cols(); } + + private: + const Derived& m_A; + const RealScalar m_p; +}; + +/** + * \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix power of some matrix (expression). + * + * \tparam Derived type of the base, a matrix (expression). + * + * This class holds the arguments to the matrix power until it is + * assigned or evaluated for some other reason (so the argument + * should not be changed in the meantime). It is the return type of + * MatrixBase::pow() and related functions and most of the + * time this is the only way it is used. + */ +template +class MatrixComplexPowerReturnValue : public ReturnByValue< MatrixComplexPowerReturnValue > +{ + public: + typedef typename Derived::PlainObject PlainObject; + typedef typename std::complex ComplexScalar; + + /** + * \brief Constructor. + * + * \param[in] A %Matrix (expression), the base of the matrix power. + * \param[in] p complex scalar, the exponent of the matrix power. + */ + MatrixComplexPowerReturnValue(const Derived& A, const ComplexScalar& p) : m_A(A), m_p(p) + { } + + /** + * \brief Compute the matrix power. + * + * Because \p p is complex, \f$ A^p \f$ is simply evaluated as \f$ + * \exp(p \log(A)) \f$. + * + * \param[out] result \f$ A^p \f$ where \p A and \p p are as in the + * constructor. + */ + template + inline void evalTo(ResultType& result) const + { result = (m_p * m_A.log()).exp(); } + + Index rows() const { return m_A.rows(); } + Index cols() const { return m_A.cols(); } + + private: + const Derived& m_A; + const ComplexScalar m_p; +}; + +namespace internal { + +template +struct traits< MatrixPowerParenthesesReturnValue > +{ typedef typename MatrixPowerType::PlainObject ReturnType; }; + +template +struct traits< MatrixPowerReturnValue > +{ typedef typename Derived::PlainObject ReturnType; }; + +template +struct traits< MatrixComplexPowerReturnValue > +{ typedef typename Derived::PlainObject ReturnType; }; + +} + +template +const MatrixPowerReturnValue MatrixBase::pow(const RealScalar& p) const +{ return MatrixPowerReturnValue(derived(), p); } + +template +const MatrixComplexPowerReturnValue MatrixBase::pow(const std::complex& p) const +{ return MatrixComplexPowerReturnValue(derived(), p); } + +} // namespace Eigen + +#endif // EIGEN_MATRIX_POWER diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixSquareRoot.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixSquareRoot.h new file mode 100644 index 0000000000000000000000000000000000000000..6c58cae669af0459640e55eb30e25c880c0e6a82 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/MatrixSquareRoot.h @@ -0,0 +1,370 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011, 2013 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_SQUARE_ROOT +#define EIGEN_MATRIX_SQUARE_ROOT + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +// pre: T.block(i,i,2,2) has complex conjugate eigenvalues +// post: sqrtT.block(i,i,2,2) is square root of T.block(i,i,2,2) +template +void matrix_sqrt_quasi_triangular_2x2_diagonal_block(const MatrixType& T, Index i, ResultType& sqrtT) +{ + // TODO: This case (2-by-2 blocks with complex conjugate eigenvalues) is probably hidden somewhere + // in EigenSolver. If we expose it, we could call it directly from here. + typedef typename traits::Scalar Scalar; + Matrix block = T.template block<2,2>(i,i); + EigenSolver > es(block); + sqrtT.template block<2,2>(i,i) + = (es.eigenvectors() * es.eigenvalues().cwiseSqrt().asDiagonal() * es.eigenvectors().inverse()).real(); +} + +// pre: block structure of T is such that (i,j) is a 1x1 block, +// all blocks of sqrtT to left of and below (i,j) are correct +// post: sqrtT(i,j) has the correct value +template +void matrix_sqrt_quasi_triangular_1x1_off_diagonal_block(const MatrixType& T, Index i, Index j, ResultType& sqrtT) +{ + typedef typename traits::Scalar Scalar; + Scalar tmp = (sqrtT.row(i).segment(i+1,j-i-1) * sqrtT.col(j).segment(i+1,j-i-1)).value(); + sqrtT.coeffRef(i,j) = (T.coeff(i,j) - tmp) / (sqrtT.coeff(i,i) + sqrtT.coeff(j,j)); +} + +// similar to compute1x1offDiagonalBlock() +template +void matrix_sqrt_quasi_triangular_1x2_off_diagonal_block(const MatrixType& T, Index i, Index j, ResultType& sqrtT) +{ + typedef typename traits::Scalar Scalar; + Matrix rhs = T.template block<1,2>(i,j); + if (j-i > 1) + rhs -= sqrtT.block(i, i+1, 1, j-i-1) * sqrtT.block(i+1, j, j-i-1, 2); + Matrix A = sqrtT.coeff(i,i) * Matrix::Identity(); + A += sqrtT.template block<2,2>(j,j).transpose(); + sqrtT.template block<1,2>(i,j).transpose() = A.fullPivLu().solve(rhs.transpose()); +} + +// similar to compute1x1offDiagonalBlock() +template +void matrix_sqrt_quasi_triangular_2x1_off_diagonal_block(const MatrixType& T, Index i, Index j, ResultType& sqrtT) +{ + typedef typename traits::Scalar Scalar; + Matrix rhs = T.template block<2,1>(i,j); + if (j-i > 2) + rhs -= sqrtT.block(i, i+2, 2, j-i-2) * sqrtT.block(i+2, j, j-i-2, 1); + Matrix A = sqrtT.coeff(j,j) * Matrix::Identity(); + A += sqrtT.template block<2,2>(i,i); + sqrtT.template block<2,1>(i,j) = A.fullPivLu().solve(rhs); +} + +// solves the equation A X + X B = C where all matrices are 2-by-2 +template +void matrix_sqrt_quasi_triangular_solve_auxiliary_equation(MatrixType& X, const MatrixType& A, const MatrixType& B, const MatrixType& C) +{ + typedef typename traits::Scalar Scalar; + Matrix coeffMatrix = Matrix::Zero(); + coeffMatrix.coeffRef(0,0) = A.coeff(0,0) + B.coeff(0,0); + coeffMatrix.coeffRef(1,1) = A.coeff(0,0) + B.coeff(1,1); + coeffMatrix.coeffRef(2,2) = A.coeff(1,1) + B.coeff(0,0); + coeffMatrix.coeffRef(3,3) = A.coeff(1,1) + B.coeff(1,1); + coeffMatrix.coeffRef(0,1) = B.coeff(1,0); + coeffMatrix.coeffRef(0,2) = A.coeff(0,1); + coeffMatrix.coeffRef(1,0) = B.coeff(0,1); + coeffMatrix.coeffRef(1,3) = A.coeff(0,1); + coeffMatrix.coeffRef(2,0) = A.coeff(1,0); + coeffMatrix.coeffRef(2,3) = B.coeff(1,0); + coeffMatrix.coeffRef(3,1) = A.coeff(1,0); + coeffMatrix.coeffRef(3,2) = B.coeff(0,1); + + Matrix rhs; + rhs.coeffRef(0) = C.coeff(0,0); + rhs.coeffRef(1) = C.coeff(0,1); + rhs.coeffRef(2) = C.coeff(1,0); + rhs.coeffRef(3) = C.coeff(1,1); + + Matrix result; + result = coeffMatrix.fullPivLu().solve(rhs); + + X.coeffRef(0,0) = result.coeff(0); + X.coeffRef(0,1) = result.coeff(1); + X.coeffRef(1,0) = result.coeff(2); + X.coeffRef(1,1) = result.coeff(3); +} + +// similar to compute1x1offDiagonalBlock() +template +void matrix_sqrt_quasi_triangular_2x2_off_diagonal_block(const MatrixType& T, Index i, Index j, ResultType& sqrtT) +{ + typedef typename traits::Scalar Scalar; + Matrix A = sqrtT.template block<2,2>(i,i); + Matrix B = sqrtT.template block<2,2>(j,j); + Matrix C = T.template block<2,2>(i,j); + if (j-i > 2) + C -= sqrtT.block(i, i+2, 2, j-i-2) * sqrtT.block(i+2, j, j-i-2, 2); + Matrix X; + matrix_sqrt_quasi_triangular_solve_auxiliary_equation(X, A, B, C); + sqrtT.template block<2,2>(i,j) = X; +} + +// pre: T is quasi-upper-triangular and sqrtT is a zero matrix of the same size +// post: the diagonal blocks of sqrtT are the square roots of the diagonal blocks of T +template +void matrix_sqrt_quasi_triangular_diagonal(const MatrixType& T, ResultType& sqrtT) +{ + using std::sqrt; + const Index size = T.rows(); + for (Index i = 0; i < size; i++) { + if (i == size - 1 || T.coeff(i+1, i) == 0) { + eigen_assert(T(i,i) >= 0); + sqrtT.coeffRef(i,i) = sqrt(T.coeff(i,i)); + } + else { + matrix_sqrt_quasi_triangular_2x2_diagonal_block(T, i, sqrtT); + ++i; + } + } +} + +// pre: T is quasi-upper-triangular and diagonal blocks of sqrtT are square root of diagonal blocks of T. +// post: sqrtT is the square root of T. +template +void matrix_sqrt_quasi_triangular_off_diagonal(const MatrixType& T, ResultType& sqrtT) +{ + const Index size = T.rows(); + for (Index j = 1; j < size; j++) { + if (T.coeff(j, j-1) != 0) // if T(j-1:j, j-1:j) is a 2-by-2 block + continue; + for (Index i = j-1; i >= 0; i--) { + if (i > 0 && T.coeff(i, i-1) != 0) // if T(i-1:i, i-1:i) is a 2-by-2 block + continue; + bool iBlockIs2x2 = (i < size - 1) && (T.coeff(i+1, i) != 0); + bool jBlockIs2x2 = (j < size - 1) && (T.coeff(j+1, j) != 0); + if (iBlockIs2x2 && jBlockIs2x2) + matrix_sqrt_quasi_triangular_2x2_off_diagonal_block(T, i, j, sqrtT); + else if (iBlockIs2x2 && !jBlockIs2x2) + matrix_sqrt_quasi_triangular_2x1_off_diagonal_block(T, i, j, sqrtT); + else if (!iBlockIs2x2 && jBlockIs2x2) + matrix_sqrt_quasi_triangular_1x2_off_diagonal_block(T, i, j, sqrtT); + else if (!iBlockIs2x2 && !jBlockIs2x2) + matrix_sqrt_quasi_triangular_1x1_off_diagonal_block(T, i, j, sqrtT); + } + } +} + +} // end of namespace internal + +/** \ingroup MatrixFunctions_Module + * \brief Compute matrix square root of quasi-triangular matrix. + * + * \tparam MatrixType type of \p arg, the argument of matrix square root, + * expected to be an instantiation of the Matrix class template. + * \tparam ResultType type of \p result, where result is to be stored. + * \param[in] arg argument of matrix square root. + * \param[out] result matrix square root of upper Hessenberg part of \p arg. + * + * This function computes the square root of the upper quasi-triangular matrix stored in the upper + * Hessenberg part of \p arg. Only the upper Hessenberg part of \p result is updated, the rest is + * not touched. See MatrixBase::sqrt() for details on how this computation is implemented. + * + * \sa MatrixSquareRoot, MatrixSquareRootQuasiTriangular + */ +template +void matrix_sqrt_quasi_triangular(const MatrixType &arg, ResultType &result) +{ + eigen_assert(arg.rows() == arg.cols()); + result.resize(arg.rows(), arg.cols()); + internal::matrix_sqrt_quasi_triangular_diagonal(arg, result); + internal::matrix_sqrt_quasi_triangular_off_diagonal(arg, result); +} + + +/** \ingroup MatrixFunctions_Module + * \brief Compute matrix square root of triangular matrix. + * + * \tparam MatrixType type of \p arg, the argument of matrix square root, + * expected to be an instantiation of the Matrix class template. + * \tparam ResultType type of \p result, where result is to be stored. + * \param[in] arg argument of matrix square root. + * \param[out] result matrix square root of upper triangular part of \p arg. + * + * Only the upper triangular part (including the diagonal) of \p result is updated, the rest is not + * touched. See MatrixBase::sqrt() for details on how this computation is implemented. + * + * \sa MatrixSquareRoot, MatrixSquareRootQuasiTriangular + */ +template +void matrix_sqrt_triangular(const MatrixType &arg, ResultType &result) +{ + using std::sqrt; + typedef typename MatrixType::Scalar Scalar; + + eigen_assert(arg.rows() == arg.cols()); + + // Compute square root of arg and store it in upper triangular part of result + // This uses that the square root of triangular matrices can be computed directly. + result.resize(arg.rows(), arg.cols()); + for (Index i = 0; i < arg.rows(); i++) { + result.coeffRef(i,i) = sqrt(arg.coeff(i,i)); + } + for (Index j = 1; j < arg.cols(); j++) { + for (Index i = j-1; i >= 0; i--) { + // if i = j-1, then segment has length 0 so tmp = 0 + Scalar tmp = (result.row(i).segment(i+1,j-i-1) * result.col(j).segment(i+1,j-i-1)).value(); + // denominator may be zero if original matrix is singular + result.coeffRef(i,j) = (arg.coeff(i,j) - tmp) / (result.coeff(i,i) + result.coeff(j,j)); + } + } +} + + +namespace internal { + +/** \ingroup MatrixFunctions_Module + * \brief Helper struct for computing matrix square roots of general matrices. + * \tparam MatrixType type of the argument of the matrix square root, + * expected to be an instantiation of the Matrix class template. + * + * \sa MatrixSquareRootTriangular, MatrixSquareRootQuasiTriangular, MatrixBase::sqrt() + */ +template ::Scalar>::IsComplex> +struct matrix_sqrt_compute +{ + /** \brief Compute the matrix square root + * + * \param[in] arg matrix whose square root is to be computed. + * \param[out] result square root of \p arg. + * + * See MatrixBase::sqrt() for details on how this computation is implemented. + */ + template static void run(const MatrixType &arg, ResultType &result); +}; + + +// ********** Partial specialization for real matrices ********** + +template +struct matrix_sqrt_compute +{ + typedef typename MatrixType::PlainObject PlainType; + template + static void run(const MatrixType &arg, ResultType &result) + { + eigen_assert(arg.rows() == arg.cols()); + + // Compute Schur decomposition of arg + const RealSchur schurOfA(arg); + const PlainType& T = schurOfA.matrixT(); + const PlainType& U = schurOfA.matrixU(); + + // Compute square root of T + PlainType sqrtT = PlainType::Zero(arg.rows(), arg.cols()); + matrix_sqrt_quasi_triangular(T, sqrtT); + + // Compute square root of arg + result = U * sqrtT * U.adjoint(); + } +}; + + +// ********** Partial specialization for complex matrices ********** + +template +struct matrix_sqrt_compute +{ + typedef typename MatrixType::PlainObject PlainType; + template + static void run(const MatrixType &arg, ResultType &result) + { + eigen_assert(arg.rows() == arg.cols()); + + // Compute Schur decomposition of arg + const ComplexSchur schurOfA(arg); + const PlainType& T = schurOfA.matrixT(); + const PlainType& U = schurOfA.matrixU(); + + // Compute square root of T + PlainType sqrtT; + matrix_sqrt_triangular(T, sqrtT); + + // Compute square root of arg + result = U * (sqrtT.template triangularView() * U.adjoint()); + } +}; + +} // end namespace internal + +/** \ingroup MatrixFunctions_Module + * + * \brief Proxy for the matrix square root of some matrix (expression). + * + * \tparam Derived Type of the argument to the matrix square root. + * + * This class holds the argument to the matrix square root until it + * is assigned or evaluated for some other reason (so the argument + * should not be changed in the meantime). It is the return type of + * MatrixBase::sqrt() and most of the time this is the only way it is + * used. + */ +template class MatrixSquareRootReturnValue +: public ReturnByValue > +{ + protected: + typedef typename internal::ref_selector::type DerivedNested; + + public: + /** \brief Constructor. + * + * \param[in] src %Matrix (expression) forming the argument of the + * matrix square root. + */ + explicit MatrixSquareRootReturnValue(const Derived& src) : m_src(src) { } + + /** \brief Compute the matrix square root. + * + * \param[out] result the matrix square root of \p src in the + * constructor. + */ + template + inline void evalTo(ResultType& result) const + { + typedef typename internal::nested_eval::type DerivedEvalType; + typedef internal::remove_all_t DerivedEvalTypeClean; + DerivedEvalType tmp(m_src); + internal::matrix_sqrt_compute::run(tmp, result); + } + + Index rows() const { return m_src.rows(); } + Index cols() const { return m_src.cols(); } + + protected: + const DerivedNested m_src; +}; + +namespace internal { +template +struct traits > +{ + typedef typename Derived::PlainObject ReturnType; +}; +} + +template +const MatrixSquareRootReturnValue MatrixBase::sqrt() const +{ + eigen_assert(rows() == cols()); + return MatrixSquareRootReturnValue(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_FUNCTION diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/StemFunction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/StemFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..25a3ef25b23ffa0aeee021c306eeeb3336809f20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MatrixFunctions/StemFunction.h @@ -0,0 +1,119 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010, 2013 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STEM_FUNCTION +#define EIGEN_STEM_FUNCTION + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \brief The exponential function (and its derivatives). */ +template +Scalar stem_function_exp(Scalar x, int) +{ + using std::exp; + return exp(x); +} + +/** \brief Cosine (and its derivatives). */ +template +Scalar stem_function_cos(Scalar x, int n) +{ + using std::cos; + using std::sin; + Scalar res; + + switch (n % 4) { + case 0: + res = std::cos(x); + break; + case 1: + res = -std::sin(x); + break; + case 2: + res = -std::cos(x); + break; + case 3: + res = std::sin(x); + break; + } + return res; +} + +/** \brief Sine (and its derivatives). */ +template +Scalar stem_function_sin(Scalar x, int n) +{ + using std::cos; + using std::sin; + Scalar res; + + switch (n % 4) { + case 0: + res = std::sin(x); + break; + case 1: + res = std::cos(x); + break; + case 2: + res = -std::sin(x); + break; + case 3: + res = -std::cos(x); + break; + } + return res; +} + +/** \brief Hyperbolic cosine (and its derivatives). */ +template +Scalar stem_function_cosh(Scalar x, int n) +{ + using std::cosh; + using std::sinh; + Scalar res; + + switch (n % 2) { + case 0: + res = std::cosh(x); + break; + case 1: + res = std::sinh(x); + break; + } + return res; +} + +/** \brief Hyperbolic sine (and its derivatives). */ +template +Scalar stem_function_sinh(Scalar x, int n) +{ + using std::cosh; + using std::sinh; + Scalar res; + + switch (n % 2) { + case 0: + res = std::sinh(x); + break; + case 1: + res = std::cosh(x); + break; + } + return res; +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_STEM_FUNCTION diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..3c294b3fdbe9e2a1af836066756d02413d84bd10 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_MOREVECTORIZATION_MODULE_H +#error "Please include unsupported/Eigen/MoreVectorization instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/MathFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/MathFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..9084298e029a9f8f27e895b8ded33a5ca6d4a156 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/MoreVectorization/MathFunctions.h @@ -0,0 +1,97 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Rohit Garg +// Copyright (C) 2009 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MOREVECTORIZATION_MATHFUNCTIONS_H +#define EIGEN_MOREVECTORIZATION_MATHFUNCTIONS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \internal \returns the arcsin of \a a (coeff-wise) */ +template inline static Packet pasin(Packet a) { return std::asin(a); } + +#ifdef EIGEN_VECTORIZE_SSE + +template<> EIGEN_DONT_INLINE Packet4f pasin(Packet4f x) +{ + EIGEN_DECLARE_CONST_Packet4f(half, 0.5); + EIGEN_DECLARE_CONST_Packet4f(minus_half, -0.5); + EIGEN_DECLARE_CONST_Packet4f(3half, 1.5); + + EIGEN_DECLARE_CONST_Packet4f_FROM_INT(sign_mask, 0x80000000); + + EIGEN_DECLARE_CONST_Packet4f(pi, 3.141592654); + EIGEN_DECLARE_CONST_Packet4f(pi_over_2, 3.141592654*0.5); + + EIGEN_DECLARE_CONST_Packet4f(asin1, 4.2163199048E-2); + EIGEN_DECLARE_CONST_Packet4f(asin2, 2.4181311049E-2); + EIGEN_DECLARE_CONST_Packet4f(asin3, 4.5470025998E-2); + EIGEN_DECLARE_CONST_Packet4f(asin4, 7.4953002686E-2); + EIGEN_DECLARE_CONST_Packet4f(asin5, 1.6666752422E-1); + + Packet4f a = pabs(x);//got the absolute value + + Packet4f sign_bit= _mm_and_ps(x, p4f_sign_mask);//extracted the sign bit + + Packet4f z1,z2;//will need them during computation + + +//will compute the two branches for asin +//so first compare with half + + Packet4f branch_mask= _mm_cmpgt_ps(a, p4f_half);//this is to select which branch to take +//both will be taken, and finally results will be merged +//the branch for values >0.5 + + { +//the core series expansion + z1=pmadd(p4f_minus_half,a,p4f_half); + Packet4f x1=psqrt(z1); + Packet4f s1=pmadd(p4f_asin1, z1, p4f_asin2); + Packet4f s2=pmadd(s1, z1, p4f_asin3); + Packet4f s3=pmadd(s2,z1, p4f_asin4); + Packet4f s4=pmadd(s3,z1, p4f_asin5); + Packet4f temp=pmul(s4,z1);//not really a madd but a mul by z so that the next term can be a madd + z1=pmadd(temp,x1,x1); + z1=padd(z1,z1); + z1=psub(p4f_pi_over_2,z1); + } + + { +//the core series expansion + Packet4f x2=a; + z2=pmul(x2,x2); + Packet4f s1=pmadd(p4f_asin1, z2, p4f_asin2); + Packet4f s2=pmadd(s1, z2, p4f_asin3); + Packet4f s3=pmadd(s2,z2, p4f_asin4); + Packet4f s4=pmadd(s3,z2, p4f_asin5); + Packet4f temp=pmul(s4,z2);//not really a madd but a mul by z so that the next term can be a madd + z2=pmadd(temp,x2,x2); + } + +/* select the correct result from the two branch evaluations */ + z1 = _mm_and_ps(branch_mask, z1); + z2 = _mm_andnot_ps(branch_mask, z2); + Packet4f z = _mm_or_ps(z1,z2); + +/* update the sign */ + return _mm_xor_ps(z, sign_bit); +} + +#endif // EIGEN_VECTORIZE_SSE + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_MOREVECTORIZATION_MATHFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/HybridNonLinearSolver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/HybridNonLinearSolver.h new file mode 100644 index 0000000000000000000000000000000000000000..4c38426883461fdb0648932c3573bdb5216d2738 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/HybridNonLinearSolver.h @@ -0,0 +1,603 @@ +// -*- coding: utf-8 +// vim: set fileencoding=utf-8 + +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_HYBRIDNONLINEARSOLVER_H +#define EIGEN_HYBRIDNONLINEARSOLVER_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace HybridNonLinearSolverSpace { + enum Status { + Running = -1, + ImproperInputParameters = 0, + RelativeErrorTooSmall = 1, + TooManyFunctionEvaluation = 2, + TolTooSmall = 3, + NotMakingProgressJacobian = 4, + NotMakingProgressIterations = 5, + UserAsked = 6 + }; +} + +/** + * \ingroup NonLinearOptimization_Module + * \brief Finds a zero of a system of n + * nonlinear functions in n variables by a modification of the Powell + * hybrid method ("dogleg"). + * + * The user must provide a subroutine which calculates the + * functions. The Jacobian is either provided by the user, or approximated + * using a forward-difference method. + * + */ +template +class HybridNonLinearSolver +{ +public: + typedef DenseIndex Index; + + HybridNonLinearSolver(FunctorType &_functor) + : functor(_functor) { nfev=njev=iter = 0; fnorm= 0.; useExternalScaling=false;} + + struct Parameters { + Parameters() + : factor(Scalar(100.)) + , maxfev(1000) + , xtol(numext::sqrt(NumTraits::epsilon())) + , nb_of_subdiagonals(-1) + , nb_of_superdiagonals(-1) + , epsfcn(Scalar(0.)) {} + Scalar factor; + Index maxfev; // maximum number of function evaluation + Scalar xtol; + Index nb_of_subdiagonals; + Index nb_of_superdiagonals; + Scalar epsfcn; + }; + typedef Matrix< Scalar, Dynamic, 1 > FVectorType; + typedef Matrix< Scalar, Dynamic, Dynamic > JacobianType; + /* TODO: if eigen provides a triangular storage, use it here */ + typedef Matrix< Scalar, Dynamic, Dynamic > UpperTriangularType; + + HybridNonLinearSolverSpace::Status hybrj1( + FVectorType &x, + const Scalar tol = numext::sqrt(NumTraits::epsilon()) + ); + + HybridNonLinearSolverSpace::Status solveInit(FVectorType &x); + HybridNonLinearSolverSpace::Status solveOneStep(FVectorType &x); + HybridNonLinearSolverSpace::Status solve(FVectorType &x); + + HybridNonLinearSolverSpace::Status hybrd1( + FVectorType &x, + const Scalar tol = numext::sqrt(NumTraits::epsilon()) + ); + + HybridNonLinearSolverSpace::Status solveNumericalDiffInit(FVectorType &x); + HybridNonLinearSolverSpace::Status solveNumericalDiffOneStep(FVectorType &x); + HybridNonLinearSolverSpace::Status solveNumericalDiff(FVectorType &x); + + void resetParameters(void) { parameters = Parameters(); } + Parameters parameters; + FVectorType fvec, qtf, diag; + JacobianType fjac; + UpperTriangularType R; + Index nfev; + Index njev; + Index iter; + Scalar fnorm; + bool useExternalScaling; +private: + FunctorType &functor; + Index n; + Scalar sum; + bool sing; + Scalar temp; + Scalar delta; + bool jeval; + Index ncsuc; + Scalar ratio; + Scalar pnorm, xnorm, fnorm1; + Index nslow1, nslow2; + Index ncfail; + Scalar actred, prered; + FVectorType wa1, wa2, wa3, wa4; + + HybridNonLinearSolver& operator=(const HybridNonLinearSolver&); +}; + + + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::hybrj1( + FVectorType &x, + const Scalar tol + ) +{ + n = x.size(); + + /* check the input parameters for errors. */ + if (n <= 0 || tol < 0.) + return HybridNonLinearSolverSpace::ImproperInputParameters; + + resetParameters(); + parameters.maxfev = 100*(n+1); + parameters.xtol = tol; + diag.setConstant(n, 1.); + useExternalScaling = true; + return solve(x); +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solveInit(FVectorType &x) +{ + n = x.size(); + + wa1.resize(n); wa2.resize(n); wa3.resize(n); wa4.resize(n); + fvec.resize(n); + qtf.resize(n); + fjac.resize(n, n); + if (!useExternalScaling) + diag.resize(n); + eigen_assert( (!useExternalScaling || diag.size()==n) && "When useExternalScaling is set, the caller must provide a valid 'diag'"); + + /* Function Body */ + nfev = 0; + njev = 0; + + /* check the input parameters for errors. */ + if (n <= 0 || parameters.xtol < 0. || parameters.maxfev <= 0 || parameters.factor <= 0. ) + return HybridNonLinearSolverSpace::ImproperInputParameters; + if (useExternalScaling) + for (Index j = 0; j < n; ++j) + if (diag[j] <= 0.) + return HybridNonLinearSolverSpace::ImproperInputParameters; + + /* evaluate the function at the starting point */ + /* and calculate its norm. */ + nfev = 1; + if ( functor(x, fvec) < 0) + return HybridNonLinearSolverSpace::UserAsked; + fnorm = fvec.stableNorm(); + + /* initialize iteration counter and monitors. */ + iter = 1; + ncsuc = 0; + ncfail = 0; + nslow1 = 0; + nslow2 = 0; + + return HybridNonLinearSolverSpace::Running; +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solveOneStep(FVectorType &x) +{ + using std::abs; + + eigen_assert(x.size()==n); // check the caller is not cheating us + + Index j; + std::vector > v_givens(n), w_givens(n); + + jeval = true; + + /* calculate the jacobian matrix. */ + if ( functor.df(x, fjac) < 0) + return HybridNonLinearSolverSpace::UserAsked; + ++njev; + + wa2 = fjac.colwise().blueNorm(); + + /* on the first iteration and if external scaling is not used, scale according */ + /* to the norms of the columns of the initial jacobian. */ + if (iter == 1) { + if (!useExternalScaling) + for (j = 0; j < n; ++j) + diag[j] = (wa2[j]==0.) ? 1. : wa2[j]; + + /* on the first iteration, calculate the norm of the scaled x */ + /* and initialize the step bound delta. */ + xnorm = diag.cwiseProduct(x).stableNorm(); + delta = parameters.factor * xnorm; + if (delta == 0.) + delta = parameters.factor; + } + + /* compute the qr factorization of the jacobian. */ + HouseholderQR qrfac(fjac); // no pivoting: + + /* copy the triangular factor of the qr factorization into r. */ + R = qrfac.matrixQR(); + + /* accumulate the orthogonal factor in fjac. */ + fjac = qrfac.householderQ(); + + /* form (q transpose)*fvec and store in qtf. */ + qtf = fjac.transpose() * fvec; + + /* rescale if necessary. */ + if (!useExternalScaling) + diag = diag.cwiseMax(wa2); + + while (true) { + /* determine the direction p. */ + internal::dogleg(R, diag, qtf, delta, wa1); + + /* store the direction p and x + p. calculate the norm of p. */ + wa1 = -wa1; + wa2 = x + wa1; + pnorm = diag.cwiseProduct(wa1).stableNorm(); + + /* on the first iteration, adjust the initial step bound. */ + if (iter == 1) + delta = (std::min)(delta,pnorm); + + /* evaluate the function at x + p and calculate its norm. */ + if ( functor(wa2, wa4) < 0) + return HybridNonLinearSolverSpace::UserAsked; + ++nfev; + fnorm1 = wa4.stableNorm(); + + /* compute the scaled actual reduction. */ + actred = -1.; + if (fnorm1 < fnorm) /* Computing 2nd power */ + actred = 1. - numext::abs2(fnorm1 / fnorm); + + /* compute the scaled predicted reduction. */ + wa3 = R.template triangularView()*wa1 + qtf; + temp = wa3.stableNorm(); + prered = 0.; + if (temp < fnorm) /* Computing 2nd power */ + prered = 1. - numext::abs2(temp / fnorm); + + /* compute the ratio of the actual to the predicted reduction. */ + ratio = 0.; + if (prered > 0.) + ratio = actred / prered; + + /* update the step bound. */ + if (ratio < Scalar(.1)) { + ncsuc = 0; + ++ncfail; + delta = Scalar(.5) * delta; + } else { + ncfail = 0; + ++ncsuc; + if (ratio >= Scalar(.5) || ncsuc > 1) + delta = (std::max)(delta, pnorm / Scalar(.5)); + if (abs(ratio - 1.) <= Scalar(.1)) { + delta = pnorm / Scalar(.5); + } + } + + /* test for successful iteration. */ + if (ratio >= Scalar(1e-4)) { + /* successful iteration. update x, fvec, and their norms. */ + x = wa2; + wa2 = diag.cwiseProduct(x); + fvec = wa4; + xnorm = wa2.stableNorm(); + fnorm = fnorm1; + ++iter; + } + + /* determine the progress of the iteration. */ + ++nslow1; + if (actred >= Scalar(.001)) + nslow1 = 0; + if (jeval) + ++nslow2; + if (actred >= Scalar(.1)) + nslow2 = 0; + + /* test for convergence. */ + if (delta <= parameters.xtol * xnorm || fnorm == 0.) + return HybridNonLinearSolverSpace::RelativeErrorTooSmall; + + /* tests for termination and stringent tolerances. */ + if (nfev >= parameters.maxfev) + return HybridNonLinearSolverSpace::TooManyFunctionEvaluation; + if (Scalar(.1) * (std::max)(Scalar(.1) * delta, pnorm) <= NumTraits::epsilon() * xnorm) + return HybridNonLinearSolverSpace::TolTooSmall; + if (nslow2 == 5) + return HybridNonLinearSolverSpace::NotMakingProgressJacobian; + if (nslow1 == 10) + return HybridNonLinearSolverSpace::NotMakingProgressIterations; + + /* criterion for recalculating jacobian. */ + if (ncfail == 2) + break; // leave inner loop and go for the next outer loop iteration + + /* calculate the rank one modification to the jacobian */ + /* and update qtf if necessary. */ + wa1 = diag.cwiseProduct( diag.cwiseProduct(wa1)/pnorm ); + wa2 = fjac.transpose() * wa4; + if (ratio >= Scalar(1e-4)) + qtf = wa2; + wa2 = (wa2-wa3)/pnorm; + + /* compute the qr factorization of the updated jacobian. */ + internal::r1updt(R, wa1, v_givens, w_givens, wa2, wa3, &sing); + internal::r1mpyq(n, n, fjac.data(), v_givens, w_givens); + internal::r1mpyq(1, n, qtf.data(), v_givens, w_givens); + + jeval = false; + } + return HybridNonLinearSolverSpace::Running; +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solve(FVectorType &x) +{ + HybridNonLinearSolverSpace::Status status = solveInit(x); + if (status==HybridNonLinearSolverSpace::ImproperInputParameters) + return status; + while (status==HybridNonLinearSolverSpace::Running) + status = solveOneStep(x); + return status; +} + + + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::hybrd1( + FVectorType &x, + const Scalar tol + ) +{ + n = x.size(); + + /* check the input parameters for errors. */ + if (n <= 0 || tol < 0.) + return HybridNonLinearSolverSpace::ImproperInputParameters; + + resetParameters(); + parameters.maxfev = 200*(n+1); + parameters.xtol = tol; + + diag.setConstant(n, 1.); + useExternalScaling = true; + return solveNumericalDiff(x); +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solveNumericalDiffInit(FVectorType &x) +{ + n = x.size(); + + if (parameters.nb_of_subdiagonals<0) parameters.nb_of_subdiagonals= n-1; + if (parameters.nb_of_superdiagonals<0) parameters.nb_of_superdiagonals= n-1; + + wa1.resize(n); wa2.resize(n); wa3.resize(n); wa4.resize(n); + qtf.resize(n); + fjac.resize(n, n); + fvec.resize(n); + if (!useExternalScaling) + diag.resize(n); + eigen_assert( (!useExternalScaling || diag.size()==n) && "When useExternalScaling is set, the caller must provide a valid 'diag'"); + + /* Function Body */ + nfev = 0; + njev = 0; + + /* check the input parameters for errors. */ + if (n <= 0 || parameters.xtol < 0. || parameters.maxfev <= 0 || parameters.nb_of_subdiagonals< 0 || parameters.nb_of_superdiagonals< 0 || parameters.factor <= 0. ) + return HybridNonLinearSolverSpace::ImproperInputParameters; + if (useExternalScaling) + for (Index j = 0; j < n; ++j) + if (diag[j] <= 0.) + return HybridNonLinearSolverSpace::ImproperInputParameters; + + /* evaluate the function at the starting point */ + /* and calculate its norm. */ + nfev = 1; + if ( functor(x, fvec) < 0) + return HybridNonLinearSolverSpace::UserAsked; + fnorm = fvec.stableNorm(); + + /* initialize iteration counter and monitors. */ + iter = 1; + ncsuc = 0; + ncfail = 0; + nslow1 = 0; + nslow2 = 0; + + return HybridNonLinearSolverSpace::Running; +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solveNumericalDiffOneStep(FVectorType &x) +{ + using std::sqrt; + using std::abs; + + eigen_assert(x.size()==n); // check the caller is not cheating us + + Index j; + std::vector > v_givens(n), w_givens(n); + + jeval = true; + if (parameters.nb_of_subdiagonals<0) parameters.nb_of_subdiagonals= n-1; + if (parameters.nb_of_superdiagonals<0) parameters.nb_of_superdiagonals= n-1; + + /* calculate the jacobian matrix. */ + if (internal::fdjac1(functor, x, fvec, fjac, parameters.nb_of_subdiagonals, parameters.nb_of_superdiagonals, parameters.epsfcn) <0) + return HybridNonLinearSolverSpace::UserAsked; + nfev += (std::min)(parameters.nb_of_subdiagonals+parameters.nb_of_superdiagonals+ 1, n); + + wa2 = fjac.colwise().blueNorm(); + + /* on the first iteration and if external scaling is not used, scale according */ + /* to the norms of the columns of the initial jacobian. */ + if (iter == 1) { + if (!useExternalScaling) + for (j = 0; j < n; ++j) + diag[j] = (wa2[j]==0.) ? 1. : wa2[j]; + + /* on the first iteration, calculate the norm of the scaled x */ + /* and initialize the step bound delta. */ + xnorm = diag.cwiseProduct(x).stableNorm(); + delta = parameters.factor * xnorm; + if (delta == 0.) + delta = parameters.factor; + } + + /* compute the qr factorization of the jacobian. */ + HouseholderQR qrfac(fjac); // no pivoting: + + /* copy the triangular factor of the qr factorization into r. */ + R = qrfac.matrixQR(); + + /* accumulate the orthogonal factor in fjac. */ + fjac = qrfac.householderQ(); + + /* form (q transpose)*fvec and store in qtf. */ + qtf = fjac.transpose() * fvec; + + /* rescale if necessary. */ + if (!useExternalScaling) + diag = diag.cwiseMax(wa2); + + while (true) { + /* determine the direction p. */ + internal::dogleg(R, diag, qtf, delta, wa1); + + /* store the direction p and x + p. calculate the norm of p. */ + wa1 = -wa1; + wa2 = x + wa1; + pnorm = diag.cwiseProduct(wa1).stableNorm(); + + /* on the first iteration, adjust the initial step bound. */ + if (iter == 1) + delta = (std::min)(delta,pnorm); + + /* evaluate the function at x + p and calculate its norm. */ + if ( functor(wa2, wa4) < 0) + return HybridNonLinearSolverSpace::UserAsked; + ++nfev; + fnorm1 = wa4.stableNorm(); + + /* compute the scaled actual reduction. */ + actred = -1.; + if (fnorm1 < fnorm) /* Computing 2nd power */ + actred = 1. - numext::abs2(fnorm1 / fnorm); + + /* compute the scaled predicted reduction. */ + wa3 = R.template triangularView()*wa1 + qtf; + temp = wa3.stableNorm(); + prered = 0.; + if (temp < fnorm) /* Computing 2nd power */ + prered = 1. - numext::abs2(temp / fnorm); + + /* compute the ratio of the actual to the predicted reduction. */ + ratio = 0.; + if (prered > 0.) + ratio = actred / prered; + + /* update the step bound. */ + if (ratio < Scalar(.1)) { + ncsuc = 0; + ++ncfail; + delta = Scalar(.5) * delta; + } else { + ncfail = 0; + ++ncsuc; + if (ratio >= Scalar(.5) || ncsuc > 1) + delta = (std::max)(delta, pnorm / Scalar(.5)); + if (abs(ratio - 1.) <= Scalar(.1)) { + delta = pnorm / Scalar(.5); + } + } + + /* test for successful iteration. */ + if (ratio >= Scalar(1e-4)) { + /* successful iteration. update x, fvec, and their norms. */ + x = wa2; + wa2 = diag.cwiseProduct(x); + fvec = wa4; + xnorm = wa2.stableNorm(); + fnorm = fnorm1; + ++iter; + } + + /* determine the progress of the iteration. */ + ++nslow1; + if (actred >= Scalar(.001)) + nslow1 = 0; + if (jeval) + ++nslow2; + if (actred >= Scalar(.1)) + nslow2 = 0; + + /* test for convergence. */ + if (delta <= parameters.xtol * xnorm || fnorm == 0.) + return HybridNonLinearSolverSpace::RelativeErrorTooSmall; + + /* tests for termination and stringent tolerances. */ + if (nfev >= parameters.maxfev) + return HybridNonLinearSolverSpace::TooManyFunctionEvaluation; + if (Scalar(.1) * (std::max)(Scalar(.1) * delta, pnorm) <= NumTraits::epsilon() * xnorm) + return HybridNonLinearSolverSpace::TolTooSmall; + if (nslow2 == 5) + return HybridNonLinearSolverSpace::NotMakingProgressJacobian; + if (nslow1 == 10) + return HybridNonLinearSolverSpace::NotMakingProgressIterations; + + /* criterion for recalculating jacobian. */ + if (ncfail == 2) + break; // leave inner loop and go for the next outer loop iteration + + /* calculate the rank one modification to the jacobian */ + /* and update qtf if necessary. */ + wa1 = diag.cwiseProduct( diag.cwiseProduct(wa1)/pnorm ); + wa2 = fjac.transpose() * wa4; + if (ratio >= Scalar(1e-4)) + qtf = wa2; + wa2 = (wa2-wa3)/pnorm; + + /* compute the qr factorization of the updated jacobian. */ + internal::r1updt(R, wa1, v_givens, w_givens, wa2, wa3, &sing); + internal::r1mpyq(n, n, fjac.data(), v_givens, w_givens); + internal::r1mpyq(1, n, qtf.data(), v_givens, w_givens); + + jeval = false; + } + return HybridNonLinearSolverSpace::Running; +} + +template +HybridNonLinearSolverSpace::Status +HybridNonLinearSolver::solveNumericalDiff(FVectorType &x) +{ + HybridNonLinearSolverSpace::Status status = solveNumericalDiffInit(x); + if (status==HybridNonLinearSolverSpace::ImproperInputParameters) + return status; + while (status==HybridNonLinearSolverSpace::Running) + status = solveNumericalDiffOneStep(x); + return status; +} + +} // end namespace Eigen + +#endif // EIGEN_HYBRIDNONLINEARSOLVER_H + +//vim: ai ts=4 sts=4 et sw=4 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..5b2276c20a8221bb75a869e26c5f6eba3cc53e7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_NONLINEAROPTIMIZATION_MODULE_H +#error "Please include unsupported/Eigen/NonLinearOptimization instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h new file mode 100644 index 0000000000000000000000000000000000000000..a176c25aa6331a228e84e2a6d9378af92486bffe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h @@ -0,0 +1,659 @@ +// -*- coding: utf-8 +// vim: set fileencoding=utf-8 + +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LEVENBERGMARQUARDT__H +#define EIGEN_LEVENBERGMARQUARDT__H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace LevenbergMarquardtSpace { + enum Status { + NotStarted = -2, + Running = -1, + ImproperInputParameters = 0, + RelativeReductionTooSmall = 1, + RelativeErrorTooSmall = 2, + RelativeErrorAndReductionTooSmall = 3, + CosinusTooSmall = 4, + TooManyFunctionEvaluation = 5, + FtolTooSmall = 6, + XtolTooSmall = 7, + GtolTooSmall = 8, + UserAsked = 9 + }; +} + + + +/** + * \ingroup NonLinearOptimization_Module + * \brief Performs non linear optimization over a non-linear function, + * using a variant of the Levenberg Marquardt algorithm. + * + * Check wikipedia for more information. + * http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm + */ +template +class LevenbergMarquardt +{ + static Scalar sqrt_epsilon() + { + using std::sqrt; + return sqrt(NumTraits::epsilon()); + } + +public: + LevenbergMarquardt(FunctorType &_functor) + : functor(_functor) { nfev = njev = iter = 0; fnorm = gnorm = 0.; useExternalScaling=false; } + + typedef DenseIndex Index; + + struct Parameters { + Parameters() + : factor(Scalar(100.)) + , maxfev(400) + , ftol(sqrt_epsilon()) + , xtol(sqrt_epsilon()) + , gtol(Scalar(0.)) + , epsfcn(Scalar(0.)) {} + Scalar factor; + Index maxfev; // maximum number of function evaluation + Scalar ftol; + Scalar xtol; + Scalar gtol; + Scalar epsfcn; + }; + + typedef Matrix< Scalar, Dynamic, 1 > FVectorType; + typedef Matrix< Scalar, Dynamic, Dynamic > JacobianType; + + LevenbergMarquardtSpace::Status lmder1( + FVectorType &x, + const Scalar tol = sqrt_epsilon() + ); + + LevenbergMarquardtSpace::Status minimize(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeInit(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeOneStep(FVectorType &x); + + static LevenbergMarquardtSpace::Status lmdif1( + FunctorType &functor, + FVectorType &x, + Index *nfev, + const Scalar tol = sqrt_epsilon() + ); + + LevenbergMarquardtSpace::Status lmstr1( + FVectorType &x, + const Scalar tol = sqrt_epsilon() + ); + + LevenbergMarquardtSpace::Status minimizeOptimumStorage(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeOptimumStorageInit(FVectorType &x); + LevenbergMarquardtSpace::Status minimizeOptimumStorageOneStep(FVectorType &x); + + void resetParameters(void) { parameters = Parameters(); } + + Parameters parameters; + FVectorType fvec, qtf, diag; + JacobianType fjac; + PermutationMatrix permutation; + Index nfev; + Index njev; + Index iter; + Scalar fnorm, gnorm; + bool useExternalScaling; + + Scalar lm_param(void) { return par; } +private: + + FunctorType &functor; + Index n; + Index m; + FVectorType wa1, wa2, wa3, wa4; + + Scalar par, sum; + Scalar temp, temp1, temp2; + Scalar delta; + Scalar ratio; + Scalar pnorm, xnorm, fnorm1, actred, dirder, prered; + + LevenbergMarquardt& operator=(const LevenbergMarquardt&); +}; + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::lmder1( + FVectorType &x, + const Scalar tol + ) +{ + n = x.size(); + m = functor.values(); + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || tol < 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + resetParameters(); + parameters.ftol = tol; + parameters.xtol = tol; + parameters.maxfev = 100*(n+1); + + return minimize(x); +} + + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimize(FVectorType &x) +{ + LevenbergMarquardtSpace::Status status = minimizeInit(x); + if (status==LevenbergMarquardtSpace::ImproperInputParameters) + return status; + do { + status = minimizeOneStep(x); + } while (status==LevenbergMarquardtSpace::Running); + return status; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeInit(FVectorType &x) +{ + n = x.size(); + m = functor.values(); + + wa1.resize(n); wa2.resize(n); wa3.resize(n); + wa4.resize(m); + fvec.resize(m); + fjac.resize(m, n); + if (!useExternalScaling) + diag.resize(n); + eigen_assert( (!useExternalScaling || diag.size()==n) && "When useExternalScaling is set, the caller must provide a valid 'diag'"); + qtf.resize(n); + + /* Function Body */ + nfev = 0; + njev = 0; + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || parameters.ftol < 0. || parameters.xtol < 0. || parameters.gtol < 0. || parameters.maxfev <= 0 || parameters.factor <= 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + if (useExternalScaling) + for (Index j = 0; j < n; ++j) + if (diag[j] <= 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + /* evaluate the function at the starting point */ + /* and calculate its norm. */ + nfev = 1; + if ( functor(x, fvec) < 0) + return LevenbergMarquardtSpace::UserAsked; + fnorm = fvec.stableNorm(); + + /* initialize levenberg-marquardt parameter and iteration counter. */ + par = 0.; + iter = 1; + + return LevenbergMarquardtSpace::NotStarted; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeOneStep(FVectorType &x) +{ + using std::abs; + using std::sqrt; + + eigen_assert(x.size()==n); // check the caller is not cheating us + + /* calculate the jacobian matrix. */ + Index df_ret = functor.df(x, fjac); + if (df_ret<0) + return LevenbergMarquardtSpace::UserAsked; + if (df_ret>0) + // numerical diff, we evaluated the function df_ret times + nfev += df_ret; + else njev++; + + /* compute the qr factorization of the jacobian. */ + wa2 = fjac.colwise().blueNorm(); + ColPivHouseholderQR qrfac(fjac); + fjac = qrfac.matrixQR(); + permutation = qrfac.colsPermutation(); + + /* on the first iteration and if external scaling is not used, scale according */ + /* to the norms of the columns of the initial jacobian. */ + if (iter == 1) { + if (!useExternalScaling) + for (Index j = 0; j < n; ++j) + diag[j] = (wa2[j]==0.)? 1. : wa2[j]; + + /* on the first iteration, calculate the norm of the scaled x */ + /* and initialize the step bound delta. */ + xnorm = diag.cwiseProduct(x).stableNorm(); + delta = parameters.factor * xnorm; + if (delta == 0.) + delta = parameters.factor; + } + + /* form (q transpose)*fvec and store the first n components in */ + /* qtf. */ + wa4 = fvec; + wa4.applyOnTheLeft(qrfac.householderQ().adjoint()); + qtf = wa4.head(n); + + /* compute the norm of the scaled gradient. */ + gnorm = 0.; + if (fnorm != 0.) + for (Index j = 0; j < n; ++j) + if (wa2[permutation.indices()[j]] != 0.) + gnorm = (std::max)(gnorm, abs( fjac.col(j).head(j+1).dot(qtf.head(j+1)/fnorm) / wa2[permutation.indices()[j]])); + + /* test for convergence of the gradient norm. */ + if (gnorm <= parameters.gtol) + return LevenbergMarquardtSpace::CosinusTooSmall; + + /* rescale if necessary. */ + if (!useExternalScaling) + diag = diag.cwiseMax(wa2); + + do { + + /* determine the levenberg-marquardt parameter. */ + internal::lmpar2(qrfac, diag, qtf, delta, par, wa1); + + /* store the direction p and x + p. calculate the norm of p. */ + wa1 = -wa1; + wa2 = x + wa1; + pnorm = diag.cwiseProduct(wa1).stableNorm(); + + /* on the first iteration, adjust the initial step bound. */ + if (iter == 1) + delta = (std::min)(delta,pnorm); + + /* evaluate the function at x + p and calculate its norm. */ + if ( functor(wa2, wa4) < 0) + return LevenbergMarquardtSpace::UserAsked; + ++nfev; + fnorm1 = wa4.stableNorm(); + + /* compute the scaled actual reduction. */ + actred = -1.; + if (Scalar(.1) * fnorm1 < fnorm) + actred = 1. - numext::abs2(fnorm1 / fnorm); + + /* compute the scaled predicted reduction and */ + /* the scaled directional derivative. */ + wa3 = fjac.template triangularView() * (qrfac.colsPermutation().inverse() *wa1); + temp1 = numext::abs2(wa3.stableNorm() / fnorm); + temp2 = numext::abs2(sqrt(par) * pnorm / fnorm); + prered = temp1 + temp2 / Scalar(.5); + dirder = -(temp1 + temp2); + + /* compute the ratio of the actual to the predicted */ + /* reduction. */ + ratio = 0.; + if (prered != 0.) + ratio = actred / prered; + + /* update the step bound. */ + if (ratio <= Scalar(.25)) { + if (actred >= 0.) + temp = Scalar(.5); + if (actred < 0.) + temp = Scalar(.5) * dirder / (dirder + Scalar(.5) * actred); + if (Scalar(.1) * fnorm1 >= fnorm || temp < Scalar(.1)) + temp = Scalar(.1); + /* Computing MIN */ + delta = temp * (std::min)(delta, pnorm / Scalar(.1)); + par /= temp; + } else if (!(par != 0. && ratio < Scalar(.75))) { + delta = pnorm / Scalar(.5); + par = Scalar(.5) * par; + } + + /* test for successful iteration. */ + if (ratio >= Scalar(1e-4)) { + /* successful iteration. update x, fvec, and their norms. */ + x = wa2; + wa2 = diag.cwiseProduct(x); + fvec = wa4; + xnorm = wa2.stableNorm(); + fnorm = fnorm1; + ++iter; + } + + /* tests for convergence. */ + if (abs(actred) <= parameters.ftol && prered <= parameters.ftol && Scalar(.5) * ratio <= 1. && delta <= parameters.xtol * xnorm) + return LevenbergMarquardtSpace::RelativeErrorAndReductionTooSmall; + if (abs(actred) <= parameters.ftol && prered <= parameters.ftol && Scalar(.5) * ratio <= 1.) + return LevenbergMarquardtSpace::RelativeReductionTooSmall; + if (delta <= parameters.xtol * xnorm) + return LevenbergMarquardtSpace::RelativeErrorTooSmall; + + /* tests for termination and stringent tolerances. */ + if (nfev >= parameters.maxfev) + return LevenbergMarquardtSpace::TooManyFunctionEvaluation; + if (abs(actred) <= NumTraits::epsilon() && prered <= NumTraits::epsilon() && Scalar(.5) * ratio <= 1.) + return LevenbergMarquardtSpace::FtolTooSmall; + if (delta <= NumTraits::epsilon() * xnorm) + return LevenbergMarquardtSpace::XtolTooSmall; + if (gnorm <= NumTraits::epsilon()) + return LevenbergMarquardtSpace::GtolTooSmall; + + } while (ratio < Scalar(1e-4)); + + return LevenbergMarquardtSpace::Running; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::lmstr1( + FVectorType &x, + const Scalar tol + ) +{ + n = x.size(); + m = functor.values(); + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || tol < 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + resetParameters(); + parameters.ftol = tol; + parameters.xtol = tol; + parameters.maxfev = 100*(n+1); + + return minimizeOptimumStorage(x); +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeOptimumStorageInit(FVectorType &x) +{ + n = x.size(); + m = functor.values(); + + wa1.resize(n); wa2.resize(n); wa3.resize(n); + wa4.resize(m); + fvec.resize(m); + // Only R is stored in fjac. Q is only used to compute 'qtf', which is + // Q.transpose()*rhs. qtf will be updated using givens rotation, + // instead of storing them in Q. + // The purpose it to only use a nxn matrix, instead of mxn here, so + // that we can handle cases where m>>n : + fjac.resize(n, n); + if (!useExternalScaling) + diag.resize(n); + eigen_assert( (!useExternalScaling || diag.size()==n) && "When useExternalScaling is set, the caller must provide a valid 'diag'"); + qtf.resize(n); + + /* Function Body */ + nfev = 0; + njev = 0; + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || parameters.ftol < 0. || parameters.xtol < 0. || parameters.gtol < 0. || parameters.maxfev <= 0 || parameters.factor <= 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + if (useExternalScaling) + for (Index j = 0; j < n; ++j) + if (diag[j] <= 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + /* evaluate the function at the starting point */ + /* and calculate its norm. */ + nfev = 1; + if ( functor(x, fvec) < 0) + return LevenbergMarquardtSpace::UserAsked; + fnorm = fvec.stableNorm(); + + /* initialize levenberg-marquardt parameter and iteration counter. */ + par = 0.; + iter = 1; + + return LevenbergMarquardtSpace::NotStarted; +} + + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeOptimumStorageOneStep(FVectorType &x) +{ + using std::abs; + using std::sqrt; + + eigen_assert(x.size()==n); // check the caller is not cheating us + + Index i, j; + bool sing; + + /* compute the qr factorization of the jacobian matrix */ + /* calculated one row at a time, while simultaneously */ + /* forming (q transpose)*fvec and storing the first */ + /* n components in qtf. */ + qtf.fill(0.); + fjac.fill(0.); + Index rownb = 2; + for (i = 0; i < m; ++i) { + if (functor.df(x, wa3, rownb) < 0) return LevenbergMarquardtSpace::UserAsked; + internal::rwupdt(fjac, wa3, qtf, fvec[i]); + ++rownb; + } + ++njev; + + /* if the jacobian is rank deficient, call qrfac to */ + /* reorder its columns and update the components of qtf. */ + sing = false; + for (j = 0; j < n; ++j) { + if (fjac(j,j) == 0.) + sing = true; + wa2[j] = fjac.col(j).head(j).stableNorm(); + } + permutation.setIdentity(n); + if (sing) { + wa2 = fjac.colwise().blueNorm(); + // TODO We have no unit test covering this code path, do not modify + // until it is carefully tested + ColPivHouseholderQR qrfac(fjac); + fjac = qrfac.matrixQR(); + wa1 = fjac.diagonal(); + fjac.diagonal() = qrfac.hCoeffs(); + permutation = qrfac.colsPermutation(); + // TODO : avoid this: + for(Index ii=0; ii< fjac.cols(); ii++) fjac.col(ii).segment(ii+1, fjac.rows()-ii-1) *= fjac(ii,ii); // rescale vectors + + for (j = 0; j < n; ++j) { + if (fjac(j,j) != 0.) { + sum = 0.; + for (i = j; i < n; ++i) + sum += fjac(i,j) * qtf[i]; + temp = -sum / fjac(j,j); + for (i = j; i < n; ++i) + qtf[i] += fjac(i,j) * temp; + } + fjac(j,j) = wa1[j]; + } + } + + /* on the first iteration and if external scaling is not used, scale according */ + /* to the norms of the columns of the initial jacobian. */ + if (iter == 1) { + if (!useExternalScaling) + for (j = 0; j < n; ++j) + diag[j] = (wa2[j]==0.)? 1. : wa2[j]; + + /* on the first iteration, calculate the norm of the scaled x */ + /* and initialize the step bound delta. */ + xnorm = diag.cwiseProduct(x).stableNorm(); + delta = parameters.factor * xnorm; + if (delta == 0.) + delta = parameters.factor; + } + + /* compute the norm of the scaled gradient. */ + gnorm = 0.; + if (fnorm != 0.) + for (j = 0; j < n; ++j) + if (wa2[permutation.indices()[j]] != 0.) + gnorm = (std::max)(gnorm, abs( fjac.col(j).head(j+1).dot(qtf.head(j+1)/fnorm) / wa2[permutation.indices()[j]])); + + /* test for convergence of the gradient norm. */ + if (gnorm <= parameters.gtol) + return LevenbergMarquardtSpace::CosinusTooSmall; + + /* rescale if necessary. */ + if (!useExternalScaling) + diag = diag.cwiseMax(wa2); + + do { + + /* determine the levenberg-marquardt parameter. */ + internal::lmpar(fjac, permutation.indices(), diag, qtf, delta, par, wa1); + + /* store the direction p and x + p. calculate the norm of p. */ + wa1 = -wa1; + wa2 = x + wa1; + pnorm = diag.cwiseProduct(wa1).stableNorm(); + + /* on the first iteration, adjust the initial step bound. */ + if (iter == 1) + delta = (std::min)(delta,pnorm); + + /* evaluate the function at x + p and calculate its norm. */ + if ( functor(wa2, wa4) < 0) + return LevenbergMarquardtSpace::UserAsked; + ++nfev; + fnorm1 = wa4.stableNorm(); + + /* compute the scaled actual reduction. */ + actred = -1.; + if (Scalar(.1) * fnorm1 < fnorm) + actred = 1. - numext::abs2(fnorm1 / fnorm); + + /* compute the scaled predicted reduction and */ + /* the scaled directional derivative. */ + wa3 = fjac.topLeftCorner(n,n).template triangularView() * (permutation.inverse() * wa1); + temp1 = numext::abs2(wa3.stableNorm() / fnorm); + temp2 = numext::abs2(sqrt(par) * pnorm / fnorm); + prered = temp1 + temp2 / Scalar(.5); + dirder = -(temp1 + temp2); + + /* compute the ratio of the actual to the predicted */ + /* reduction. */ + ratio = 0.; + if (prered != 0.) + ratio = actred / prered; + + /* update the step bound. */ + if (ratio <= Scalar(.25)) { + if (actred >= 0.) + temp = Scalar(.5); + if (actred < 0.) + temp = Scalar(.5) * dirder / (dirder + Scalar(.5) * actred); + if (Scalar(.1) * fnorm1 >= fnorm || temp < Scalar(.1)) + temp = Scalar(.1); + /* Computing MIN */ + delta = temp * (std::min)(delta, pnorm / Scalar(.1)); + par /= temp; + } else if (!(par != 0. && ratio < Scalar(.75))) { + delta = pnorm / Scalar(.5); + par = Scalar(.5) * par; + } + + /* test for successful iteration. */ + if (ratio >= Scalar(1e-4)) { + /* successful iteration. update x, fvec, and their norms. */ + x = wa2; + wa2 = diag.cwiseProduct(x); + fvec = wa4; + xnorm = wa2.stableNorm(); + fnorm = fnorm1; + ++iter; + } + + /* tests for convergence. */ + if (abs(actred) <= parameters.ftol && prered <= parameters.ftol && Scalar(.5) * ratio <= 1. && delta <= parameters.xtol * xnorm) + return LevenbergMarquardtSpace::RelativeErrorAndReductionTooSmall; + if (abs(actred) <= parameters.ftol && prered <= parameters.ftol && Scalar(.5) * ratio <= 1.) + return LevenbergMarquardtSpace::RelativeReductionTooSmall; + if (delta <= parameters.xtol * xnorm) + return LevenbergMarquardtSpace::RelativeErrorTooSmall; + + /* tests for termination and stringent tolerances. */ + if (nfev >= parameters.maxfev) + return LevenbergMarquardtSpace::TooManyFunctionEvaluation; + if (abs(actred) <= NumTraits::epsilon() && prered <= NumTraits::epsilon() && Scalar(.5) * ratio <= 1.) + return LevenbergMarquardtSpace::FtolTooSmall; + if (delta <= NumTraits::epsilon() * xnorm) + return LevenbergMarquardtSpace::XtolTooSmall; + if (gnorm <= NumTraits::epsilon()) + return LevenbergMarquardtSpace::GtolTooSmall; + + } while (ratio < Scalar(1e-4)); + + return LevenbergMarquardtSpace::Running; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::minimizeOptimumStorage(FVectorType &x) +{ + LevenbergMarquardtSpace::Status status = minimizeOptimumStorageInit(x); + if (status==LevenbergMarquardtSpace::ImproperInputParameters) + return status; + do { + status = minimizeOptimumStorageOneStep(x); + } while (status==LevenbergMarquardtSpace::Running); + return status; +} + +template +LevenbergMarquardtSpace::Status +LevenbergMarquardt::lmdif1( + FunctorType &functor, + FVectorType &x, + Index *nfev, + const Scalar tol + ) +{ + Index n = x.size(); + Index m = functor.values(); + + /* check the input parameters for errors. */ + if (n <= 0 || m < n || tol < 0.) + return LevenbergMarquardtSpace::ImproperInputParameters; + + NumericalDiff numDiff(functor); + // embedded LevenbergMarquardt + LevenbergMarquardt, Scalar > lm(numDiff); + lm.parameters.ftol = tol; + lm.parameters.xtol = tol; + lm.parameters.maxfev = 200*(n+1); + + LevenbergMarquardtSpace::Status info = LevenbergMarquardtSpace::Status(lm.minimize(x)); + if (nfev) + * nfev = lm.nfev; + return info; +} + +} // end namespace Eigen + +#endif // EIGEN_LEVENBERGMARQUARDT__H + +//vim: ai ts=4 sts=4 et sw=4 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/chkder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/chkder.h new file mode 100644 index 0000000000000000000000000000000000000000..d0974a0afaa4f26b68c80e7cfbc4d7fc1578b879 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/chkder.h @@ -0,0 +1,68 @@ +#define chkder_log10e 0.43429448190325182765 +#define chkder_factor 100. + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void chkder( + const Matrix< Scalar, Dynamic, 1 > &x, + const Matrix< Scalar, Dynamic, 1 > &fvec, + const Matrix< Scalar, Dynamic, Dynamic > &fjac, + Matrix< Scalar, Dynamic, 1 > &xp, + const Matrix< Scalar, Dynamic, 1 > &fvecp, + int mode, + Matrix< Scalar, Dynamic, 1 > &err + ) +{ + using std::sqrt; + using std::abs; + using std::log; + + typedef DenseIndex Index; + + const Scalar eps = sqrt(NumTraits::epsilon()); + const Scalar epsf = chkder_factor * NumTraits::epsilon(); + const Scalar epslog = chkder_log10e * log(eps); + Scalar temp; + + const Index m = fvec.size(), n = x.size(); + + if (mode != 2) { + /* mode = 1. */ + xp.resize(n); + for (Index j = 0; j < n; ++j) { + temp = eps * abs(x[j]); + if (temp == 0.) + temp = eps; + xp[j] = x[j] + temp; + } + } + else { + /* mode = 2. */ + err.setZero(m); + for (Index j = 0; j < n; ++j) { + temp = abs(x[j]); + if (temp == 0.) + temp = 1.; + err += temp * fjac.col(j); + } + for (Index i = 0; i < m; ++i) { + temp = 1.; + if (fvec[i] != 0. && fvecp[i] != 0. && abs(fvecp[i] - fvec[i]) >= epsf * abs(fvec[i])) + temp = eps * abs((fvecp[i] - fvec[i]) / eps - err[i]) / (abs(fvec[i]) + abs(fvecp[i])); + err[i] = 1.; + if (temp > NumTraits::epsilon() && temp < eps) + err[i] = (chkder_log10e * log(temp) - epslog) / epslog; + if (temp >= eps) + err[i] = 0.; + } + } +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/covar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/covar.h new file mode 100644 index 0000000000000000000000000000000000000000..181c4f32c73e52ff699587b10c82b781a4c22775 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/covar.h @@ -0,0 +1,72 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void covar( + Matrix< Scalar, Dynamic, Dynamic > &r, + const VectorXi &ipvt, + Scalar tol = std::sqrt(NumTraits::epsilon()) ) +{ + using std::abs; + typedef DenseIndex Index; + + /* Local variables */ + Index i, j, k, l, ii, jj; + bool sing; + Scalar temp; + + /* Function Body */ + const Index n = r.cols(); + const Scalar tolr = tol * abs(r(0,0)); + Matrix< Scalar, Dynamic, 1 > wa(n); + eigen_assert(ipvt.size()==n); + + /* form the inverse of r in the full upper triangle of r. */ + l = -1; + for (k = 0; k < n; ++k) + if (abs(r(k,k)) > tolr) { + r(k,k) = 1. / r(k,k); + for (j = 0; j <= k-1; ++j) { + temp = r(k,k) * r(j,k); + r(j,k) = 0.; + r.col(k).head(j+1) -= r.col(j).head(j+1) * temp; + } + l = k; + } + + /* form the full upper triangle of the inverse of (r transpose)*r */ + /* in the full upper triangle of r. */ + for (k = 0; k <= l; ++k) { + for (j = 0; j <= k-1; ++j) + r.col(j).head(j+1) += r.col(k).head(j+1) * r(j,k); + r.col(k).head(k+1) *= r(k,k); + } + + /* form the full lower triangle of the covariance matrix */ + /* in the strict lower triangle of r and in wa. */ + for (j = 0; j < n; ++j) { + jj = ipvt[j]; + sing = j > l; + for (i = 0; i <= j; ++i) { + if (sing) + r(i,j) = 0.; + ii = ipvt[i]; + if (ii > jj) + r(ii,jj) = r(i,j); + if (ii < jj) + r(jj,ii) = r(i,j); + } + wa[jj] = r(j,j); + } + + /* symmetrize the covariance matrix in r. */ + r.topLeftCorner(n,n).template triangularView() = r.topLeftCorner(n,n).transpose(); + r.diagonal() = wa; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/dogleg.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/dogleg.h new file mode 100644 index 0000000000000000000000000000000000000000..7c170a2ab7e09279d2de1e27740b8ab0c7662374 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/dogleg.h @@ -0,0 +1,109 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void dogleg( + const Matrix< Scalar, Dynamic, Dynamic > &qrfac, + const Matrix< Scalar, Dynamic, 1 > &diag, + const Matrix< Scalar, Dynamic, 1 > &qtb, + Scalar delta, + Matrix< Scalar, Dynamic, 1 > &x) +{ + using std::abs; + using std::sqrt; + + typedef DenseIndex Index; + + /* Local variables */ + Index i, j; + Scalar sum, temp, alpha, bnorm; + Scalar gnorm, qnorm; + Scalar sgnorm; + + /* Function Body */ + const Scalar epsmch = NumTraits::epsilon(); + const Index n = qrfac.cols(); + eigen_assert(n==qtb.size()); + eigen_assert(n==x.size()); + eigen_assert(n==diag.size()); + Matrix< Scalar, Dynamic, 1 > wa1(n), wa2(n); + + /* first, calculate the gauss-newton direction. */ + for (j = n-1; j >=0; --j) { + temp = qrfac(j,j); + if (temp == 0.) { + temp = epsmch * qrfac.col(j).head(j+1).maxCoeff(); + if (temp == 0.) + temp = epsmch; + } + if (j==n-1) + x[j] = qtb[j] / temp; + else + x[j] = (qtb[j] - qrfac.row(j).tail(n-j-1).dot(x.tail(n-j-1))) / temp; + } + + /* test whether the gauss-newton direction is acceptable. */ + qnorm = diag.cwiseProduct(x).stableNorm(); + if (qnorm <= delta) + return; + + // TODO : this path is not tested by Eigen unit tests + + /* the gauss-newton direction is not acceptable. */ + /* next, calculate the scaled gradient direction. */ + + wa1.fill(0.); + for (j = 0; j < n; ++j) { + wa1.tail(n-j) += qrfac.row(j).tail(n-j) * qtb[j]; + wa1[j] /= diag[j]; + } + + /* calculate the norm of the scaled gradient and test for */ + /* the special case in which the scaled gradient is zero. */ + gnorm = wa1.stableNorm(); + sgnorm = 0.; + alpha = delta / qnorm; + if (gnorm == 0.) + goto algo_end; + + /* calculate the point along the scaled gradient */ + /* at which the quadratic is minimized. */ + wa1.array() /= (diag*gnorm).array(); + // TODO : once unit tests cover this part,: + // wa2 = qrfac.template triangularView() * wa1; + for (j = 0; j < n; ++j) { + sum = 0.; + for (i = j; i < n; ++i) { + sum += qrfac(j,i) * wa1[i]; + } + wa2[j] = sum; + } + temp = wa2.stableNorm(); + sgnorm = gnorm / temp / temp; + + /* test whether the scaled gradient direction is acceptable. */ + alpha = 0.; + if (sgnorm >= delta) + goto algo_end; + + /* the scaled gradient direction is not acceptable. */ + /* finally, calculate the point along the dogleg */ + /* at which the quadratic is minimized. */ + bnorm = qtb.stableNorm(); + temp = bnorm / gnorm * (bnorm / qnorm) * (sgnorm / delta); + temp = temp - delta / qnorm * numext::abs2(sgnorm / delta) + sqrt(numext::abs2(temp - delta / qnorm) + (1.-numext::abs2(delta / qnorm)) * (1.-numext::abs2(sgnorm / delta))); + alpha = delta / qnorm * (1. - numext::abs2(sgnorm / delta)) / temp; +algo_end: + + /* form appropriate convex combination of the gauss-newton */ + /* direction and the scaled gradient direction. */ + temp = (1.-alpha) * (std::min)(sgnorm,delta); + x = temp * wa1 + alpha * x; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/fdjac1.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/fdjac1.h new file mode 100644 index 0000000000000000000000000000000000000000..317b1578e586230561c4af97fb522ea0e4848062 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/fdjac1.h @@ -0,0 +1,81 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +DenseIndex fdjac1( + const FunctorType &Functor, + Matrix< Scalar, Dynamic, 1 > &x, + Matrix< Scalar, Dynamic, 1 > &fvec, + Matrix< Scalar, Dynamic, Dynamic > &fjac, + DenseIndex ml, DenseIndex mu, + Scalar epsfcn) +{ + using std::sqrt; + using std::abs; + + typedef DenseIndex Index; + + /* Local variables */ + Scalar h; + Index j, k; + Scalar eps, temp; + Index msum; + int iflag; + Index start, length; + + /* Function Body */ + const Scalar epsmch = NumTraits::epsilon(); + const Index n = x.size(); + eigen_assert(fvec.size()==n); + Matrix< Scalar, Dynamic, 1 > wa1(n); + Matrix< Scalar, Dynamic, 1 > wa2(n); + + eps = sqrt((std::max)(epsfcn,epsmch)); + msum = ml + mu + 1; + if (msum >= n) { + /* computation of dense approximate jacobian. */ + for (j = 0; j < n; ++j) { + temp = x[j]; + h = eps * abs(temp); + if (h == 0.) + h = eps; + x[j] = temp + h; + iflag = Functor(x, wa1); + if (iflag < 0) + return iflag; + x[j] = temp; + fjac.col(j) = (wa1-fvec)/h; + } + + }else { + /* computation of banded approximate jacobian. */ + for (k = 0; k < msum; ++k) { + for (j = k; (msum<0) ? (j>n): (jn): (j(0,j-mu); + length = (std::min)(n-1, j+ml) - start + 1; + fjac.col(j).segment(start, length) = ( wa1.segment(start, length)-fvec.segment(start, length))/h; + } + } + } + return 0; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/lmpar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/lmpar.h new file mode 100644 index 0000000000000000000000000000000000000000..64af0fdef86fb4fb0d2a085bb333d27f207ec952 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/lmpar.h @@ -0,0 +1,300 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void lmpar( + Matrix< Scalar, Dynamic, Dynamic > &r, + const VectorXi &ipvt, + const Matrix< Scalar, Dynamic, 1 > &diag, + const Matrix< Scalar, Dynamic, 1 > &qtb, + Scalar delta, + Scalar &par, + Matrix< Scalar, Dynamic, 1 > &x) +{ + using std::abs; + using std::sqrt; + typedef DenseIndex Index; + + /* Local variables */ + Index i, j, l; + Scalar fp; + Scalar parc, parl; + Index iter; + Scalar temp, paru; + Scalar gnorm; + Scalar dxnorm; + + + /* Function Body */ + const Scalar dwarf = (std::numeric_limits::min)(); + const Index n = r.cols(); + eigen_assert(n==diag.size()); + eigen_assert(n==qtb.size()); + eigen_assert(n==x.size()); + + Matrix< Scalar, Dynamic, 1 > wa1, wa2; + + /* compute and store in x the gauss-newton direction. if the */ + /* jacobian is rank-deficient, obtain a least squares solution. */ + Index nsing = n-1; + wa1 = qtb; + for (j = 0; j < n; ++j) { + if (r(j,j) == 0. && nsing == n-1) + nsing = j - 1; + if (nsing < n-1) + wa1[j] = 0.; + } + for (j = nsing; j>=0; --j) { + wa1[j] /= r(j,j); + temp = wa1[j]; + for (i = 0; i < j ; ++i) + wa1[i] -= r(i,j) * temp; + } + + for (j = 0; j < n; ++j) + x[ipvt[j]] = wa1[j]; + + /* initialize the iteration counter. */ + /* evaluate the function at the origin, and test */ + /* for acceptance of the gauss-newton direction. */ + iter = 0; + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + fp = dxnorm - delta; + if (fp <= Scalar(0.1) * delta) { + par = 0; + return; + } + + /* if the jacobian is not rank deficient, the newton */ + /* step provides a lower bound, parl, for the zero of */ + /* the function. otherwise set this bound to zero. */ + parl = 0.; + if (nsing >= n-1) { + for (j = 0; j < n; ++j) { + l = ipvt[j]; + wa1[j] = diag[l] * (wa2[l] / dxnorm); + } + // it's actually a triangularView.solveInplace(), though in a weird + // way: + for (j = 0; j < n; ++j) { + Scalar sum = 0.; + for (i = 0; i < j; ++i) + sum += r(i,j) * wa1[i]; + wa1[j] = (wa1[j] - sum) / r(j,j); + } + temp = wa1.blueNorm(); + parl = fp / delta / temp / temp; + } + + /* calculate an upper bound, paru, for the zero of the function. */ + for (j = 0; j < n; ++j) + wa1[j] = r.col(j).head(j+1).dot(qtb.head(j+1)) / diag[ipvt[j]]; + + gnorm = wa1.stableNorm(); + paru = gnorm / delta; + if (paru == 0.) + paru = dwarf / (std::min)(delta,Scalar(0.1)); + + /* if the input par lies outside of the interval (parl,paru), */ + /* set par to the closer endpoint. */ + par = (std::max)(par,parl); + par = (std::min)(par,paru); + if (par == 0.) + par = gnorm / dxnorm; + + /* beginning of an iteration. */ + while (true) { + ++iter; + + /* evaluate the function at the current value of par. */ + if (par == 0.) + par = (std::max)(dwarf,Scalar(.001) * paru); /* Computing MAX */ + wa1 = sqrt(par)* diag; + + Matrix< Scalar, Dynamic, 1 > sdiag(n); + qrsolv(r, ipvt, wa1, qtb, x, sdiag); + + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + temp = fp; + fp = dxnorm - delta; + + /* if the function is small enough, accept the current value */ + /* of par. also test for the exceptional cases where parl */ + /* is zero or the number of iterations has reached 10. */ + if (abs(fp) <= Scalar(0.1) * delta || (parl == 0. && fp <= temp && temp < 0.) || iter == 10) + break; + + /* compute the newton correction. */ + for (j = 0; j < n; ++j) { + l = ipvt[j]; + wa1[j] = diag[l] * (wa2[l] / dxnorm); + } + for (j = 0; j < n; ++j) { + wa1[j] /= sdiag[j]; + temp = wa1[j]; + for (i = j+1; i < n; ++i) + wa1[i] -= r(i,j) * temp; + } + temp = wa1.blueNorm(); + parc = fp / delta / temp / temp; + + /* depending on the sign of the function, update parl or paru. */ + if (fp > 0.) + parl = (std::max)(parl,par); + if (fp < 0.) + paru = (std::min)(paru,par); + + /* compute an improved estimate for par. */ + /* Computing MAX */ + par = (std::max)(parl,par+parc); + + /* end of an iteration. */ + } + + /* termination. */ + if (iter == 0) + par = 0.; + return; +} + +template +void lmpar2( + const ColPivHouseholderQR > &qr, + const Matrix< Scalar, Dynamic, 1 > &diag, + const Matrix< Scalar, Dynamic, 1 > &qtb, + Scalar delta, + Scalar &par, + Matrix< Scalar, Dynamic, 1 > &x) + +{ + using std::sqrt; + using std::abs; + typedef DenseIndex Index; + + /* Local variables */ + Index j; + Scalar fp; + Scalar parc, parl; + Index iter; + Scalar temp, paru; + Scalar gnorm; + Scalar dxnorm; + + + /* Function Body */ + const Scalar dwarf = (std::numeric_limits::min)(); + const Index n = qr.matrixQR().cols(); + eigen_assert(n==diag.size()); + eigen_assert(n==qtb.size()); + + Matrix< Scalar, Dynamic, 1 > wa1, wa2; + + /* compute and store in x the gauss-newton direction. if the */ + /* jacobian is rank-deficient, obtain a least squares solution. */ + +// const Index rank = qr.nonzeroPivots(); // exactly double(0.) + const Index rank = qr.rank(); // use a threshold + wa1 = qtb; + wa1.tail(n-rank).setZero(); + qr.matrixQR().topLeftCorner(rank, rank).template triangularView().solveInPlace(wa1.head(rank)); + + x = qr.colsPermutation()*wa1; + + /* initialize the iteration counter. */ + /* evaluate the function at the origin, and test */ + /* for acceptance of the gauss-newton direction. */ + iter = 0; + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + fp = dxnorm - delta; + if (fp <= Scalar(0.1) * delta) { + par = 0; + return; + } + + /* if the jacobian is not rank deficient, the newton */ + /* step provides a lower bound, parl, for the zero of */ + /* the function. otherwise set this bound to zero. */ + parl = 0.; + if (rank==n) { + wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2)/dxnorm; + qr.matrixQR().topLeftCorner(n, n).transpose().template triangularView().solveInPlace(wa1); + temp = wa1.blueNorm(); + parl = fp / delta / temp / temp; + } + + /* calculate an upper bound, paru, for the zero of the function. */ + for (j = 0; j < n; ++j) + wa1[j] = qr.matrixQR().col(j).head(j+1).dot(qtb.head(j+1)) / diag[qr.colsPermutation().indices()(j)]; + + gnorm = wa1.stableNorm(); + paru = gnorm / delta; + if (paru == 0.) + paru = dwarf / (std::min)(delta,Scalar(0.1)); + + /* if the input par lies outside of the interval (parl,paru), */ + /* set par to the closer endpoint. */ + par = (std::max)(par,parl); + par = (std::min)(par,paru); + if (par == 0.) + par = gnorm / dxnorm; + + /* beginning of an iteration. */ + Matrix< Scalar, Dynamic, Dynamic > s = qr.matrixQR(); + while (true) { + ++iter; + + /* evaluate the function at the current value of par. */ + if (par == 0.) + par = (std::max)(dwarf,Scalar(.001) * paru); /* Computing MAX */ + wa1 = sqrt(par)* diag; + + Matrix< Scalar, Dynamic, 1 > sdiag(n); + qrsolv(s, qr.colsPermutation().indices(), wa1, qtb, x, sdiag); + + wa2 = diag.cwiseProduct(x); + dxnorm = wa2.blueNorm(); + temp = fp; + fp = dxnorm - delta; + + /* if the function is small enough, accept the current value */ + /* of par. also test for the exceptional cases where parl */ + /* is zero or the number of iterations has reached 10. */ + if (abs(fp) <= Scalar(0.1) * delta || (parl == 0. && fp <= temp && temp < 0.) || iter == 10) + break; + + /* compute the newton correction. */ + wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2/dxnorm); + // we could almost use this here, but the diagonal is outside qr, in sdiag[] + // qr.matrixQR().topLeftCorner(n, n).transpose().template triangularView().solveInPlace(wa1); + for (j = 0; j < n; ++j) { + wa1[j] /= sdiag[j]; + temp = wa1[j]; + for (Index i = j+1; i < n; ++i) + wa1[i] -= s(i,j) * temp; + } + temp = wa1.blueNorm(); + parc = fp / delta / temp / temp; + + /* depending on the sign of the function, update parl or paru. */ + if (fp > 0.) + parl = (std::max)(parl,par); + if (fp < 0.) + paru = (std::min)(paru,par); + + /* compute an improved estimate for par. */ + par = (std::max)(parl,par+parc); + } + if (iter == 0) + par = 0.; + return; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/qrsolv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/qrsolv.h new file mode 100644 index 0000000000000000000000000000000000000000..1cdcd4e21c3aa1ca34e86e6eaa86a4e16d8005e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/qrsolv.h @@ -0,0 +1,93 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +// TODO : once qrsolv2 is removed, use ColPivHouseholderQR or PermutationMatrix instead of ipvt +template +void qrsolv( + Matrix< Scalar, Dynamic, Dynamic > &s, + // TODO : use a PermutationMatrix once lmpar is no more: + const VectorXi &ipvt, + const Matrix< Scalar, Dynamic, 1 > &diag, + const Matrix< Scalar, Dynamic, 1 > &qtb, + Matrix< Scalar, Dynamic, 1 > &x, + Matrix< Scalar, Dynamic, 1 > &sdiag) + +{ + typedef DenseIndex Index; + + /* Local variables */ + Index i, j, k, l; + Scalar temp; + Index n = s.cols(); + Matrix< Scalar, Dynamic, 1 > wa(n); + JacobiRotation givens; + + /* Function Body */ + // the following will only change the lower triangular part of s, including + // the diagonal, though the diagonal is restored afterward + + /* copy r and (q transpose)*b to preserve input and initialize s. */ + /* in particular, save the diagonal elements of r in x. */ + x = s.diagonal(); + wa = qtb; + + s.topLeftCorner(n,n).template triangularView() = s.topLeftCorner(n,n).transpose(); + + /* eliminate the diagonal matrix d using a givens rotation. */ + for (j = 0; j < n; ++j) { + + /* prepare the row of d to be eliminated, locating the */ + /* diagonal element using p from the qr factorization. */ + l = ipvt[j]; + if (diag[l] == 0.) + break; + sdiag.tail(n-j).setZero(); + sdiag[j] = diag[l]; + + /* the transformations to eliminate the row of d */ + /* modify only a single element of (q transpose)*b */ + /* beyond the first n, which is initially zero. */ + Scalar qtbpj = 0.; + for (k = j; k < n; ++k) { + /* determine a givens rotation which eliminates the */ + /* appropriate element in the current row of d. */ + givens.makeGivens(-s(k,k), sdiag[k]); + + /* compute the modified diagonal element of r and */ + /* the modified element of ((q transpose)*b,0). */ + s(k,k) = givens.c() * s(k,k) + givens.s() * sdiag[k]; + temp = givens.c() * wa[k] + givens.s() * qtbpj; + qtbpj = -givens.s() * wa[k] + givens.c() * qtbpj; + wa[k] = temp; + + /* accumulate the transformation in the row of s. */ + for (i = k+1; i().solveInPlace(wa.head(nsing)); + + // restore + sdiag = s.diagonal(); + s.diagonal() = x; + + /* permute the components of z back to components of x. */ + for (j = 0; j < n; ++j) x[ipvt[j]] = wa[j]; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/r1mpyq.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/r1mpyq.h new file mode 100644 index 0000000000000000000000000000000000000000..37ef2580bb41b6d8f1c8b89719ed49df6dd9c635 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/r1mpyq.h @@ -0,0 +1,32 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +// TODO : move this to GivensQR once there's such a thing in Eigen + +template +void r1mpyq(DenseIndex m, DenseIndex n, Scalar *a, const std::vector > &v_givens, const std::vector > &w_givens) +{ + typedef DenseIndex Index; + + /* apply the first set of givens rotations to a. */ + for (Index j = n-2; j>=0; --j) + for (Index i = 0; i +void r1updt( + Matrix< Scalar, Dynamic, Dynamic > &s, + const Matrix< Scalar, Dynamic, 1> &u, + std::vector > &v_givens, + std::vector > &w_givens, + Matrix< Scalar, Dynamic, 1> &v, + Matrix< Scalar, Dynamic, 1> &w, + bool *sing) +{ + typedef DenseIndex Index; + const JacobiRotation IdentityRotation = JacobiRotation(1,0); + + /* Local variables */ + const Index m = s.rows(); + const Index n = s.cols(); + Index i, j=1; + Scalar temp; + JacobiRotation givens; + + // r1updt had a broader usecase, but we don't use it here. And, more + // importantly, we can not test it. + eigen_assert(m==n); + eigen_assert(u.size()==m); + eigen_assert(v.size()==n); + eigen_assert(w.size()==n); + + /* move the nontrivial part of the last column of s into w. */ + w[n-1] = s(n-1,n-1); + + /* rotate the vector v into a multiple of the n-th unit vector */ + /* in such a way that a spike is introduced into w. */ + for (j=n-2; j>=0; --j) { + w[j] = 0.; + if (v[j] != 0.) { + /* determine a givens rotation which eliminates the */ + /* j-th element of v. */ + givens.makeGivens(-v[n-1], v[j]); + + /* apply the transformation to v and store the information */ + /* necessary to recover the givens rotation. */ + v[n-1] = givens.s() * v[j] + givens.c() * v[n-1]; + v_givens[j] = givens; + + /* apply the transformation to s and extend the spike in w. */ + for (i = j; i < m; ++i) { + temp = givens.c() * s(j,i) - givens.s() * w[i]; + w[i] = givens.s() * s(j,i) + givens.c() * w[i]; + s(j,i) = temp; + } + } else + v_givens[j] = IdentityRotation; + } + + /* add the spike from the rank 1 update to w. */ + w += v[n-1] * u; + + /* eliminate the spike. */ + *sing = false; + for (j = 0; j < n-1; ++j) { + if (w[j] != 0.) { + /* determine a givens rotation which eliminates the */ + /* j-th element of the spike. */ + givens.makeGivens(-s(j,j), w[j]); + + /* apply the transformation to s and reduce the spike in w. */ + for (i = j; i < m; ++i) { + temp = givens.c() * s(j,i) + givens.s() * w[i]; + w[i] = -givens.s() * s(j,i) + givens.c() * w[i]; + s(j,i) = temp; + } + + /* store the information necessary to recover the */ + /* givens rotation. */ + w_givens[j] = givens; + } else + v_givens[j] = IdentityRotation; + + /* test for zero diagonal elements in the output s. */ + if (s(j,j) == 0.) { + *sing = true; + } + } + /* move w back into the last column of the output s. */ + s(n-1,n-1) = w[n-1]; + + if (s(j,j) == 0.) { + *sing = true; + } + return; +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/rwupdt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/rwupdt.h new file mode 100644 index 0000000000000000000000000000000000000000..f9ca50465cf0e521ab3c3819a660a7ef46d0c30b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NonLinearOptimization/rwupdt.h @@ -0,0 +1,51 @@ +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +template +void rwupdt( + Matrix< Scalar, Dynamic, Dynamic > &r, + const Matrix< Scalar, Dynamic, 1> &w, + Matrix< Scalar, Dynamic, 1> &b, + Scalar alpha) +{ + typedef DenseIndex Index; + + const Index n = r.cols(); + eigen_assert(r.rows()>=n); + std::vector > givens(n); + + /* Local variables */ + Scalar temp, rowj; + + /* Function Body */ + for (Index j = 0; j < n; ++j) { + rowj = w[j]; + + /* apply the previous transformations to */ + /* r(i,j), i=0,1,...,j-1, and to w(j). */ + for (Index i = 0; i < j; ++i) { + temp = givens[i].c() * r(i,j) + givens[i].s() * rowj; + rowj = -givens[i].s() * r(i,j) + givens[i].c() * rowj; + r(i,j) = temp; + } + + /* determine a givens rotation which eliminates w(j). */ + givens[j].makeGivens(-r(j,j), rowj); + + if (rowj == 0.) + continue; // givens[j] is identity + + /* apply the current transformation to r(j,j), b(j), and alpha. */ + r(j,j) = givens[j].c() * r(j,j) + givens[j].s() * rowj; + temp = givens[j].c() * b[j] + givens[j].s() * alpha; + alpha = -givens[j].s() * b[j] + givens[j].c() * alpha; + b[j] = temp; + } +} + +} // end namespace internal + +} // end namespace Eigen diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..8c513d20348faef27adb5ae51ea322bb78857bcb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_NUMERICALDIFF_MODULE_H +#error "Please include unsupported/Eigen/NumericalDiff instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/NumericalDiff.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/NumericalDiff.h new file mode 100644 index 0000000000000000000000000000000000000000..daa42107a3ba96f5d9344d7a6d9c74766884a78d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/NumericalDiff/NumericalDiff.h @@ -0,0 +1,132 @@ +// -*- coding: utf-8 +// vim: set fileencoding=utf-8 + +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Thomas Capricelli +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NUMERICAL_DIFF_H +#define EIGEN_NUMERICAL_DIFF_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +enum NumericalDiffMode { + Forward, + Central +}; + + +/** + * This class allows you to add a method df() to your functor, which will + * use numerical differentiation to compute an approximate of the + * derivative for the functor. Of course, if you have an analytical form + * for the derivative, you should rather implement df() by yourself. + * + * More information on + * http://en.wikipedia.org/wiki/Numerical_differentiation + * + * Currently only "Forward" and "Central" scheme are implemented. + */ +template +class NumericalDiff : public Functor_ +{ +public: + typedef Functor_ Functor; + typedef typename Functor::Scalar Scalar; + typedef typename Functor::InputType InputType; + typedef typename Functor::ValueType ValueType; + typedef typename Functor::JacobianType JacobianType; + + NumericalDiff(Scalar _epsfcn=0.) : Functor(), epsfcn(_epsfcn) {} + NumericalDiff(const Functor& f, Scalar _epsfcn=0.) : Functor(f), epsfcn(_epsfcn) {} + + // forward constructors + template + NumericalDiff(const T0& a0) : Functor(a0), epsfcn(0) {} + template + NumericalDiff(const T0& a0, const T1& a1) : Functor(a0, a1), epsfcn(0) {} + template + NumericalDiff(const T0& a0, const T1& a1, const T2& a2) : Functor(a0, a1, a2), epsfcn(0) {} + + enum { + InputsAtCompileTime = Functor::InputsAtCompileTime, + ValuesAtCompileTime = Functor::ValuesAtCompileTime + }; + + /** + * return the number of evaluation of functor + */ + int df(const InputType& _x, JacobianType &jac) const + { + using std::sqrt; + using std::abs; + /* Local variables */ + Scalar h; + int nfev=0; + const typename InputType::Index n = _x.size(); + const Scalar eps = sqrt(((std::max)(epsfcn,NumTraits::epsilon() ))); + ValueType val1, val2; + InputType x = _x; + // TODO : we should do this only if the size is not already known + val1.resize(Functor::values()); + val2.resize(Functor::values()); + + // initialization + switch(mode) { + case Forward: + // compute f(x) + Functor::operator()(x, val1); nfev++; + break; + case Central: + // do nothing + break; + default: + eigen_assert(false); + }; + + // Function Body + for (int j = 0; j < n; ++j) { + h = eps * abs(x[j]); + if (h == 0.) { + h = eps; + } + switch(mode) { + case Forward: + x[j] += h; + Functor::operator()(x, val2); + nfev++; + x[j] = _x[j]; + jac.col(j) = (val2-val1)/h; + break; + case Central: + x[j] += h; + Functor::operator()(x, val2); nfev++; + x[j] -= 2*h; + Functor::operator()(x, val1); nfev++; + x[j] = _x[j]; + jac.col(j) = (val2-val1)/(2*h); + break; + default: + eigen_assert(false); + }; + } + return nfev; + } +private: + Scalar epsfcn; + + NumericalDiff& operator=(const NumericalDiff&); +}; + +} // end namespace Eigen + +//vim: ai ts=4 sts=4 et sw=4 +#endif // EIGEN_NUMERICAL_DIFF_H + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/Companion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/Companion.h new file mode 100644 index 0000000000000000000000000000000000000000..23c281aa48e53801eab825fd2c67b6bdee514ab2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/Companion.h @@ -0,0 +1,282 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Manuel Yguel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_COMPANION_H +#define EIGEN_COMPANION_H + +// This file requires the user to include +// * Eigen/Core +// * Eigen/src/PolynomialSolver.h + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +#ifndef EIGEN_PARSED_BY_DOXYGEN + +template +struct decrement_if_fixed_size +{ + enum { + ret = (Size == Dynamic) ? Dynamic : Size-1 }; +}; + +#endif + +template< typename Scalar_, int Deg_ > +class companion +{ + public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar_,Deg_==Dynamic ? Dynamic : Deg_) + + enum { + Deg = Deg_, + Deg_1=decrement_if_fixed_size::ret + }; + + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + typedef Matrix RightColumn; + //typedef DiagonalMatrix< Scalar, Deg_1, Deg_1 > BottomLeftDiagonal; + typedef Matrix BottomLeftDiagonal; + + typedef Matrix DenseCompanionMatrixType; + typedef Matrix< Scalar, Deg_, Deg_1 > LeftBlock; + typedef Matrix< Scalar, Deg_1, Deg_1 > BottomLeftBlock; + typedef Matrix< Scalar, 1, Deg_1 > LeftBlockFirstRow; + + typedef DenseIndex Index; + + public: + EIGEN_STRONG_INLINE const Scalar_ operator()(Index row, Index col ) const + { + if( m_bl_diag.rows() > col ) + { + if( 0 < row ){ return m_bl_diag[col]; } + else{ return 0; } + } + else{ return m_monic[row]; } + } + + public: + template + void setPolynomial( const VectorType& poly ) + { + const Index deg = poly.size()-1; + m_monic = -poly.head(deg)/poly[deg]; + m_bl_diag.setOnes(deg-1); + } + + template + companion( const VectorType& poly ){ + setPolynomial( poly ); } + + public: + DenseCompanionMatrixType denseMatrix() const + { + const Index deg = m_monic.size(); + const Index deg_1 = deg-1; + DenseCompanionMatrixType companMat(deg,deg); + companMat << + ( LeftBlock(deg,deg_1) + << LeftBlockFirstRow::Zero(1,deg_1), + BottomLeftBlock::Identity(deg-1,deg-1)*m_bl_diag.asDiagonal() ).finished() + , m_monic; + return companMat; + } + + + + protected: + /** Helper function for the balancing algorithm. + * \returns true if the row and the column, having colNorm and rowNorm + * as norms, are balanced, false otherwise. + * colB and rowB are respectively the multipliers for + * the column and the row in order to balance them. + * */ + bool balanced( RealScalar colNorm, RealScalar rowNorm, + bool& isBalanced, RealScalar& colB, RealScalar& rowB ); + + /** Helper function for the balancing algorithm. + * \returns true if the row and the column, having colNorm and rowNorm + * as norms, are balanced, false otherwise. + * colB and rowB are respectively the multipliers for + * the column and the row in order to balance them. + * */ + bool balancedR( RealScalar colNorm, RealScalar rowNorm, + bool& isBalanced, RealScalar& colB, RealScalar& rowB ); + + public: + /** + * Balancing algorithm from B. N. PARLETT and C. REINSCH (1969) + * "Balancing a matrix for calculation of eigenvalues and eigenvectors" + * adapted to the case of companion matrices. + * A matrix with non zero row and non zero column is balanced + * for a certain norm if the i-th row and the i-th column + * have same norm for all i. + */ + void balance(); + + protected: + RightColumn m_monic; + BottomLeftDiagonal m_bl_diag; +}; + + + +template< typename Scalar_, int Deg_ > +inline +bool companion::balanced( RealScalar colNorm, RealScalar rowNorm, + bool& isBalanced, RealScalar& colB, RealScalar& rowB ) +{ + if( RealScalar(0) == colNorm || RealScalar(0) == rowNorm + || !(numext::isfinite)(colNorm) || !(numext::isfinite)(rowNorm)){ + return true; + } + else + { + //To find the balancing coefficients, if the radix is 2, + //one finds \f$ \sigma \f$ such that + // \f$ 2^{2\sigma-1} < rowNorm / colNorm \le 2^{2\sigma+1} \f$ + // then the balancing coefficient for the row is \f$ 1/2^{\sigma} \f$ + // and the balancing coefficient for the column is \f$ 2^{\sigma} \f$ + const RealScalar radix = RealScalar(2); + const RealScalar radix2 = RealScalar(4); + + rowB = rowNorm / radix; + colB = RealScalar(1); + const RealScalar s = colNorm + rowNorm; + + // Find sigma s.t. rowNorm / 2 <= 2^(2*sigma) * colNorm + RealScalar scout = colNorm; + while (scout < rowB) + { + colB *= radix; + scout *= radix2; + } + + // We now have an upper-bound for sigma, try to lower it. + // Find sigma s.t. 2^(2*sigma) * colNorm / 2 < rowNorm + scout = colNorm * (colB / radix) * colB; // Avoid overflow. + while (scout >= rowNorm) + { + colB /= radix; + scout /= radix2; + } + + // This line is used to avoid insubstantial balancing. + if ((rowNorm + radix * scout) < RealScalar(0.95) * s * colB) + { + isBalanced = false; + rowB = RealScalar(1) / colB; + return false; + } + else + { + return true; + } + } +} + +template< typename Scalar_, int Deg_ > +inline +bool companion::balancedR( RealScalar colNorm, RealScalar rowNorm, + bool& isBalanced, RealScalar& colB, RealScalar& rowB ) +{ + if( RealScalar(0) == colNorm || RealScalar(0) == rowNorm ){ return true; } + else + { + /** + * Set the norm of the column and the row to the geometric mean + * of the row and column norm + */ + const RealScalar q = colNorm/rowNorm; + if( !isApprox( q, Scalar_(1) ) ) + { + rowB = sqrt( colNorm/rowNorm ); + colB = RealScalar(1)/rowB; + + isBalanced = false; + return false; + } + else{ + return true; } + } +} + + +template< typename Scalar_, int Deg_ > +void companion::balance() +{ + using std::abs; + EIGEN_STATIC_ASSERT( Deg == Dynamic || 1 < Deg, YOU_MADE_A_PROGRAMMING_MISTAKE ); + const Index deg = m_monic.size(); + const Index deg_1 = deg-1; + + bool hasConverged=false; + while( !hasConverged ) + { + hasConverged = true; + RealScalar colNorm,rowNorm; + RealScalar colB,rowB; + + //First row, first column excluding the diagonal + //============================================== + colNorm = abs(m_bl_diag[0]); + rowNorm = abs(m_monic[0]); + + //Compute balancing of the row and the column + if( !balanced( colNorm, rowNorm, hasConverged, colB, rowB ) ) + { + m_bl_diag[0] *= colB; + m_monic[0] *= rowB; + } + + //Middle rows and columns excluding the diagonal + //============================================== + for( Index i=1; i headMonic( m_monic, 0, deg_1 ); + colNorm = headMonic.array().abs().sum(); + rowNorm = abs( m_bl_diag[ebl] ); + + //Compute balancing of the row and the column + if( !balanced( colNorm, rowNorm, hasConverged, colB, rowB ) ) + { + headMonic *= colB; + m_bl_diag[ebl] *= rowB; + } + } +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_COMPANION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..b3aa50ca6357dccc0fc6acefaa1608e7e866ff95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_POLYNOMIALS_MODULE_H +#error "Please include unsupported/Eigen/Polynomials instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialSolver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialSolver.h new file mode 100644 index 0000000000000000000000000000000000000000..64cab12045cf9c06e8107af70b79658416ed54aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialSolver.h @@ -0,0 +1,430 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Manuel Yguel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_POLYNOMIAL_SOLVER_H +#define EIGEN_POLYNOMIAL_SOLVER_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \ingroup Polynomials_Module + * \class PolynomialSolverBase. + * + * \brief Defined to be inherited by polynomial solvers: it provides + * convenient methods such as + * - real roots, + * - greatest, smallest complex roots, + * - real roots with greatest, smallest absolute real value, + * - greatest, smallest real roots. + * + * It stores the set of roots as a vector of complexes. + * + */ +template< typename Scalar_, int Deg_ > +class PolynomialSolverBase +{ + public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar_,Deg_==Dynamic ? Dynamic : Deg_) + + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + typedef std::complex RootType; + typedef Matrix RootsType; + + typedef DenseIndex Index; + + protected: + template< typename OtherPolynomial > + inline void setPolynomial( const OtherPolynomial& poly ){ + m_roots.resize(poly.size()-1); } + + public: + template< typename OtherPolynomial > + inline PolynomialSolverBase( const OtherPolynomial& poly ){ + setPolynomial( poly() ); } + + inline PolynomialSolverBase(){} + + public: + /** \returns the complex roots of the polynomial */ + inline const RootsType& roots() const { return m_roots; } + + public: + /** Clear and fills the back insertion sequence with the real roots of the polynomial + * i.e. the real part of the complex roots that have an imaginary part which + * absolute value is smaller than absImaginaryThreshold. + * absImaginaryThreshold takes the dummy_precision associated + * with the Scalar_ template parameter of the PolynomialSolver class as the default value. + * + * \param[out] bi_seq : the back insertion sequence (stl concept) + * \param[in] absImaginaryThreshold : the maximum bound of the imaginary part of a complex + * number that is considered as real. + * */ + template + inline void realRoots( Stl_back_insertion_sequence& bi_seq, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + using std::abs; + bi_seq.clear(); + for(Index i=0; i + inline const RootType& selectComplexRoot_withRespectToNorm( squaredNormBinaryPredicate& pred ) const + { + Index res=0; + RealScalar norm2 = numext::abs2( m_roots[0] ); + for( Index i=1; i greater; + return selectComplexRoot_withRespectToNorm( greater ); + } + + /** + * \returns the complex root with smallest norm. + */ + inline const RootType& smallestRoot() const + { + std::less less; + return selectComplexRoot_withRespectToNorm( less ); + } + + protected: + template + inline const RealScalar& selectRealRoot_withRespectToAbsRealPart( + squaredRealPartBinaryPredicate& pred, + bool& hasArealRoot, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + using std::abs; + hasArealRoot = false; + Index res=0; + RealScalar abs2(0); + + for( Index i=0; i + inline const RealScalar& selectRealRoot_withRespectToRealPart( + RealPartBinaryPredicate& pred, + bool& hasArealRoot, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + using std::abs; + hasArealRoot = false; + Index res=0; + RealScalar val(0); + + for( Index i=0; i::dummy_precision() ) const + { + std::greater greater; + return selectRealRoot_withRespectToAbsRealPart( greater, hasArealRoot, absImaginaryThreshold ); + } + + + /** + * \returns a real root with smallest absolute magnitude. + * A real root is defined as the real part of a complex root with absolute imaginary + * part smallest than absImaginaryThreshold. + * absImaginaryThreshold takes the dummy_precision associated + * with the Scalar_ template parameter of the PolynomialSolver class as the default value. + * If no real root is found the boolean hasArealRoot is set to false and the real part of + * the root with smallest absolute imaginary part is returned instead. + * + * \param[out] hasArealRoot : boolean true if a real root is found according to the + * absImaginaryThreshold criterion, false otherwise. + * \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide + * whether or not a root is real. + */ + inline const RealScalar& absSmallestRealRoot( + bool& hasArealRoot, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + std::less less; + return selectRealRoot_withRespectToAbsRealPart( less, hasArealRoot, absImaginaryThreshold ); + } + + + /** + * \returns the real root with greatest value. + * A real root is defined as the real part of a complex root with absolute imaginary + * part smallest than absImaginaryThreshold. + * absImaginaryThreshold takes the dummy_precision associated + * with the Scalar_ template parameter of the PolynomialSolver class as the default value. + * If no real root is found the boolean hasArealRoot is set to false and the real part of + * the root with smallest absolute imaginary part is returned instead. + * + * \param[out] hasArealRoot : boolean true if a real root is found according to the + * absImaginaryThreshold criterion, false otherwise. + * \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide + * whether or not a root is real. + */ + inline const RealScalar& greatestRealRoot( + bool& hasArealRoot, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + std::greater greater; + return selectRealRoot_withRespectToRealPart( greater, hasArealRoot, absImaginaryThreshold ); + } + + + /** + * \returns the real root with smallest value. + * A real root is defined as the real part of a complex root with absolute imaginary + * part smallest than absImaginaryThreshold. + * absImaginaryThreshold takes the dummy_precision associated + * with the Scalar_ template parameter of the PolynomialSolver class as the default value. + * If no real root is found the boolean hasArealRoot is set to false and the real part of + * the root with smallest absolute imaginary part is returned instead. + * + * \param[out] hasArealRoot : boolean true if a real root is found according to the + * absImaginaryThreshold criterion, false otherwise. + * \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide + * whether or not a root is real. + */ + inline const RealScalar& smallestRealRoot( + bool& hasArealRoot, + const RealScalar& absImaginaryThreshold = NumTraits::dummy_precision() ) const + { + std::less less; + return selectRealRoot_withRespectToRealPart( less, hasArealRoot, absImaginaryThreshold ); + } + + protected: + RootsType m_roots; +}; + +#define EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( BASE ) \ + typedef typename BASE::Scalar Scalar; \ + typedef typename BASE::RealScalar RealScalar; \ + typedef typename BASE::RootType RootType; \ + typedef typename BASE::RootsType RootsType; + + + +/** \ingroup Polynomials_Module + * + * \class PolynomialSolver + * + * \brief A polynomial solver + * + * Computes the complex roots of a real polynomial. + * + * \param Scalar_ the scalar type, i.e., the type of the polynomial coefficients + * \param Deg_ the degree of the polynomial, can be a compile time value or Dynamic. + * Notice that the number of polynomial coefficients is Deg_+1. + * + * This class implements a polynomial solver and provides convenient methods such as + * - real roots, + * - greatest, smallest complex roots, + * - real roots with greatest, smallest absolute real value. + * - greatest, smallest real roots. + * + * WARNING: this polynomial solver is experimental, part of the unsupported Eigen modules. + * + * + * Currently a QR algorithm is used to compute the eigenvalues of the companion matrix of + * the polynomial to compute its roots. + * This supposes that the complex moduli of the roots are all distinct: e.g. there should + * be no multiple roots or conjugate roots for instance. + * With 32bit (float) floating types this problem shows up frequently. + * However, almost always, correct accuracy is reached even in these cases for 64bit + * (double) floating types and small polynomial degree (<20). + */ +template +class PolynomialSolver : public PolynomialSolverBase +{ + public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(Scalar_,Deg_==Dynamic ? Dynamic : Deg_) + + typedef PolynomialSolverBase PS_Base; + EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( PS_Base ) + + typedef Matrix CompanionMatrixType; + typedef std::conditional_t::IsComplex, + ComplexEigenSolver, + EigenSolver > EigenSolverType; + typedef std::conditional_t::IsComplex, Scalar, std::complex > ComplexScalar; + + public: + /** Computes the complex roots of a new polynomial. */ + template< typename OtherPolynomial > + void compute( const OtherPolynomial& poly ) + { + eigen_assert( Scalar(0) != poly[poly.size()-1] ); + eigen_assert( poly.size() > 1 ); + if(poly.size() > 2 ) + { + internal::companion companion( poly ); + companion.balance(); + m_eigenSolver.compute( companion.denseMatrix() ); + m_roots = m_eigenSolver.eigenvalues(); + // cleanup noise in imaginary part of real roots: + // if the imaginary part is rather small compared to the real part + // and that cancelling the imaginary part yield a smaller evaluation, + // then it's safe to keep the real part only. + RealScalar coarse_prec = RealScalar(std::pow(4,poly.size()+1))*NumTraits::epsilon(); + for(Index i = 0; i + inline PolynomialSolver( const OtherPolynomial& poly ){ + compute( poly ); } + + inline PolynomialSolver(){} + + protected: + using PS_Base::m_roots; + EigenSolverType m_eigenSolver; +}; + + +template< typename Scalar_ > +class PolynomialSolver : public PolynomialSolverBase +{ + public: + typedef PolynomialSolverBase PS_Base; + EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( PS_Base ) + + public: + /** Computes the complex roots of a new polynomial. */ + template< typename OtherPolynomial > + void compute( const OtherPolynomial& poly ) + { + eigen_assert( poly.size() == 2 ); + eigen_assert( Scalar(0) != poly[1] ); + m_roots[0] = -poly[0]/poly[1]; + } + + public: + template< typename OtherPolynomial > + inline PolynomialSolver( const OtherPolynomial& poly ){ + compute( poly ); } + + inline PolynomialSolver(){} + + protected: + using PS_Base::m_roots; +}; + +} // end namespace Eigen + +#endif // EIGEN_POLYNOMIAL_SOLVER_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialUtils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..6af8613b6c1ae5f6b8c38b74e5eb99e6388f0af5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Polynomials/PolynomialUtils.h @@ -0,0 +1,145 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Manuel Yguel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_POLYNOMIAL_UTILS_H +#define EIGEN_POLYNOMIAL_UTILS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \ingroup Polynomials_Module + * \returns the evaluation of the polynomial at x using Horner algorithm. + * + * \param[in] poly : the vector of coefficients of the polynomial ordered + * by degrees i.e. poly[i] is the coefficient of degree i of the polynomial + * e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$. + * \param[in] x : the value to evaluate the polynomial at. + * + * \note for stability: + * \f$ |x| \le 1 \f$ + */ +template +inline +T poly_eval_horner( const Polynomials& poly, const T& x ) +{ + T val=poly[poly.size()-1]; + for(DenseIndex i=poly.size()-2; i>=0; --i ){ + val = val*x + poly[i]; } + return val; +} + +/** \ingroup Polynomials_Module + * \returns the evaluation of the polynomial at x using stabilized Horner algorithm. + * + * \param[in] poly : the vector of coefficients of the polynomial ordered + * by degrees i.e. poly[i] is the coefficient of degree i of the polynomial + * e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$. + * \param[in] x : the value to evaluate the polynomial at. + */ +template +inline +T poly_eval( const Polynomials& poly, const T& x ) +{ + typedef typename NumTraits::Real Real; + + if( numext::abs2( x ) <= Real(1) ){ + return poly_eval_horner( poly, x ); } + else + { + T val=poly[0]; + T inv_x = T(1)/x; + for( DenseIndex i=1; i +inline +typename NumTraits::Real cauchy_max_bound( const Polynomial& poly ) +{ + using std::abs; + typedef typename Polynomial::Scalar Scalar; + typedef typename NumTraits::Real Real; + + eigen_assert( Scalar(0) != poly[poly.size()-1] ); + const Scalar inv_leading_coeff = Scalar(1)/poly[poly.size()-1]; + Real cb(0); + + for( DenseIndex i=0; i +inline +typename NumTraits::Real cauchy_min_bound( const Polynomial& poly ) +{ + using std::abs; + typedef typename Polynomial::Scalar Scalar; + typedef typename NumTraits::Real Real; + + DenseIndex i=0; + while( i +void roots_to_monicPolynomial( const RootVector& rv, Polynomial& poly ) +{ + + typedef typename Polynomial::Scalar Scalar; + + poly.setZero( rv.size()+1 ); + poly[0] = -rv[0]; poly[1] = Scalar(1); + for( DenseIndex i=1; i< rv.size(); ++i ) + { + for( DenseIndex j=i+1; j>0; --j ){ poly[j] = poly[j-1] - rv[i]*poly[j]; } + poly[0] = -rv[i]*poly[0]; + } +} + +} // end namespace Eigen + +#endif // EIGEN_POLYNOMIAL_UTILS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..bddf0b0ae22915e8d80a24d7e2d54bfe33ffd177 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_SKYLINE_MODULE_H +#error "Please include unsupported/Eigen/Skyline instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineInplaceLU.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineInplaceLU.h new file mode 100644 index 0000000000000000000000000000000000000000..ef90438305b78d06c2e9a1e01bbef608e2415be0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineInplaceLU.h @@ -0,0 +1,354 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINEINPLACELU_H +#define EIGEN_SKYLINEINPLACELU_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \ingroup Skyline_Module + * + * \class SkylineInplaceLU + * + * \brief Inplace LU decomposition of a skyline matrix and associated features + * + * \param MatrixType the type of the matrix of which we are computing the LU factorization + * + */ +template +class SkylineInplaceLU { +protected: + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::Index Index; + + typedef typename NumTraits::Real RealScalar; + +public: + + /** Creates a LU object and compute the respective factorization of \a matrix using + * flags \a flags. */ + SkylineInplaceLU(MatrixType& matrix, int flags = 0) + : /*m_matrix(matrix.rows(), matrix.cols()),*/ m_flags(flags), m_status(0), m_lu(matrix) { + m_precision = RealScalar(0.1) * Eigen::dummy_precision (); + m_lu.IsRowMajor ? computeRowMajor() : compute(); + } + + /** Sets the relative threshold value used to prune zero coefficients during the decomposition. + * + * Setting a value greater than zero speeds up computation, and yields to an incomplete + * factorization with fewer non zero coefficients. Such approximate factors are especially + * useful to initialize an iterative solver. + * + * Note that the exact meaning of this parameter might depends on the actual + * backend. Moreover, not all backends support this feature. + * + * \sa precision() */ + void setPrecision(RealScalar v) { + m_precision = v; + } + + /** \returns the current precision. + * + * \sa setPrecision() */ + RealScalar precision() const { + return m_precision; + } + + /** Sets the flags. Possible values are: + * - CompleteFactorization + * - IncompleteFactorization + * - MemoryEfficient + * - one of the ordering methods + * - etc... + * + * \sa flags() */ + void setFlags(int f) { + m_flags = f; + } + + /** \returns the current flags */ + int flags() const { + return m_flags; + } + + void setOrderingMethod(int m) { + m_flags = m; + } + + int orderingMethod() const { + return m_flags; + } + + /** Computes/re-computes the LU factorization */ + void compute(); + void computeRowMajor(); + + /** \returns the lower triangular matrix L */ + //inline const MatrixType& matrixL() const { return m_matrixL; } + + /** \returns the upper triangular matrix U */ + //inline const MatrixType& matrixU() const { return m_matrixU; } + + template + bool solve(const MatrixBase &b, MatrixBase* x, + const int transposed = 0) const; + + /** \returns true if the factorization succeeded */ + inline bool succeeded(void) const { + return m_succeeded; + } + +protected: + RealScalar m_precision; + int m_flags; + mutable int m_status; + bool m_succeeded; + MatrixType& m_lu; +}; + +/** Computes / recomputes the in place LU decomposition of the SkylineInplaceLU. + * using the default algorithm. + */ +template +//template +void SkylineInplaceLU::compute() { + const size_t rows = m_lu.rows(); + const size_t cols = m_lu.cols(); + + eigen_assert(rows == cols && "We do not (yet) support rectangular LU."); + eigen_assert(!m_lu.IsRowMajor && "LU decomposition does not work with rowMajor Storage"); + + for (Index row = 0; row < rows; row++) { + const double pivot = m_lu.coeffDiag(row); + + //Lower matrix Columns update + const Index& col = row; + for (typename MatrixType::InnerLowerIterator lIt(m_lu, col); lIt; ++lIt) { + lIt.valueRef() /= pivot; + } + + //Upper matrix update -> contiguous memory access + typename MatrixType::InnerLowerIterator lIt(m_lu, col); + for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { + typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); + typename MatrixType::InnerUpperIterator uIt(m_lu, rrow); + const double coef = lIt.value(); + + uItPivot += (rrow - row - 1); + + //update upper part -> contiguous memory access + for (++uItPivot; uIt && uItPivot;) { + uIt.valueRef() -= uItPivot.value() * coef; + + ++uIt; + ++uItPivot; + } + ++lIt; + } + + //Upper matrix update -> non contiguous memory access + typename MatrixType::InnerLowerIterator lIt3(m_lu, col); + for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { + typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); + const double coef = lIt3.value(); + + //update lower part -> non contiguous memory access + for (Index i = 0; i < rrow - row - 1; i++) { + m_lu.coeffRefLower(rrow, row + i + 1) -= uItPivot.value() * coef; + ++uItPivot; + } + ++lIt3; + } + //update diag -> contiguous + typename MatrixType::InnerLowerIterator lIt2(m_lu, col); + for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) { + + typename MatrixType::InnerUpperIterator uItPivot(m_lu, row); + typename MatrixType::InnerUpperIterator uIt(m_lu, rrow); + const double coef = lIt2.value(); + + uItPivot += (rrow - row - 1); + m_lu.coeffRefDiag(rrow) -= uItPivot.value() * coef; + ++lIt2; + } + } +} + +template +void SkylineInplaceLU::computeRowMajor() { + const size_t rows = m_lu.rows(); + const size_t cols = m_lu.cols(); + + eigen_assert(rows == cols && "We do not (yet) support rectangular LU."); + eigen_assert(m_lu.IsRowMajor && "You're trying to apply rowMajor decomposition on a ColMajor matrix !"); + + for (Index row = 0; row < rows; row++) { + typename MatrixType::InnerLowerIterator llIt(m_lu, row); + + + for (Index col = llIt.col(); col < row; col++) { + if (m_lu.coeffExistLower(row, col)) { + const double diag = m_lu.coeffDiag(col); + + typename MatrixType::InnerLowerIterator lIt(m_lu, row); + typename MatrixType::InnerUpperIterator uIt(m_lu, col); + + + const Index offset = lIt.col() - uIt.row(); + + + Index stop = offset > 0 ? col - lIt.col() : col - uIt.row(); + + //#define VECTORIZE +#ifdef VECTORIZE + Map rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); + Map colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); + + + Scalar newCoeff = m_lu.coeffLower(row, col) - rowVal.dot(colVal); +#else + if (offset > 0) //Skip zero value of lIt + uIt += offset; + else //Skip zero values of uIt + lIt += -offset; + Scalar newCoeff = m_lu.coeffLower(row, col); + + for (Index k = 0; k < stop; ++k) { + const Scalar tmp = newCoeff; + newCoeff = tmp - lIt.value() * uIt.value(); + ++lIt; + ++uIt; + } +#endif + + m_lu.coeffRefLower(row, col) = newCoeff / diag; + } + } + + //Upper matrix update + const Index col = row; + typename MatrixType::InnerUpperIterator uuIt(m_lu, col); + for (Index rrow = uuIt.row(); rrow < col; rrow++) { + + typename MatrixType::InnerLowerIterator lIt(m_lu, rrow); + typename MatrixType::InnerUpperIterator uIt(m_lu, col); + const Index offset = lIt.col() - uIt.row(); + + Index stop = offset > 0 ? rrow - lIt.col() : rrow - uIt.row(); + +#ifdef VECTORIZE + Map rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); + Map colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); + + Scalar newCoeff = m_lu.coeffUpper(rrow, col) - rowVal.dot(colVal); +#else + if (offset > 0) //Skip zero value of lIt + uIt += offset; + else //Skip zero values of uIt + lIt += -offset; + Scalar newCoeff = m_lu.coeffUpper(rrow, col); + for (Index k = 0; k < stop; ++k) { + const Scalar tmp = newCoeff; + newCoeff = tmp - lIt.value() * uIt.value(); + + ++lIt; + ++uIt; + } +#endif + m_lu.coeffRefUpper(rrow, col) = newCoeff; + } + + + //Diag matrix update + typename MatrixType::InnerLowerIterator lIt(m_lu, row); + typename MatrixType::InnerUpperIterator uIt(m_lu, row); + + const Index offset = lIt.col() - uIt.row(); + + + Index stop = offset > 0 ? lIt.size() : uIt.size(); +#ifdef VECTORIZE + Map rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop); + Map colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop); + Scalar newCoeff = m_lu.coeffDiag(row) - rowVal.dot(colVal); +#else + if (offset > 0) //Skip zero value of lIt + uIt += offset; + else //Skip zero values of uIt + lIt += -offset; + Scalar newCoeff = m_lu.coeffDiag(row); + for (Index k = 0; k < stop; ++k) { + const Scalar tmp = newCoeff; + newCoeff = tmp - lIt.value() * uIt.value(); + ++lIt; + ++uIt; + } +#endif + m_lu.coeffRefDiag(row) = newCoeff; + } +} + +/** Computes *x = U^-1 L^-1 b + * + * If \a transpose is set to SvTranspose or SvAdjoint, the solution + * of the transposed/adjoint system is computed instead. + * + * Not all backends implement the solution of the transposed or + * adjoint system. + */ +template +template +bool SkylineInplaceLU::solve(const MatrixBase &b, MatrixBase* x, const int transposed) const { + const size_t rows = m_lu.rows(); + const size_t cols = m_lu.cols(); + + + for (Index row = 0; row < rows; row++) { + x->coeffRef(row) = b.coeff(row); + Scalar newVal = x->coeff(row); + typename MatrixType::InnerLowerIterator lIt(m_lu, row); + + Index col = lIt.col(); + while (lIt.col() < row) { + + newVal -= x->coeff(col++) * lIt.value(); + ++lIt; + } + + x->coeffRef(row) = newVal; + } + + + for (Index col = rows - 1; col > 0; col--) { + x->coeffRef(col) = x->coeff(col) / m_lu.coeffDiag(col); + + const Scalar x_col = x->coeff(col); + + typename MatrixType::InnerUpperIterator uIt(m_lu, col); + uIt += uIt.size()-1; + + + while (uIt) { + x->coeffRef(uIt.row()) -= x_col * uIt.value(); + //TODO : introduce --operator + uIt += -1; + } + + + } + x->coeffRef(0) = x->coeff(0) / m_lu.coeffDiag(0); + + return true; +} + +} // end namespace Eigen + +#endif // EIGEN_SKYLINEINPLACELU_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrix.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..887bf834a7a2d528f77dae5a960473df6badd9ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrix.h @@ -0,0 +1,864 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINEMATRIX_H +#define EIGEN_SKYLINEMATRIX_H + +#include "SkylineStorage.h" +#include "SkylineMatrixBase.h" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \ingroup Skyline_Module + * + * \class SkylineMatrix + * + * \brief The main skyline matrix class + * + * This class implements a skyline matrix using the very uncommon storage + * scheme. + * + * \param Scalar_ the scalar type, i.e. the type of the coefficients + * \param Options_ Union of bit flags controlling the storage scheme. Currently the only possibility + * is RowMajor. The default is 0 which means column-major. + * + * + */ +namespace internal { +template +struct traits > { + typedef Scalar_ Scalar; + typedef Sparse StorageKind; + + enum { + RowsAtCompileTime = Dynamic, + ColsAtCompileTime = Dynamic, + MaxRowsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic, + Flags = SkylineBit | Options_, + CoeffReadCost = NumTraits::ReadCost, + }; +}; +} + +template +class SkylineMatrix +: public SkylineMatrixBase > { +public: + EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(SkylineMatrix) + EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, +=) + EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(SkylineMatrix, -=) + + using Base::IsRowMajor; + +protected: + + typedef SkylineMatrix TransposedSkylineMatrix; + + Index m_outerSize; + Index m_innerSize; + +public: + Index* m_colStartIndex; + Index* m_rowStartIndex; + SkylineStorage m_data; + +public: + + inline Index rows() const { + return IsRowMajor ? m_outerSize : m_innerSize; + } + + inline Index cols() const { + return IsRowMajor ? m_innerSize : m_outerSize; + } + + inline Index innerSize() const { + return m_innerSize; + } + + inline Index outerSize() const { + return m_outerSize; + } + + inline Index upperNonZeros() const { + return m_data.upperSize(); + } + + inline Index lowerNonZeros() const { + return m_data.lowerSize(); + } + + inline Index upperNonZeros(Index j) const { + return m_colStartIndex[j + 1] - m_colStartIndex[j]; + } + + inline Index lowerNonZeros(Index j) const { + return m_rowStartIndex[j + 1] - m_rowStartIndex[j]; + } + + inline const Scalar* _diagPtr() const { + return &m_data.diag(0); + } + + inline Scalar* _diagPtr() { + return &m_data.diag(0); + } + + inline const Scalar* _upperPtr() const { + return &m_data.upper(0); + } + + inline Scalar* _upperPtr() { + return &m_data.upper(0); + } + + inline const Scalar* _lowerPtr() const { + return &m_data.lower(0); + } + + inline Scalar* _lowerPtr() { + return &m_data.lower(0); + } + + inline const Index* _upperProfilePtr() const { + return &m_data.upperProfile(0); + } + + inline Index* _upperProfilePtr() { + return &m_data.upperProfile(0); + } + + inline const Index* _lowerProfilePtr() const { + return &m_data.lowerProfile(0); + } + + inline Index* _lowerProfilePtr() { + return &m_data.lowerProfile(0); + } + + inline Scalar coeff(Index row, Index col) const { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + + if (outer == inner) + return this->m_data.diag(outer); + + if (IsRowMajor) { + if (inner > outer) //upper matrix + { + const Index minOuterIndex = inner - m_data.upperProfile(inner); + if (outer >= minOuterIndex) + return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); + else + return Scalar(0); + } + if (inner < outer) //lower matrix + { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + if (inner >= minInnerIndex) + return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); + else + return Scalar(0); + } + return m_data.upper(m_colStartIndex[inner] + outer - inner); + } else { + if (outer > inner) //upper matrix + { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + if (outer <= maxOuterIndex) + return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); + else + return Scalar(0); + } + if (outer < inner) //lower matrix + { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + + if (inner <= maxInnerIndex) + return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); + else + return Scalar(0); + } + } + } + + inline Scalar& coeffRef(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + + if (outer == inner) + return this->m_data.diag(outer); + + if (IsRowMajor) { + if (col > row) //upper matrix + { + const Index minOuterIndex = inner - m_data.upperProfile(inner); + eigen_assert(outer >= minOuterIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); + } + if (col < row) //lower matrix + { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + eigen_assert(inner >= minInnerIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); + } + } else { + if (outer > inner) //upper matrix + { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + eigen_assert(outer <= maxOuterIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); + } + if (outer < inner) //lower matrix + { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + eigen_assert(inner <= maxInnerIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); + } + } + } + + inline Scalar coeffDiag(Index idx) const { + eigen_assert(idx < outerSize()); + eigen_assert(idx < innerSize()); + return this->m_data.diag(idx); + } + + inline Scalar coeffLower(Index row, Index col) const { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + if (inner >= minInnerIndex) + return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); + else + return Scalar(0); + + } else { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + if (inner <= maxInnerIndex) + return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); + else + return Scalar(0); + } + } + + inline Scalar coeffUpper(Index row, Index col) const { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minOuterIndex = inner - m_data.upperProfile(inner); + if (outer >= minOuterIndex) + return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); + else + return Scalar(0); + } else { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + if (outer <= maxOuterIndex) + return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); + else + return Scalar(0); + } + } + + inline Scalar& coeffRefDiag(Index idx) { + eigen_assert(idx < outerSize()); + eigen_assert(idx < innerSize()); + return this->m_data.diag(idx); + } + + inline Scalar& coeffRefLower(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + eigen_assert(inner >= minInnerIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); + } else { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + eigen_assert(inner <= maxInnerIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer)); + } + } + + inline bool coeffExistLower(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + return inner >= minInnerIndex; + } else { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + return inner <= maxInnerIndex; + } + } + + inline Scalar& coeffRefUpper(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minOuterIndex = inner - m_data.upperProfile(inner); + eigen_assert(outer >= minOuterIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); + } else { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + eigen_assert(outer <= maxOuterIndex && "You tried to access a coeff that does not exist in the storage"); + return this->m_data.upper(m_colStartIndex[inner] + (outer - inner)); + } + } + + inline bool coeffExistUpper(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + eigen_assert(inner != outer); + + if (IsRowMajor) { + const Index minOuterIndex = inner - m_data.upperProfile(inner); + return outer >= minOuterIndex; + } else { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + return outer <= maxOuterIndex; + } + } + + +protected: + +public: + class InnerUpperIterator; + class InnerLowerIterator; + + class OuterUpperIterator; + class OuterLowerIterator; + + /** Removes all non zeros */ + inline void setZero() { + m_data.clear(); + std::fill_n(m_colStartIndex, m_outerSize + 1, Index(0)); + std::fill_n(m_rowStartIndex, m_outerSize + 1, Index(0)); + } + + /** \returns the number of non zero coefficients */ + inline Index nonZeros() const { + return m_data.diagSize() + m_data.upperSize() + m_data.lowerSize(); + } + + /** Preallocates \a reserveSize non zeros */ + inline void reserve(Index reserveSize, Index reserveUpperSize, Index reserveLowerSize) { + m_data.reserve(reserveSize, reserveUpperSize, reserveLowerSize); + } + + /** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col. + + * + * \warning This function can be extremely slow if the non zero coefficients + * are not inserted in a coherent order. + * + * After an insertion session, you should call the finalize() function. + */ + EIGEN_DONT_INLINE Scalar & insert(Index row, Index col) { + const Index outer = IsRowMajor ? row : col; + const Index inner = IsRowMajor ? col : row; + + eigen_assert(outer < outerSize()); + eigen_assert(inner < innerSize()); + + if (outer == inner) + return m_data.diag(col); + + if (IsRowMajor) { + if (outer < inner) //upper matrix + { + Index minOuterIndex = 0; + minOuterIndex = inner - m_data.upperProfile(inner); + + if (outer < minOuterIndex) //The value does not yet exist + { + const Index previousProfile = m_data.upperProfile(inner); + + m_data.upperProfile(inner) = inner - outer; + + + const Index bandIncrement = m_data.upperProfile(inner) - previousProfile; + //shift data stored after this new one + const Index stop = m_colStartIndex[cols()]; + const Index start = m_colStartIndex[inner]; + + + for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { + m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx); + } + + for (Index innerIdx = cols(); innerIdx > inner; innerIdx--) { + m_colStartIndex[innerIdx] += bandIncrement; + } + + //zeros new data + std::fill_n(this->_upperPtr() + start, bandIncrement - 1, Scalar(0)); + + return m_data.upper(m_colStartIndex[inner]); + } else { + return m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner))); + } + } + + if (outer > inner) //lower matrix + { + const Index minInnerIndex = outer - m_data.lowerProfile(outer); + if (inner < minInnerIndex) //The value does not yet exist + { + const Index previousProfile = m_data.lowerProfile(outer); + m_data.lowerProfile(outer) = outer - inner; + + const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile; + //shift data stored after this new one + const Index stop = m_rowStartIndex[rows()]; + const Index start = m_rowStartIndex[outer]; + + + for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { + m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx); + } + + for (Index innerIdx = rows(); innerIdx > outer; innerIdx--) { + m_rowStartIndex[innerIdx] += bandIncrement; + } + + //zeros new data + std::fill_n(this->_lowerPtr() + start, bandIncrement - 1, Scalar(0)); + return m_data.lower(m_rowStartIndex[outer]); + } else { + return m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer))); + } + } + } else { + if (outer > inner) //upper matrix + { + const Index maxOuterIndex = inner + m_data.upperProfile(inner); + if (outer > maxOuterIndex) //The value does not yet exist + { + const Index previousProfile = m_data.upperProfile(inner); + m_data.upperProfile(inner) = outer - inner; + + const Index bandIncrement = m_data.upperProfile(inner) - previousProfile; + //shift data stored after this new one + const Index stop = m_rowStartIndex[rows()]; + const Index start = m_rowStartIndex[inner + 1]; + + for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { + m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx); + } + + for (Index innerIdx = inner + 1; innerIdx < outerSize() + 1; innerIdx++) { + m_rowStartIndex[innerIdx] += bandIncrement; + } + std::fill_n(this->_upperPtr() + m_rowStartIndex[inner] + previousProfile + 1, bandIncrement - 1, Scalar(0)); + return m_data.upper(m_rowStartIndex[inner] + m_data.upperProfile(inner)); + } else { + return m_data.upper(m_rowStartIndex[inner] + (outer - inner)); + } + } + + if (outer < inner) //lower matrix + { + const Index maxInnerIndex = outer + m_data.lowerProfile(outer); + if (inner > maxInnerIndex) //The value does not yet exist + { + const Index previousProfile = m_data.lowerProfile(outer); + m_data.lowerProfile(outer) = inner - outer; + + const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile; + //shift data stored after this new one + const Index stop = m_colStartIndex[cols()]; + const Index start = m_colStartIndex[outer + 1]; + + for (Index innerIdx = stop; innerIdx >= start; innerIdx--) { + m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx); + } + + for (Index innerIdx = outer + 1; innerIdx < outerSize() + 1; innerIdx++) { + m_colStartIndex[innerIdx] += bandIncrement; + } + std::fill_n(this->_lowerPtr() + m_colStartIndex[outer] + previousProfile + 1, bandIncrement - 1, Scalar(0)); + return m_data.lower(m_colStartIndex[outer] + m_data.lowerProfile(outer)); + } else { + return m_data.lower(m_colStartIndex[outer] + (inner - outer)); + } + } + } + } + + /** Must be called after inserting a set of non zero entries. + */ + inline void finalize() { + if (IsRowMajor) { + if (rows() > cols()) + m_data.resize(cols(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1); + else + m_data.resize(rows(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1); + + // eigen_assert(rows() == cols() && "memory reorganisatrion only works with suare matrix"); + // + // Scalar* newArray = new Scalar[m_colStartIndex[cols()] + 1 + m_rowStartIndex[rows()] + 1]; + // Index dataIdx = 0; + // for (Index row = 0; row < rows(); row++) { + // + // const Index nbLowerElts = m_rowStartIndex[row + 1] - m_rowStartIndex[row]; + // // std::cout << "nbLowerElts" << nbLowerElts << std::endl; + // memcpy(newArray + dataIdx, m_data.m_lower + m_rowStartIndex[row], nbLowerElts * sizeof (Scalar)); + // m_rowStartIndex[row] = dataIdx; + // dataIdx += nbLowerElts; + // + // const Index nbUpperElts = m_colStartIndex[row + 1] - m_colStartIndex[row]; + // memcpy(newArray + dataIdx, m_data.m_upper + m_colStartIndex[row], nbUpperElts * sizeof (Scalar)); + // m_colStartIndex[row] = dataIdx; + // dataIdx += nbUpperElts; + // + // + // } + // //todo : don't access m_data profile directly : add an accessor from SkylineMatrix + // m_rowStartIndex[rows()] = m_rowStartIndex[rows()-1] + m_data.lowerProfile(rows()-1); + // m_colStartIndex[cols()] = m_colStartIndex[cols()-1] + m_data.upperProfile(cols()-1); + // + // delete[] m_data.m_lower; + // delete[] m_data.m_upper; + // + // m_data.m_lower = newArray; + // m_data.m_upper = newArray; + } else { + if (rows() > cols()) + m_data.resize(cols(), rows(), cols(), m_rowStartIndex[cols()] + 1, m_colStartIndex[cols()] + 1); + else + m_data.resize(rows(), rows(), cols(), m_rowStartIndex[rows()] + 1, m_colStartIndex[rows()] + 1); + } + } + + inline void squeeze() { + finalize(); + m_data.squeeze(); + } + + void prune(Scalar reference, RealScalar epsilon = dummy_precision ()) { + //TODO + } + + /** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero + * \sa resizeNonZeros(Index), reserve(), setZero() + */ + void resize(size_t rows, size_t cols) { + const Index diagSize = rows > cols ? cols : rows; + m_innerSize = IsRowMajor ? cols : rows; + + eigen_assert(rows == cols && "Skyline matrix must be square matrix"); + + if (diagSize % 2) { // diagSize is odd + const Index k = (diagSize - 1) / 2; + + m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols, + 2 * k * k + k + 1, + 2 * k * k + k + 1); + + } else // diagSize is even + { + const Index k = diagSize / 2; + m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols, + 2 * k * k - k + 1, + 2 * k * k - k + 1); + } + + if (m_colStartIndex && m_rowStartIndex) { + delete[] m_colStartIndex; + delete[] m_rowStartIndex; + } + m_colStartIndex = new Index [cols + 1]; + m_rowStartIndex = new Index [rows + 1]; + m_outerSize = diagSize; + + m_data.reset(); + m_data.clear(); + + m_outerSize = diagSize; + std::fill_n(m_colStartIndex, cols + 1, Index(0)); + std::fill_n(m_rowStartIndex, rows + 1, Index(0)); + } + + void resizeNonZeros(Index size) { + m_data.resize(size); + } + + inline SkylineMatrix() + : m_outerSize(-1), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { + resize(0, 0); + } + + inline SkylineMatrix(size_t rows, size_t cols) + : m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { + resize(rows, cols); + } + + template + inline SkylineMatrix(const SkylineMatrixBase& other) + : m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { + *this = other.derived(); + } + + inline SkylineMatrix(const SkylineMatrix & other) + : Base(), m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) { + *this = other.derived(); + } + + inline void swap(SkylineMatrix & other) { + //EIGEN_DBG_SKYLINE(std::cout << "SkylineMatrix:: swap\n"); + std::swap(m_colStartIndex, other.m_colStartIndex); + std::swap(m_rowStartIndex, other.m_rowStartIndex); + std::swap(m_innerSize, other.m_innerSize); + std::swap(m_outerSize, other.m_outerSize); + m_data.swap(other.m_data); + } + + inline SkylineMatrix & operator=(const SkylineMatrix & other) { + std::cout << "SkylineMatrix& operator=(const SkylineMatrix& other)\n"; + if (other.isRValue()) { + swap(other.const_cast_derived()); + } else { + resize(other.rows(), other.cols()); + memcpy(m_colStartIndex, other.m_colStartIndex, (m_outerSize + 1) * sizeof (Index)); + memcpy(m_rowStartIndex, other.m_rowStartIndex, (m_outerSize + 1) * sizeof (Index)); + m_data = other.m_data; + } + return *this; + } + + template + inline SkylineMatrix & operator=(const SkylineMatrixBase& other) { + const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit); + if (needToTranspose) { + // TODO + // return *this; + } else { + // there is no special optimization + return SkylineMatrixBase::operator=(other.derived()); + } + } + + friend std::ostream & operator <<(std::ostream & s, const SkylineMatrix & m) { + + EIGEN_DBG_SKYLINE( + std::cout << "upper elements : " << std::endl; + for (Index i = 0; i < m.m_data.upperSize(); i++) + std::cout << m.m_data.upper(i) << "\t"; + std::cout << std::endl; + std::cout << "upper profile : " << std::endl; + for (Index i = 0; i < m.m_data.upperProfileSize(); i++) + std::cout << m.m_data.upperProfile(i) << "\t"; + std::cout << std::endl; + std::cout << "lower startIdx : " << std::endl; + for (Index i = 0; i < m.m_data.upperProfileSize(); i++) + std::cout << (IsRowMajor ? m.m_colStartIndex[i] : m.m_rowStartIndex[i]) << "\t"; + std::cout << std::endl; + + + std::cout << "lower elements : " << std::endl; + for (Index i = 0; i < m.m_data.lowerSize(); i++) + std::cout << m.m_data.lower(i) << "\t"; + std::cout << std::endl; + std::cout << "lower profile : " << std::endl; + for (Index i = 0; i < m.m_data.lowerProfileSize(); i++) + std::cout << m.m_data.lowerProfile(i) << "\t"; + std::cout << std::endl; + std::cout << "lower startIdx : " << std::endl; + for (Index i = 0; i < m.m_data.lowerProfileSize(); i++) + std::cout << (IsRowMajor ? m.m_rowStartIndex[i] : m.m_colStartIndex[i]) << "\t"; + std::cout << std::endl; + ); + for (Index rowIdx = 0; rowIdx < m.rows(); rowIdx++) { + for (Index colIdx = 0; colIdx < m.cols(); colIdx++) { + s << m.coeff(rowIdx, colIdx) << "\t"; + } + s << std::endl; + } + return s; + } + + /** Destructor */ + inline ~SkylineMatrix() { + delete[] m_colStartIndex; + delete[] m_rowStartIndex; + } + + /** Overloaded for performance */ + Scalar sum() const; +}; + +template +class SkylineMatrix::InnerUpperIterator { +public: + + InnerUpperIterator(const SkylineMatrix& mat, Index outer) + : m_matrix(mat), m_outer(outer), + m_id(Options_ == RowMajor ? mat.m_colStartIndex[outer] : mat.m_rowStartIndex[outer] + 1), + m_start(m_id), + m_end(Options_ == RowMajor ? mat.m_colStartIndex[outer + 1] : mat.m_rowStartIndex[outer + 1] + 1) { + } + + inline InnerUpperIterator & operator++() { + m_id++; + return *this; + } + + inline InnerUpperIterator & operator+=(Index shift) { + m_id += shift; + return *this; + } + + inline Scalar value() const { + return m_matrix.m_data.upper(m_id); + } + + inline Scalar* valuePtr() { + return const_cast (&(m_matrix.m_data.upper(m_id))); + } + + inline Scalar& valueRef() { + return const_cast (m_matrix.m_data.upper(m_id)); + } + + inline Index index() const { + return IsRowMajor ? m_outer - m_matrix.m_data.upperProfile(m_outer) + (m_id - m_start) : + m_outer + (m_id - m_start) + 1; + } + + inline Index row() const { + return IsRowMajor ? index() : m_outer; + } + + inline Index col() const { + return IsRowMajor ? m_outer : index(); + } + + inline size_t size() const { + return m_matrix.m_data.upperProfile(m_outer); + } + + inline operator bool() const { + return (m_id < m_end) && (m_id >= m_start); + } + +protected: + const SkylineMatrix& m_matrix; + const Index m_outer; + Index m_id; + const Index m_start; + const Index m_end; +}; + +template +class SkylineMatrix::InnerLowerIterator { +public: + + InnerLowerIterator(const SkylineMatrix& mat, Index outer) + : m_matrix(mat), + m_outer(outer), + m_id(Options_ == RowMajor ? mat.m_rowStartIndex[outer] : mat.m_colStartIndex[outer] + 1), + m_start(m_id), + m_end(Options_ == RowMajor ? mat.m_rowStartIndex[outer + 1] : mat.m_colStartIndex[outer + 1] + 1) { + } + + inline InnerLowerIterator & operator++() { + m_id++; + return *this; + } + + inline InnerLowerIterator & operator+=(Index shift) { + m_id += shift; + return *this; + } + + inline Scalar value() const { + return m_matrix.m_data.lower(m_id); + } + + inline Scalar* valuePtr() { + return const_cast (&(m_matrix.m_data.lower(m_id))); + } + + inline Scalar& valueRef() { + return const_cast (m_matrix.m_data.lower(m_id)); + } + + inline Index index() const { + return IsRowMajor ? m_outer - m_matrix.m_data.lowerProfile(m_outer) + (m_id - m_start) : + m_outer + (m_id - m_start) + 1; + ; + } + + inline Index row() const { + return IsRowMajor ? m_outer : index(); + } + + inline Index col() const { + return IsRowMajor ? index() : m_outer; + } + + inline size_t size() const { + return m_matrix.m_data.lowerProfile(m_outer); + } + + inline operator bool() const { + return (m_id < m_end) && (m_id >= m_start); + } + +protected: + const SkylineMatrix& m_matrix; + const Index m_outer; + Index m_id; + const Index m_start; + const Index m_end; +}; + +} // end namespace Eigen + +#endif // EIGEN_SKYLINEMATRIX_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrixBase.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrixBase.h new file mode 100644 index 0000000000000000000000000000000000000000..86fd10d2312a47708cc5f224fb3dde27c644eaf6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineMatrixBase.h @@ -0,0 +1,213 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINEMATRIXBASE_H +#define EIGEN_SKYLINEMATRIXBASE_H + +#include "SkylineUtil.h" + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \ingroup Skyline_Module + * + * \class SkylineMatrixBase + * + * \brief Base class of any skyline matrices or skyline expressions + * + * \param Derived + * + */ +template class SkylineMatrixBase : public EigenBase { +public: + + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::index::type Index; + + enum { + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + /**< The number of rows at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */ + + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + /**< The number of columns at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */ + + + SizeAtCompileTime = (internal::size_of_xpr_at_compile_time::ret), + /**< This is equal to the number of coefficients, i.e. the number of + * rows times the number of columns, or to \a Dynamic if this is not + * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ + + MaxRowsAtCompileTime = RowsAtCompileTime, + MaxColsAtCompileTime = ColsAtCompileTime, + + MaxSizeAtCompileTime = (internal::size_at_compile_time(MaxRowsAtCompileTime, + MaxColsAtCompileTime)), + + IsVectorAtCompileTime = RowsAtCompileTime == 1 || ColsAtCompileTime == 1, + /**< This is set to true if either the number of rows or the number of + * columns is known at compile-time to be equal to 1. Indeed, in that case, + * we are dealing with a column-vector (if there is only one column) or with + * a row-vector (if there is only one row). */ + + Flags = internal::traits::Flags, + /**< This stores expression \ref flags flags which may or may not be inherited by new expressions + * constructed from this one. See the \ref flags "list of flags". + */ + + CoeffReadCost = internal::traits::CoeffReadCost, + /**< This is a rough measure of how expensive it is to read one coefficient from + * this expression. + */ + + IsRowMajor = Flags & RowMajorBit ? 1 : 0 + }; + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is the "real scalar" type; if the \a Scalar type is already real numbers + * (e.g. int, float or double) then \a RealScalar is just the same as \a Scalar. If + * \a Scalar is \a std::complex then RealScalar is \a T. + * + * \sa class NumTraits + */ + typedef typename NumTraits::Real RealScalar; + + /** type of the equivalent square matrix */ + typedef Matrix SquareMatrixType; + + inline const Derived& derived() const { + return *static_cast (this); + } + + inline Derived& derived() { + return *static_cast (this); + } + + inline Derived& const_cast_derived() const { + return *static_cast (const_cast (this)); + } +#endif // not EIGEN_PARSED_BY_DOXYGEN + + /** \returns the number of rows. \sa cols(), RowsAtCompileTime */ + inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT { + return derived().rows(); + } + + /** \returns the number of columns. \sa rows(), ColsAtCompileTime*/ + inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT { + return derived().cols(); + } + + /** \returns the number of coefficients, which is \a rows()*cols(). + * \sa rows(), cols(), SizeAtCompileTime. */ + inline EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT { + return rows() * cols(); + } + + /** \returns the number of nonzero coefficients which is in practice the number + * of stored coefficients. */ + inline Index nonZeros() const { + return derived().nonZeros(); + } + + /** \returns the size of the storage major dimension, + * i.e., the number of columns for a columns major matrix, and the number of rows otherwise */ + Index outerSize() const { + return (int(Flags) & RowMajorBit) ? this->rows() : this->cols(); + } + + /** \returns the size of the inner dimension according to the storage order, + * i.e., the number of rows for a columns major matrix, and the number of cols otherwise */ + Index innerSize() const { + return (int(Flags) & RowMajorBit) ? this->cols() : this->rows(); + } + + bool isRValue() const { + return m_isRValue; + } + + Derived& markAsRValue() { + m_isRValue = true; + return derived(); + } + + SkylineMatrixBase() : m_isRValue(false) { + /* TODO check flags */ + } + + inline Derived & operator=(const Derived& other) { + this->operator= (other); + return derived(); + } + + template + inline void assignGeneric(const OtherDerived& other) { + derived().resize(other.rows(), other.cols()); + for (Index row = 0; row < rows(); row++) + for (Index col = 0; col < cols(); col++) { + if (other.coeff(row, col) != Scalar(0)) + derived().insert(row, col) = other.coeff(row, col); + } + derived().finalize(); + } + + template + inline Derived & operator=(const SkylineMatrixBase& other) { + //TODO + } + + template + inline Derived & operator=(const SkylineProduct& product); + + friend std::ostream & operator <<(std::ostream & s, const SkylineMatrixBase& m) { + s << m.derived(); + return s; + } + + template + const typename SkylineProductReturnType::Type + operator*(const MatrixBase &other) const; + + /** \internal use operator= */ + template + void evalTo(MatrixBase& dst) const { + dst.setZero(); + for (Index i = 0; i < rows(); i++) + for (Index j = 0; j < rows(); j++) + dst(i, j) = derived().coeff(i, j); + } + + Matrix toDense() const { + return derived(); + } + + /** \returns the matrix or vector obtained by evaluating this expression. + * + * Notice that in the case of a plain matrix or vector (not an expression) this function just returns + * a const reference, in order to avoid a useless copy. + */ + EIGEN_STRONG_INLINE const typename internal::eval::type eval() const { + return typename internal::eval::type(derived()); + } + +protected: + bool m_isRValue; +}; + +} // end namespace Eigen + +#endif // EIGEN_SKYLINEMATRIXBASE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineProduct.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..03f4269e3329959504a332131cbfe266164e5ebf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineProduct.h @@ -0,0 +1,297 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINEPRODUCT_H +#define EIGEN_SKYLINEPRODUCT_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +template +struct SkylineProductReturnType { + typedef const typename internal::nested_eval::type LhsNested; + typedef const typename internal::nested_eval::type RhsNested; + + typedef SkylineProduct Type; +}; + +template +struct internal::traits > { + // clean the nested types: + typedef internal::remove_all_t LhsNested_; + typedef internal::remove_all_t RhsNested_; + typedef typename LhsNested_::Scalar Scalar; + + enum { + LhsCoeffReadCost = LhsNested_::CoeffReadCost, + RhsCoeffReadCost = RhsNested_::CoeffReadCost, + LhsFlags = LhsNested_::Flags, + RhsFlags = RhsNested_::Flags, + + RowsAtCompileTime = LhsNested_::RowsAtCompileTime, + ColsAtCompileTime = RhsNested_::ColsAtCompileTime, + InnerSize = internal::min_size_prefer_fixed(LhsNested_::ColsAtCompileTime, RhsNested_::RowsAtCompileTime), + + MaxRowsAtCompileTime = LhsNested_::MaxRowsAtCompileTime, + MaxColsAtCompileTime = RhsNested_::MaxColsAtCompileTime, + + EvalToRowMajor = (RhsFlags & LhsFlags & RowMajorBit), + ResultIsSkyline = ProductMode == SkylineTimeSkylineProduct, + + RemovedBits = ~((EvalToRowMajor ? 0 : RowMajorBit) | (ResultIsSkyline ? 0 : SkylineBit)), + + Flags = (int(LhsFlags | RhsFlags) & HereditaryBits & RemovedBits) + | EvalBeforeAssigningBit + | EvalBeforeNestingBit, + + CoeffReadCost = HugeCost + }; + + typedef std::conditional_t >, + MatrixBase > > Base; +}; + +namespace internal { +template +class SkylineProduct : no_assignment_operator, +public traits >::Base { +public: + + EIGEN_GENERIC_PUBLIC_INTERFACE(SkylineProduct) + +private: + + typedef typename traits::LhsNested_ LhsNested_; + typedef typename traits::RhsNested_ RhsNested_; + +public: + + template + EIGEN_STRONG_INLINE SkylineProduct(const Lhs& lhs, const Rhs& rhs) + : m_lhs(lhs), m_rhs(rhs) { + eigen_assert(lhs.cols() == rhs.rows()); + + enum { + ProductIsValid = LhsNested_::ColsAtCompileTime == Dynamic + || RhsNested_::RowsAtCompileTime == Dynamic + || int(LhsNested_::ColsAtCompileTime) == int(RhsNested_::RowsAtCompileTime), + AreVectors = LhsNested_::IsVectorAtCompileTime && RhsNested_::IsVectorAtCompileTime, + SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(LhsNested_, RhsNested_) + }; + // note to the lost user: + // * for a dot product use: v1.dot(v2) + // * for a coeff-wise product use: v1.cwise()*v2 + EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes), + INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) + EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors), + INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) + EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT) + } + + EIGEN_STRONG_INLINE Index rows() const { + return m_lhs.rows(); + } + + EIGEN_STRONG_INLINE Index cols() const { + return m_rhs.cols(); + } + + EIGEN_STRONG_INLINE const LhsNested_& lhs() const { + return m_lhs; + } + + EIGEN_STRONG_INLINE const RhsNested_& rhs() const { + return m_rhs; + } + +protected: + LhsNested m_lhs; + RhsNested m_rhs; +}; + +// dense = skyline * dense +// Note that here we force no inlining and separate the setZero() because GCC messes up otherwise + +template +EIGEN_DONT_INLINE void skyline_row_major_time_dense_product(const Lhs& lhs, const Rhs& rhs, Dest& dst) { + typedef remove_all_t Lhs_; + typedef remove_all_t Rhs_; + typedef typename traits::Scalar Scalar; + + enum { + LhsIsRowMajor = (Lhs_::Flags & RowMajorBit) == RowMajorBit, + LhsIsSelfAdjoint = (Lhs_::Flags & SelfAdjointBit) == SelfAdjointBit, + ProcessFirstHalf = LhsIsSelfAdjoint + && (((Lhs_::Flags & (UpperTriangularBit | LowerTriangularBit)) == 0) + || ((Lhs_::Flags & UpperTriangularBit) && !LhsIsRowMajor) + || ((Lhs_::Flags & LowerTriangularBit) && LhsIsRowMajor)), + ProcessSecondHalf = LhsIsSelfAdjoint && (!ProcessFirstHalf) + }; + + //Use matrix diagonal part <- Improvement : use inner iterator on dense matrix. + for (Index col = 0; col < rhs.cols(); col++) { + for (Index row = 0; row < lhs.rows(); row++) { + dst(row, col) = lhs.coeffDiag(row) * rhs(row, col); + } + } + //Use matrix lower triangular part + for (Index row = 0; row < lhs.rows(); row++) { + typename Lhs_::InnerLowerIterator lIt(lhs, row); + const Index stop = lIt.col() + lIt.size(); + for (Index col = 0; col < rhs.cols(); col++) { + + Index k = lIt.col(); + Scalar tmp = 0; + while (k < stop) { + tmp += + lIt.value() * + rhs(k++, col); + ++lIt; + } + dst(row, col) += tmp; + lIt += -lIt.size(); + } + + } + + //Use matrix upper triangular part + for (Index lhscol = 0; lhscol < lhs.cols(); lhscol++) { + typename Lhs_::InnerUpperIterator uIt(lhs, lhscol); + const Index stop = uIt.size() + uIt.row(); + for (Index rhscol = 0; rhscol < rhs.cols(); rhscol++) { + + + const Scalar rhsCoeff = rhs.coeff(lhscol, rhscol); + Index k = uIt.row(); + while (k < stop) { + dst(k++, rhscol) += + uIt.value() * + rhsCoeff; + ++uIt; + } + uIt += -uIt.size(); + } + } + +} + +template +EIGEN_DONT_INLINE void skyline_col_major_time_dense_product(const Lhs& lhs, const Rhs& rhs, Dest& dst) { + typedef remove_all_t Lhs_; + typedef remove_all_t Rhs_; + typedef typename traits::Scalar Scalar; + + enum { + LhsIsRowMajor = (Lhs_::Flags & RowMajorBit) == RowMajorBit, + LhsIsSelfAdjoint = (Lhs_::Flags & SelfAdjointBit) == SelfAdjointBit, + ProcessFirstHalf = LhsIsSelfAdjoint + && (((Lhs_::Flags & (UpperTriangularBit | LowerTriangularBit)) == 0) + || ((Lhs_::Flags & UpperTriangularBit) && !LhsIsRowMajor) + || ((Lhs_::Flags & LowerTriangularBit) && LhsIsRowMajor)), + ProcessSecondHalf = LhsIsSelfAdjoint && (!ProcessFirstHalf) + }; + + //Use matrix diagonal part <- Improvement : use inner iterator on dense matrix. + for (Index col = 0; col < rhs.cols(); col++) { + for (Index row = 0; row < lhs.rows(); row++) { + dst(row, col) = lhs.coeffDiag(row) * rhs(row, col); + } + } + + //Use matrix upper triangular part + for (Index row = 0; row < lhs.rows(); row++) { + typename Lhs_::InnerUpperIterator uIt(lhs, row); + const Index stop = uIt.col() + uIt.size(); + for (Index col = 0; col < rhs.cols(); col++) { + + Index k = uIt.col(); + Scalar tmp = 0; + while (k < stop) { + tmp += + uIt.value() * + rhs(k++, col); + ++uIt; + } + + + dst(row, col) += tmp; + uIt += -uIt.size(); + } + } + + //Use matrix lower triangular part + for (Index lhscol = 0; lhscol < lhs.cols(); lhscol++) { + typename Lhs_::InnerLowerIterator lIt(lhs, lhscol); + const Index stop = lIt.size() + lIt.row(); + for (Index rhscol = 0; rhscol < rhs.cols(); rhscol++) { + + const Scalar rhsCoeff = rhs.coeff(lhscol, rhscol); + Index k = lIt.row(); + while (k < stop) { + dst(k++, rhscol) += + lIt.value() * + rhsCoeff; + ++lIt; + } + lIt += -lIt.size(); + } + } + +} + +template::Flags&RowMajorBit> + struct skyline_product_selector; + +template +struct skyline_product_selector { + typedef typename traits>::Scalar Scalar; + + static void run(const Lhs& lhs, const Rhs& rhs, ResultType & res) { + skyline_row_major_time_dense_product (lhs, rhs, res); + } +}; + +template +struct skyline_product_selector { + typedef typename traits>::Scalar Scalar; + + static void run(const Lhs& lhs, const Rhs& rhs, ResultType & res) { + skyline_col_major_time_dense_product (lhs, rhs, res); + } +}; + +} // end namespace internal + +// template +// template +// Derived & MatrixBase::lazyAssign(const SkylineProduct& product) { +// typedef internal::remove_all_t Lhs_; +// internal::skyline_product_selector, +// internal::remove_all_t, +// Derived>::run(product.lhs(), product.rhs(), derived()); +// +// return derived(); +// } + +// skyline * dense + +template +template +EIGEN_STRONG_INLINE const typename SkylineProductReturnType::Type +SkylineMatrixBase::operator*(const MatrixBase &other) const { + + return typename SkylineProductReturnType::Type(derived(), other.derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_SKYLINEPRODUCT_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineStorage.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineStorage.h new file mode 100644 index 0000000000000000000000000000000000000000..73b15a67f46f831deaee90d2b504c99b6a7f4bdc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineStorage.h @@ -0,0 +1,261 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINE_STORAGE_H +#define EIGEN_SKYLINE_STORAGE_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** Stores a skyline set of values in three structures : + * The diagonal elements + * The upper elements + * The lower elements + * + */ +template +class SkylineStorage { + typedef typename NumTraits::Real RealScalar; + typedef SparseIndex Index; +public: + + SkylineStorage() + : m_diag(0), + m_lower(0), + m_upper(0), + m_lowerProfile(0), + m_upperProfile(0), + m_diagSize(0), + m_upperSize(0), + m_lowerSize(0), + m_upperProfileSize(0), + m_lowerProfileSize(0), + m_allocatedSize(0) { + } + + SkylineStorage(const SkylineStorage& other) + : m_diag(0), + m_lower(0), + m_upper(0), + m_lowerProfile(0), + m_upperProfile(0), + m_diagSize(0), + m_upperSize(0), + m_lowerSize(0), + m_upperProfileSize(0), + m_lowerProfileSize(0), + m_allocatedSize(0) { + *this = other; + } + + SkylineStorage & operator=(const SkylineStorage& other) { + resize(other.diagSize(), other.m_upperProfileSize, other.m_lowerProfileSize, other.upperSize(), other.lowerSize()); + memcpy(m_diag, other.m_diag, m_diagSize * sizeof (Scalar)); + memcpy(m_upper, other.m_upper, other.upperSize() * sizeof (Scalar)); + memcpy(m_lower, other.m_lower, other.lowerSize() * sizeof (Scalar)); + memcpy(m_upperProfile, other.m_upperProfile, m_upperProfileSize * sizeof (Index)); + memcpy(m_lowerProfile, other.m_lowerProfile, m_lowerProfileSize * sizeof (Index)); + return *this; + } + + void swap(SkylineStorage& other) { + std::swap(m_diag, other.m_diag); + std::swap(m_upper, other.m_upper); + std::swap(m_lower, other.m_lower); + std::swap(m_upperProfile, other.m_upperProfile); + std::swap(m_lowerProfile, other.m_lowerProfile); + std::swap(m_diagSize, other.m_diagSize); + std::swap(m_upperSize, other.m_upperSize); + std::swap(m_lowerSize, other.m_lowerSize); + std::swap(m_allocatedSize, other.m_allocatedSize); + } + + ~SkylineStorage() { + delete[] m_diag; + delete[] m_upper; + if (m_upper != m_lower) + delete[] m_lower; + delete[] m_upperProfile; + delete[] m_lowerProfile; + } + + void reserve(Index size, Index upperProfileSize, Index lowerProfileSize, Index upperSize, Index lowerSize) { + Index newAllocatedSize = size + upperSize + lowerSize; + if (newAllocatedSize > m_allocatedSize) + reallocate(size, upperProfileSize, lowerProfileSize, upperSize, lowerSize); + } + + void squeeze() { + if (m_allocatedSize > m_diagSize + m_upperSize + m_lowerSize) + reallocate(m_diagSize, m_upperProfileSize, m_lowerProfileSize, m_upperSize, m_lowerSize); + } + + void resize(Index diagSize, Index upperProfileSize, Index lowerProfileSize, Index upperSize, Index lowerSize, float reserveSizeFactor = 0) { + if (m_allocatedSize < diagSize + upperSize + lowerSize) + reallocate(diagSize, upperProfileSize, lowerProfileSize, upperSize + Index(reserveSizeFactor * upperSize), lowerSize + Index(reserveSizeFactor * lowerSize)); + m_diagSize = diagSize; + m_upperSize = upperSize; + m_lowerSize = lowerSize; + m_upperProfileSize = upperProfileSize; + m_lowerProfileSize = lowerProfileSize; + } + + inline Index diagSize() const { + return m_diagSize; + } + + inline Index upperSize() const { + return m_upperSize; + } + + inline Index lowerSize() const { + return m_lowerSize; + } + + inline Index upperProfileSize() const { + return m_upperProfileSize; + } + + inline Index lowerProfileSize() const { + return m_lowerProfileSize; + } + + inline Index allocatedSize() const { + return m_allocatedSize; + } + + inline void clear() { + m_diagSize = 0; + } + + inline Scalar& diag(Index i) { + return m_diag[i]; + } + + inline const Scalar& diag(Index i) const { + return m_diag[i]; + } + + inline Scalar& upper(Index i) { + return m_upper[i]; + } + + inline const Scalar& upper(Index i) const { + return m_upper[i]; + } + + inline Scalar& lower(Index i) { + return m_lower[i]; + } + + inline const Scalar& lower(Index i) const { + return m_lower[i]; + } + + inline Index& upperProfile(Index i) { + return m_upperProfile[i]; + } + + inline const Index& upperProfile(Index i) const { + return m_upperProfile[i]; + } + + inline Index& lowerProfile(Index i) { + return m_lowerProfile[i]; + } + + inline const Index& lowerProfile(Index i) const { + return m_lowerProfile[i]; + } + + static SkylineStorage Map(Index* upperProfile, Index* lowerProfile, Scalar* diag, Scalar* upper, Scalar* lower, Index size, Index upperSize, Index lowerSize) { + SkylineStorage res; + res.m_upperProfile = upperProfile; + res.m_lowerProfile = lowerProfile; + res.m_diag = diag; + res.m_upper = upper; + res.m_lower = lower; + res.m_allocatedSize = res.m_diagSize = size; + res.m_upperSize = upperSize; + res.m_lowerSize = lowerSize; + return res; + } + + inline void reset() { + std::fill_n(m_diag, m_diagSize, Scalar(0)); + std::fill_n(m_upper, m_upperSize, Scalar(0)); + std::fill_n(m_lower, m_lowerSize, Scalar(0)); + std::fill_n(m_upperProfile, m_diagSize, Index(0)); + std::fill_n(m_lowerProfile, m_diagSize, Index(0)); + } + + void prune(Scalar reference, RealScalar epsilon = dummy_precision()) { + //TODO + } + +protected: + + inline void reallocate(Index diagSize, Index upperProfileSize, Index lowerProfileSize, Index upperSize, Index lowerSize) { + + Scalar* diag = new Scalar[diagSize]; + Scalar* upper = new Scalar[upperSize]; + Scalar* lower = new Scalar[lowerSize]; + Index* upperProfile = new Index[upperProfileSize]; + Index* lowerProfile = new Index[lowerProfileSize]; + + Index copyDiagSize = (std::min)(diagSize, m_diagSize); + Index copyUpperSize = (std::min)(upperSize, m_upperSize); + Index copyLowerSize = (std::min)(lowerSize, m_lowerSize); + Index copyUpperProfileSize = (std::min)(upperProfileSize, m_upperProfileSize); + Index copyLowerProfileSize = (std::min)(lowerProfileSize, m_lowerProfileSize); + + // copy + memcpy(diag, m_diag, copyDiagSize * sizeof (Scalar)); + memcpy(upper, m_upper, copyUpperSize * sizeof (Scalar)); + memcpy(lower, m_lower, copyLowerSize * sizeof (Scalar)); + memcpy(upperProfile, m_upperProfile, copyUpperProfileSize * sizeof (Index)); + memcpy(lowerProfile, m_lowerProfile, copyLowerProfileSize * sizeof (Index)); + + + + // delete old stuff + delete[] m_diag; + delete[] m_upper; + delete[] m_lower; + delete[] m_upperProfile; + delete[] m_lowerProfile; + m_diag = diag; + m_upper = upper; + m_lower = lower; + m_upperProfile = upperProfile; + m_lowerProfile = lowerProfile; + m_allocatedSize = diagSize + upperSize + lowerSize; + m_upperSize = upperSize; + m_lowerSize = lowerSize; + } + +public: + Scalar* m_diag; + Scalar* m_upper; + Scalar* m_lower; + Index* m_upperProfile; + Index* m_lowerProfile; + Index m_diagSize; + Index m_upperSize; + Index m_lowerSize; + Index m_upperProfileSize; + Index m_lowerProfileSize; + Index m_allocatedSize; + +}; + +} // end namespace Eigen + +#endif // EIGEN_SKYLINE_STORAGE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineUtil.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineUtil.h new file mode 100644 index 0000000000000000000000000000000000000000..47fb4e328e22e44c3fa9a6ca868cad9debd42feb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Skyline/SkylineUtil.h @@ -0,0 +1,91 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Guillaume Saupin +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SKYLINEUTIL_H +#define EIGEN_SKYLINEUTIL_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +#ifdef NDEBUG +#define EIGEN_DBG_SKYLINE(X) +#else +#define EIGEN_DBG_SKYLINE(X) X +#endif + +const unsigned int SkylineBit = 0x1200; +template class SkylineProduct; +enum AdditionalProductEvaluationMode {SkylineTimeDenseProduct, SkylineTimeSkylineProduct, DenseTimeSkylineProduct}; +enum {IsSkyline = SkylineBit}; + + +#define EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, Op) \ +template \ +EIGEN_STRONG_INLINE Derived& operator Op(const Eigen::SkylineMatrixBase& other) \ +{ \ + return Base::operator Op(other.derived()); \ +} \ +EIGEN_STRONG_INLINE Derived& operator Op(const Derived& other) \ +{ \ + return Base::operator Op(other); \ +} + +#define EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, Op) \ +template \ +EIGEN_STRONG_INLINE Derived& operator Op(const Other& scalar) \ +{ \ + return Base::operator Op(scalar); \ +} + +#define EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATORS(Derived) \ + EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, =) \ + EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, +=) \ + EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, -=) \ + EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, *=) \ + EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, /=) + +#define EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE_(Derived, BaseClass) \ + typedef BaseClass Base; \ + typedef typename Eigen::internal::traits::Scalar Scalar; \ + typedef typename Eigen::NumTraits::Real RealScalar; \ + typedef typename Eigen::internal::traits::StorageKind StorageKind; \ + typedef typename Eigen::internal::index::type Index; \ + enum { Flags = Eigen::internal::traits::Flags, }; + +#define EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(Derived) \ + EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE_(Derived, Eigen::SkylineMatrixBase) + +template class SkylineMatrixBase; +template class SkylineMatrix; +template class DynamicSkylineMatrix; +template class SkylineVector; +template class MappedSkylineMatrix; + +namespace internal { + +template struct skyline_product_mode; +template::value> struct SkylineProductReturnType; + +template class eval +{ + typedef typename traits::Scalar Scalar_; + enum { + Flags_ = traits::Flags + }; + + public: + typedef SkylineMatrix type; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SKYLINEUTIL_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/BlockSparseMatrix.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/BlockSparseMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..853fbb0c0bd49da9b2c4f15f8e28c5602a5c0201 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/BlockSparseMatrix.h @@ -0,0 +1,1081 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2013 Desire Nuentsa +// Copyright (C) 2013 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEBLOCKMATRIX_H +#define EIGEN_SPARSEBLOCKMATRIX_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +/** \ingroup SparseCore_Module + * + * \class BlockSparseMatrix + * + * \brief A versatile sparse matrix representation where each element is a block + * + * This class provides routines to manipulate block sparse matrices stored in a + * BSR-like representation. There are two main types : + * + * 1. All blocks have the same number of rows and columns, called block size + * in the following. In this case, if this block size is known at compile time, + * it can be given as a template parameter like + * \code + * BlockSparseMatrix bmat(b_rows, b_cols); + * \endcode + * Here, bmat is a b_rows x b_cols block sparse matrix + * where each coefficient is a 3x3 dense matrix. + * If the block size is fixed but will be given at runtime, + * \code + * BlockSparseMatrix bmat(b_rows, b_cols); + * bmat.setBlockSize(block_size); + * \endcode + * + * 2. The second case is for variable-block sparse matrices. + * Here each block has its own dimensions. The only restriction is that all the blocks + * in a row (resp. a column) should have the same number of rows (resp. of columns). + * It is thus required in this case to describe the layout of the matrix by calling + * setBlockLayout(rowBlocks, colBlocks). + * + * In any of the previous case, the matrix can be filled by calling setFromTriplets(). + * A regular sparse matrix can be converted to a block sparse matrix and vice versa. + * It is obviously required to describe the block layout beforehand by calling either + * setBlockSize() for fixed-size blocks or setBlockLayout for variable-size blocks. + * + * \tparam Scalar_ The Scalar type + * \tparam _BlockAtCompileTime The block layout option. It takes the following values + * Dynamic : block size known at runtime + * a numeric number : fixed-size block known at compile time + */ +template class BlockSparseMatrix; + +template class BlockSparseMatrixView; + +namespace internal { +template +struct traits > +{ + typedef Scalar_ Scalar; + typedef Index_ Index; + typedef Sparse StorageKind; // FIXME Where is it used ?? + typedef MatrixXpr XprKind; + enum { + RowsAtCompileTime = Dynamic, + ColsAtCompileTime = Dynamic, + MaxRowsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic, + BlockSize = _BlockAtCompileTime, + Flags = Options_ | NestByRefBit | LvalueBit, + CoeffReadCost = NumTraits::ReadCost, + SupportedAccessPatterns = InnerRandomAccessPattern + }; +}; +template +struct traits > +{ + typedef Ref > Scalar; + typedef Ref > RealScalar; + +}; + +// Function object to sort a triplet list +template +struct TripletComp +{ + typedef typename Iterator::value_type Triplet; + bool operator()(const Triplet& a, const Triplet& b) + { if(IsColMajor) + return ((a.col() == b.col() && a.row() < b.row()) || (a.col() < b.col())); + else + return ((a.row() == b.row() && a.col() < b.col()) || (a.row() < b.row())); + } +}; +} // end namespace internal + + +/* Proxy to view the block sparse matrix as a regular sparse matrix */ +template +class BlockSparseMatrixView : public SparseMatrixBase +{ + public: + typedef Ref Scalar; + typedef Ref RealScalar; + typedef typename BlockSparseMatrixT::Index Index; + typedef BlockSparseMatrixT Nested; + enum { + Flags = BlockSparseMatrixT::Options, + Options = BlockSparseMatrixT::Options, + RowsAtCompileTime = BlockSparseMatrixT::RowsAtCompileTime, + ColsAtCompileTime = BlockSparseMatrixT::ColsAtCompileTime, + MaxColsAtCompileTime = BlockSparseMatrixT::MaxColsAtCompileTime, + MaxRowsAtCompileTime = BlockSparseMatrixT::MaxRowsAtCompileTime + }; + public: + BlockSparseMatrixView(const BlockSparseMatrixT& spblockmat) + : m_spblockmat(spblockmat) + {} + + Index outerSize() const + { + return (Flags&RowMajorBit) == 1 ? this->rows() : this->cols(); + } + Index cols() const + { + return m_spblockmat.blockCols(); + } + Index rows() const + { + return m_spblockmat.blockRows(); + } + Scalar coeff(Index row, Index col) + { + return m_spblockmat.coeff(row, col); + } + Scalar coeffRef(Index row, Index col) + { + return m_spblockmat.coeffRef(row, col); + } + // Wrapper to iterate over all blocks + class InnerIterator : public BlockSparseMatrixT::BlockInnerIterator + { + public: + InnerIterator(const BlockSparseMatrixView& mat, Index outer) + : BlockSparseMatrixT::BlockInnerIterator(mat.m_spblockmat, outer) + {} + + }; + + protected: + const BlockSparseMatrixT& m_spblockmat; +}; + +// Proxy to view a regular vector as a block vector +template +class BlockVectorView +{ + public: + enum { + BlockSize = BlockSparseMatrixT::BlockSize, + ColsAtCompileTime = VectorType::ColsAtCompileTime, + RowsAtCompileTime = VectorType::RowsAtCompileTime, + Flags = VectorType::Flags + }; + typedef Ref >Scalar; + typedef typename BlockSparseMatrixT::Index Index; + public: + BlockVectorView(const BlockSparseMatrixT& spblockmat, const VectorType& vec) + : m_spblockmat(spblockmat),m_vec(vec) + { } + inline Index cols() const + { + return m_vec.cols(); + } + inline Index size() const + { + return m_spblockmat.blockRows(); + } + inline Scalar coeff(Index bi) const + { + Index startRow = m_spblockmat.blockRowsIndex(bi); + Index rowSize = m_spblockmat.blockRowsIndex(bi+1) - startRow; + return m_vec.middleRows(startRow, rowSize); + } + inline Scalar coeff(Index bi, Index j) const + { + Index startRow = m_spblockmat.blockRowsIndex(bi); + Index rowSize = m_spblockmat.blockRowsIndex(bi+1) - startRow; + return m_vec.block(startRow, j, rowSize, 1); + } + protected: + const BlockSparseMatrixT& m_spblockmat; + const VectorType& m_vec; +}; + +template class BlockVectorReturn; + + +// Proxy to view a regular vector as a block vector +template +class BlockVectorReturn +{ + public: + enum { + ColsAtCompileTime = VectorType::ColsAtCompileTime, + RowsAtCompileTime = VectorType::RowsAtCompileTime, + Flags = VectorType::Flags + }; + typedef Ref > Scalar; + typedef typename BlockSparseMatrixT::Index Index; + public: + BlockVectorReturn(const BlockSparseMatrixT& spblockmat, VectorType& vec) + : m_spblockmat(spblockmat),m_vec(vec) + { } + inline Index size() const + { + return m_spblockmat.blockRows(); + } + inline Scalar coeffRef(Index bi) + { + Index startRow = m_spblockmat.blockRowsIndex(bi); + Index rowSize = m_spblockmat.blockRowsIndex(bi+1) - startRow; + return m_vec.middleRows(startRow, rowSize); + } + inline Scalar coeffRef(Index bi, Index j) + { + Index startRow = m_spblockmat.blockRowsIndex(bi); + Index rowSize = m_spblockmat.blockRowsIndex(bi+1) - startRow; + return m_vec.block(startRow, j, rowSize, 1); + } + + protected: + const BlockSparseMatrixT& m_spblockmat; + VectorType& m_vec; +}; + +// Block version of the sparse dense product +template +class BlockSparseTimeDenseProduct; + +namespace internal { + +template +struct traits > +{ + typedef Dense StorageKind; + typedef MatrixXpr XprKind; + typedef typename BlockSparseMatrixT::Scalar Scalar; + typedef typename BlockSparseMatrixT::Index Index; + enum { + RowsAtCompileTime = Dynamic, + ColsAtCompileTime = Dynamic, + MaxRowsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic, + Flags = 0, + CoeffReadCost = internal::traits::CoeffReadCost + }; +}; +} // end namespace internal + +template +class BlockSparseTimeDenseProduct + : public ProductBase, Lhs, Rhs> +{ + public: + EIGEN_PRODUCT_PUBLIC_INTERFACE(BlockSparseTimeDenseProduct) + + BlockSparseTimeDenseProduct(const Lhs& lhs, const Rhs& rhs) : Base(lhs,rhs) + {} + + template void scaleAndAddTo(Dest& dest, const typename Rhs::Scalar& alpha) const + { + BlockVectorReturn tmpDest(m_lhs, dest); + internal::sparse_time_dense_product( BlockSparseMatrixView(m_lhs), BlockVectorView(m_lhs, m_rhs), tmpDest, alpha); + } + + private: + BlockSparseTimeDenseProduct& operator=(const BlockSparseTimeDenseProduct&); +}; + +template +class BlockSparseMatrix : public SparseMatrixBase > +{ + public: + typedef Scalar_ Scalar; + typedef typename NumTraits::Real RealScalar; + typedef StorageIndex_ StorageIndex; + typedef typename internal::ref_selector >::type Nested; + + enum { + Options = Options_, + Flags = Options, + BlockSize=_BlockAtCompileTime, + RowsAtCompileTime = Dynamic, + ColsAtCompileTime = Dynamic, + MaxRowsAtCompileTime = Dynamic, + MaxColsAtCompileTime = Dynamic, + IsVectorAtCompileTime = 0, + IsColMajor = Flags&RowMajorBit ? 0 : 1 + }; + typedef Matrix BlockScalar; + typedef Matrix BlockRealScalar; + typedef std::conditional_t<_BlockAtCompileTime==Dynamic, Scalar, BlockScalar> BlockScalarReturnType; + typedef BlockSparseMatrix PlainObject; + public: + // Default constructor + BlockSparseMatrix() + : m_innerBSize(0),m_outerBSize(0),m_innerOffset(0),m_outerOffset(0), + m_nonzerosblocks(0),m_values(0),m_blockPtr(0),m_indices(0), + m_outerIndex(0),m_blockSize(BlockSize) + { } + + + /** + * \brief Construct and resize + * + */ + BlockSparseMatrix(Index brow, Index bcol) + : m_innerBSize(IsColMajor ? brow : bcol), + m_outerBSize(IsColMajor ? bcol : brow), + m_innerOffset(0),m_outerOffset(0),m_nonzerosblocks(0), + m_values(0),m_blockPtr(0),m_indices(0), + m_outerIndex(0),m_blockSize(BlockSize) + { } + + /** + * \brief Copy-constructor + */ + BlockSparseMatrix(const BlockSparseMatrix& other) + : m_innerBSize(other.m_innerBSize),m_outerBSize(other.m_outerBSize), + m_nonzerosblocks(other.m_nonzerosblocks),m_nonzeros(other.m_nonzeros), + m_blockPtr(0),m_blockSize(other.m_blockSize) + { + // should we allow copying between variable-size blocks and fixed-size blocks ?? + eigen_assert(m_blockSize == BlockSize && " CAN NOT COPY BETWEEN FIXED-SIZE AND VARIABLE-SIZE BLOCKS"); + + std::copy(other.m_innerOffset, other.m_innerOffset+m_innerBSize+1, m_innerOffset); + std::copy(other.m_outerOffset, other.m_outerOffset+m_outerBSize+1, m_outerOffset); + std::copy(other.m_values, other.m_values+m_nonzeros, m_values); + + if(m_blockSize != Dynamic) + std::copy(other.m_blockPtr, other.m_blockPtr+m_nonzerosblocks, m_blockPtr); + + std::copy(other.m_indices, other.m_indices+m_nonzerosblocks, m_indices); + std::copy(other.m_outerIndex, other.m_outerIndex+m_outerBSize, m_outerIndex); + } + + friend void swap(BlockSparseMatrix& first, BlockSparseMatrix& second) + { + std::swap(first.m_innerBSize, second.m_innerBSize); + std::swap(first.m_outerBSize, second.m_outerBSize); + std::swap(first.m_innerOffset, second.m_innerOffset); + std::swap(first.m_outerOffset, second.m_outerOffset); + std::swap(first.m_nonzerosblocks, second.m_nonzerosblocks); + std::swap(first.m_nonzeros, second.m_nonzeros); + std::swap(first.m_values, second.m_values); + std::swap(first.m_blockPtr, second.m_blockPtr); + std::swap(first.m_indices, second.m_indices); + std::swap(first.m_outerIndex, second.m_outerIndex); + std::swap(first.m_BlockSize, second.m_blockSize); + } + + BlockSparseMatrix& operator=(BlockSparseMatrix other) + { + //Copy-and-swap paradigm ... avoid leaked data if thrown + swap(*this, other); + return *this; + } + + // Destructor + ~BlockSparseMatrix() + { + delete[] m_outerIndex; + delete[] m_innerOffset; + delete[] m_outerOffset; + delete[] m_indices; + delete[] m_blockPtr; + delete[] m_values; + } + + + /** + * \brief Constructor from a sparse matrix + * + */ + template + inline BlockSparseMatrix(const MatrixType& spmat) : m_blockSize(BlockSize) + { + EIGEN_STATIC_ASSERT((m_blockSize != Dynamic), THIS_METHOD_IS_ONLY_FOR_FIXED_SIZE); + + *this = spmat; + } + + /** + * \brief Assignment from a sparse matrix with the same storage order + * + * Convert from a sparse matrix to block sparse matrix. + * \warning Before calling this function, tt is necessary to call + * either setBlockLayout() (matrices with variable-size blocks) + * or setBlockSize() (for fixed-size blocks). + */ + template + inline BlockSparseMatrix& operator=(const MatrixType& spmat) + { + eigen_assert((m_innerBSize != 0 && m_outerBSize != 0) + && "Trying to assign to a zero-size matrix, call resize() first"); + eigen_assert(((MatrixType::Options&RowMajorBit) != IsColMajor) && "Wrong storage order"); + typedef SparseMatrix MatrixPatternType; + MatrixPatternType blockPattern(blockRows(), blockCols()); + m_nonzeros = 0; + + // First, compute the number of nonzero blocks and their locations + for(StorageIndex bj = 0; bj < m_outerBSize; ++bj) + { + // Browse each outer block and compute the structure + std::vector nzblocksFlag(m_innerBSize,false); // Record the existing blocks + blockPattern.startVec(bj); + for(StorageIndex j = blockOuterIndex(bj); j < blockOuterIndex(bj+1); ++j) + { + typename MatrixType::InnerIterator it_spmat(spmat, j); + for(; it_spmat; ++it_spmat) + { + StorageIndex bi = innerToBlock(it_spmat.index()); // Index of the current nonzero block + if(!nzblocksFlag[bi]) + { + // Save the index of this nonzero block + nzblocksFlag[bi] = true; + blockPattern.insertBackByOuterInnerUnordered(bj, bi) = true; + // Compute the total number of nonzeros (including explicit zeros in blocks) + m_nonzeros += blockOuterSize(bj) * blockInnerSize(bi); + } + } + } // end current outer block + } + blockPattern.finalize(); + + // Allocate the internal arrays + setBlockStructure(blockPattern); + + for(StorageIndex nz = 0; nz < m_nonzeros; ++nz) m_values[nz] = Scalar(0); + for(StorageIndex bj = 0; bj < m_outerBSize; ++bj) + { + // Now copy the values + for(StorageIndex j = blockOuterIndex(bj); j < blockOuterIndex(bj+1); ++j) + { + // Browse the outer block column by column (for column-major matrices) + typename MatrixType::InnerIterator it_spmat(spmat, j); + for(; it_spmat; ++it_spmat) + { + StorageIndex idx = 0; // Position of this block in the column block + StorageIndex bi = innerToBlock(it_spmat.index()); // Index of the current nonzero block + // Go to the inner block where this element belongs to + while(bi > m_indices[m_outerIndex[bj]+idx]) ++idx; // Not expensive for ordered blocks + StorageIndex idxVal;// Get the right position in the array of values for this element + if(m_blockSize == Dynamic) + { + // Offset from all blocks before ... + idxVal = m_blockPtr[m_outerIndex[bj]+idx]; + // ... and offset inside the block + idxVal += (j - blockOuterIndex(bj)) * blockOuterSize(bj) + it_spmat.index() - m_innerOffset[bi]; + } + else + { + // All blocks before + idxVal = (m_outerIndex[bj] + idx) * m_blockSize * m_blockSize; + // inside the block + idxVal += (j - blockOuterIndex(bj)) * m_blockSize + (it_spmat.index()%m_blockSize); + } + // Insert the value + m_values[idxVal] = it_spmat.value(); + } // end of this column + } // end of this block + } // end of this outer block + + return *this; + } + + /** + * \brief Set the nonzero block pattern of the matrix + * + * Given a sparse matrix describing the nonzero block pattern, + * this function prepares the internal pointers for values. + * After calling this function, any *nonzero* block (bi, bj) can be set + * with a simple call to coeffRef(bi,bj). + * + * + * \warning Before calling this function, tt is necessary to call + * either setBlockLayout() (matrices with variable-size blocks) + * or setBlockSize() (for fixed-size blocks). + * + * \param blockPattern Sparse matrix of boolean elements describing the block structure + * + * \sa setBlockLayout() \sa setBlockSize() + */ + template + void setBlockStructure(const MatrixType& blockPattern) + { + resize(blockPattern.rows(), blockPattern.cols()); + reserve(blockPattern.nonZeros()); + + // Browse the block pattern and set up the various pointers + m_outerIndex[0] = 0; + if(m_blockSize == Dynamic) m_blockPtr[0] = 0; + for(StorageIndex nz = 0; nz < m_nonzeros; ++nz) m_values[nz] = Scalar(0); + for(StorageIndex bj = 0; bj < m_outerBSize; ++bj) + { + //Browse each outer block + + //First, copy and save the indices of nonzero blocks + //FIXME : find a way to avoid this ... + std::vector nzBlockIdx; + typename MatrixType::InnerIterator it(blockPattern, bj); + for(; it; ++it) + { + nzBlockIdx.push_back(it.index()); + } + std::sort(nzBlockIdx.begin(), nzBlockIdx.end()); + + // Now, fill block indices and (eventually) pointers to blocks + for(StorageIndex idx = 0; idx < nzBlockIdx.size(); ++idx) + { + StorageIndex offset = m_outerIndex[bj]+idx; // offset in m_indices + m_indices[offset] = nzBlockIdx[idx]; + if(m_blockSize == Dynamic) + m_blockPtr[offset] = m_blockPtr[offset-1] + blockInnerSize(nzBlockIdx[idx]) * blockOuterSize(bj); + // There is no blockPtr for fixed-size blocks... not needed !??? + } + // Save the pointer to the next outer block + m_outerIndex[bj+1] = m_outerIndex[bj] + nzBlockIdx.size(); + } + } + + /** + * \brief Set the number of rows and columns blocks + */ + inline void resize(Index brow, Index bcol) + { + m_innerBSize = IsColMajor ? brow : bcol; + m_outerBSize = IsColMajor ? bcol : brow; + } + + /** + * \brief set the block size at runtime for fixed-size block layout + * + * Call this only for fixed-size blocks + */ + inline void setBlockSize(Index blockSize) + { + m_blockSize = blockSize; + } + + /** + * \brief Set the row and column block layouts, + * + * This function set the size of each row and column block. + * So this function should be used only for blocks with variable size. + * \param rowBlocks : Number of rows per row block + * \param colBlocks : Number of columns per column block + * \sa resize(), setBlockSize() + */ + inline void setBlockLayout(const VectorXi& rowBlocks, const VectorXi& colBlocks) + { + const VectorXi& innerBlocks = IsColMajor ? rowBlocks : colBlocks; + const VectorXi& outerBlocks = IsColMajor ? colBlocks : rowBlocks; + eigen_assert(m_innerBSize == innerBlocks.size() && "CHECK THE NUMBER OF ROW OR COLUMN BLOCKS"); + eigen_assert(m_outerBSize == outerBlocks.size() && "CHECK THE NUMBER OF ROW OR COLUMN BLOCKS"); + m_outerBSize = outerBlocks.size(); + // starting index of blocks... cumulative sums + m_innerOffset = new StorageIndex[m_innerBSize+1]; + m_outerOffset = new StorageIndex[m_outerBSize+1]; + m_innerOffset[0] = 0; + m_outerOffset[0] = 0; + std::partial_sum(&innerBlocks[0], &innerBlocks[m_innerBSize-1]+1, &m_innerOffset[1]); + std::partial_sum(&outerBlocks[0], &outerBlocks[m_outerBSize-1]+1, &m_outerOffset[1]); + + // Compute the total number of nonzeros + m_nonzeros = 0; + for(StorageIndex bj = 0; bj < m_outerBSize; ++bj) + for(StorageIndex bi = 0; bi < m_innerBSize; ++bi) + m_nonzeros += outerBlocks[bj] * innerBlocks[bi]; + + } + + /** + * \brief Allocate the internal array of pointers to blocks and their inner indices + * + * \note For fixed-size blocks, call setBlockSize() to set the block. + * And For variable-size blocks, call setBlockLayout() before using this function + * + * \param nonzerosblocks Number of nonzero blocks. The total number of nonzeros is + * is computed in setBlockLayout() for variable-size blocks + * \sa setBlockSize() + */ + inline void reserve(const Index nonzerosblocks) + { + eigen_assert((m_innerBSize != 0 && m_outerBSize != 0) && + "TRYING TO RESERVE ZERO-SIZE MATRICES, CALL resize() first"); + + //FIXME Should free if already allocated + m_outerIndex = new StorageIndex[m_outerBSize+1]; + + m_nonzerosblocks = nonzerosblocks; + if(m_blockSize != Dynamic) + { + m_nonzeros = nonzerosblocks * (m_blockSize * m_blockSize); + m_blockPtr = 0; + } + else + { + // m_nonzeros is already computed in setBlockLayout() + m_blockPtr = new StorageIndex[m_nonzerosblocks+1]; + } + m_indices = new StorageIndex[m_nonzerosblocks+1]; + m_values = new Scalar[m_nonzeros]; + } + + + /** + * \brief Fill values in a matrix from a triplet list. + * + * Each triplet item has a block stored in an Eigen dense matrix. + * The InputIterator class should provide the functions row(), col() and value() + * + * \note For fixed-size blocks, call setBlockSize() before this function. + * + * FIXME Do not accept duplicates + */ + template + void setFromTriplets(const InputIterator& begin, const InputIterator& end) + { + eigen_assert((m_innerBSize!=0 && m_outerBSize !=0) && "ZERO BLOCKS, PLEASE CALL resize() before"); + + /* First, sort the triplet list + * FIXME This can be unnecessarily expensive since only the inner indices have to be sorted + * The best approach is like in SparseMatrix::setFromTriplets() + */ + internal::TripletComp tripletcomp; + std::sort(begin, end, tripletcomp); + + /* Count the number of rows and column blocks, + * and the number of nonzero blocks per outer dimension + */ + VectorXi rowBlocks(m_innerBSize); // Size of each block row + VectorXi colBlocks(m_outerBSize); // Size of each block column + rowBlocks.setZero(); colBlocks.setZero(); + VectorXi nzblock_outer(m_outerBSize); // Number of nz blocks per outer vector + VectorXi nz_outer(m_outerBSize); // Number of nz per outer vector...for variable-size blocks + nzblock_outer.setZero(); + nz_outer.setZero(); + for(InputIterator it(begin); it !=end; ++it) + { + eigen_assert(it->row() >= 0 && it->row() < this->blockRows() && it->col() >= 0 && it->col() < this->blockCols()); + eigen_assert((it->value().rows() == it->value().cols() && (it->value().rows() == m_blockSize)) + || (m_blockSize == Dynamic)); + + if(m_blockSize == Dynamic) + { + eigen_assert((rowBlocks[it->row()] == 0 || rowBlocks[it->row()] == it->value().rows()) && + "NON CORRESPONDING SIZES FOR ROW BLOCKS"); + eigen_assert((colBlocks[it->col()] == 0 || colBlocks[it->col()] == it->value().cols()) && + "NON CORRESPONDING SIZES FOR COLUMN BLOCKS"); + rowBlocks[it->row()] =it->value().rows(); + colBlocks[it->col()] = it->value().cols(); + } + nz_outer(IsColMajor ? it->col() : it->row()) += it->value().rows() * it->value().cols(); + nzblock_outer(IsColMajor ? it->col() : it->row())++; + } + // Allocate member arrays + if(m_blockSize == Dynamic) setBlockLayout(rowBlocks, colBlocks); + StorageIndex nzblocks = nzblock_outer.sum(); + reserve(nzblocks); + + // Temporary markers + VectorXi block_id(m_outerBSize); // To be used as a block marker during insertion + + // Setup outer index pointers and markers + m_outerIndex[0] = 0; + if (m_blockSize == Dynamic) m_blockPtr[0] = 0; + for(StorageIndex bj = 0; bj < m_outerBSize; ++bj) + { + m_outerIndex[bj+1] = m_outerIndex[bj] + nzblock_outer(bj); + block_id(bj) = m_outerIndex[bj]; + if(m_blockSize==Dynamic) + { + m_blockPtr[m_outerIndex[bj+1]] = m_blockPtr[m_outerIndex[bj]] + nz_outer(bj); + } + } + + // Fill the matrix + for(InputIterator it(begin); it!=end; ++it) + { + StorageIndex outer = IsColMajor ? it->col() : it->row(); + StorageIndex inner = IsColMajor ? it->row() : it->col(); + m_indices[block_id(outer)] = inner; + StorageIndex block_size = it->value().rows()*it->value().cols(); + StorageIndex nz_marker = blockPtr(block_id[outer]); + memcpy(&(m_values[nz_marker]), it->value().data(), block_size * sizeof(Scalar)); + if(m_blockSize == Dynamic) + { + m_blockPtr[block_id(outer)+1] = m_blockPtr[block_id(outer)] + block_size; + } + block_id(outer)++; + } + + // An alternative when the outer indices are sorted...no need to use an array of markers +// for(Index bcol = 0; bcol < m_outerBSize; ++bcol) +// { +// Index id = 0, id_nz = 0, id_nzblock = 0; +// for(InputIterator it(begin); it!=end; ++it) +// { +// while (idvalue().rows()*it->value().cols(); +// m_blockPtr[id_nzblock+1] = m_blockPtr[id_nzblock] + block_size; +// id_nzblock++; +// memcpy(&(m_values[id_nz]),it->value().data(), block_size*sizeof(Scalar)); +// id_nz += block_size; +// } +// while(id < m_outerBSize-1) // Empty columns at the end +// { +// id++; +// m_outerIndex[id+1]=m_outerIndex[id]; +// } +// } + } + + + /** + * \returns the number of rows + */ + inline Index rows() const + { +// return blockRows(); + return (IsColMajor ? innerSize() : outerSize()); + } + + /** + * \returns the number of cols + */ + inline Index cols() const + { +// return blockCols(); + return (IsColMajor ? outerSize() : innerSize()); + } + + inline Index innerSize() const + { + if(m_blockSize == Dynamic) return m_innerOffset[m_innerBSize]; + else return (m_innerBSize * m_blockSize) ; + } + + inline Index outerSize() const + { + if(m_blockSize == Dynamic) return m_outerOffset[m_outerBSize]; + else return (m_outerBSize * m_blockSize) ; + } + /** \returns the number of rows grouped by blocks */ + inline Index blockRows() const + { + return (IsColMajor ? m_innerBSize : m_outerBSize); + } + /** \returns the number of columns grouped by blocks */ + inline Index blockCols() const + { + return (IsColMajor ? m_outerBSize : m_innerBSize); + } + + inline Index outerBlocks() const { return m_outerBSize; } + inline Index innerBlocks() const { return m_innerBSize; } + + /** \returns the block index where outer belongs to */ + inline Index outerToBlock(Index outer) const + { + eigen_assert(outer < outerSize() && "OUTER INDEX OUT OF BOUNDS"); + + if(m_blockSize != Dynamic) + return (outer / m_blockSize); // Integer division + + StorageIndex b_outer = 0; + while(m_outerOffset[b_outer] <= outer) ++b_outer; + return b_outer - 1; + } + /** \returns the block index where inner belongs to */ + inline Index innerToBlock(Index inner) const + { + eigen_assert(inner < innerSize() && "OUTER INDEX OUT OF BOUNDS"); + + if(m_blockSize != Dynamic) + return (inner / m_blockSize); // Integer division + + StorageIndex b_inner = 0; + while(m_innerOffset[b_inner] <= inner) ++b_inner; + return b_inner - 1; + } + + /** + *\returns a reference to the (i,j) block as an Eigen Dense Matrix + */ + Ref coeffRef(Index brow, Index bcol) + { + eigen_assert(brow < blockRows() && "BLOCK ROW INDEX OUT OF BOUNDS"); + eigen_assert(bcol < blockCols() && "BLOCK nzblocksFlagCOLUMN OUT OF BOUNDS"); + + StorageIndex rsize = IsColMajor ? blockInnerSize(brow): blockOuterSize(bcol); + StorageIndex csize = IsColMajor ? blockOuterSize(bcol) : blockInnerSize(brow); + StorageIndex inner = IsColMajor ? brow : bcol; + StorageIndex outer = IsColMajor ? bcol : brow; + StorageIndex offset = m_outerIndex[outer]; + while(offset < m_outerIndex[outer+1] && m_indices[offset] != inner) + offset++; + if(m_indices[offset] == inner) + { + return Map(&(m_values[blockPtr(offset)]), rsize, csize); + } + else + { + //FIXME the block does not exist, Insert it !!!!!!!!! + eigen_assert("DYNAMIC INSERTION IS NOT YET SUPPORTED"); + } + } + + /** + * \returns the value of the (i,j) block as an Eigen Dense Matrix + */ + Map coeff(Index brow, Index bcol) const + { + eigen_assert(brow < blockRows() && "BLOCK ROW INDEX OUT OF BOUNDS"); + eigen_assert(bcol < blockCols() && "BLOCK COLUMN OUT OF BOUNDS"); + + StorageIndex rsize = IsColMajor ? blockInnerSize(brow): blockOuterSize(bcol); + StorageIndex csize = IsColMajor ? blockOuterSize(bcol) : blockInnerSize(brow); + StorageIndex inner = IsColMajor ? brow : bcol; + StorageIndex outer = IsColMajor ? bcol : brow; + StorageIndex offset = m_outerIndex[outer]; + while(offset < m_outerIndex[outer+1] && m_indices[offset] != inner) offset++; + if(m_indices[offset] == inner) + { + return Map (&(m_values[blockPtr(offset)]), rsize, csize); + } + else +// return BlockScalar::Zero(rsize, csize); + eigen_assert("NOT YET SUPPORTED"); + } + + // Block Matrix times vector product + template + BlockSparseTimeDenseProduct operator*(const VecType& lhs) const + { + return BlockSparseTimeDenseProduct(*this, lhs); + } + + /** \returns the number of nonzero blocks */ + inline Index nonZerosBlocks() const { return m_nonzerosblocks; } + /** \returns the total number of nonzero elements, including eventual explicit zeros in blocks */ + inline Index nonZeros() const { return m_nonzeros; } + + inline BlockScalarReturnType *valuePtr() {return static_cast(m_values);} +// inline Scalar *valuePtr(){ return m_values; } + inline StorageIndex *innerIndexPtr() {return m_indices; } + inline const StorageIndex *innerIndexPtr() const {return m_indices; } + inline StorageIndex *outerIndexPtr() {return m_outerIndex; } + inline const StorageIndex* outerIndexPtr() const {return m_outerIndex; } + + /** \brief for compatibility purposes with the SparseMatrix class */ + inline bool isCompressed() const {return true;} + /** + * \returns the starting index of the bi row block + */ + inline Index blockRowsIndex(Index bi) const + { + return IsColMajor ? blockInnerIndex(bi) : blockOuterIndex(bi); + } + + /** + * \returns the starting index of the bj col block + */ + inline Index blockColsIndex(Index bj) const + { + return IsColMajor ? blockOuterIndex(bj) : blockInnerIndex(bj); + } + + inline Index blockOuterIndex(Index bj) const + { + return (m_blockSize == Dynamic) ? m_outerOffset[bj] : (bj * m_blockSize); + } + inline Index blockInnerIndex(Index bi) const + { + return (m_blockSize == Dynamic) ? m_innerOffset[bi] : (bi * m_blockSize); + } + + // Not needed ??? + inline Index blockInnerSize(Index bi) const + { + return (m_blockSize == Dynamic) ? (m_innerOffset[bi+1] - m_innerOffset[bi]) : m_blockSize; + } + inline Index blockOuterSize(Index bj) const + { + return (m_blockSize == Dynamic) ? (m_outerOffset[bj+1]- m_outerOffset[bj]) : m_blockSize; + } + + /** + * \brief Browse the matrix by outer index + */ + class InnerIterator; // Browse column by column + + /** + * \brief Browse the matrix by block outer index + */ + class BlockInnerIterator; // Browse block by block + + friend std::ostream & operator << (std::ostream & s, const BlockSparseMatrix& m) + { + for (StorageIndex j = 0; j < m.outerBlocks(); ++j) + { + BlockInnerIterator itb(m, j); + for(; itb; ++itb) + { + s << "("<()); + } + + + protected: +// inline Index blockDynIdx(Index id, internal::true_type) const +// { +// return m_blockPtr[id]; +// } +// inline Index blockDynIdx(Index id, internal::false_type) const +// { +// return id * BlockSize * BlockSize; +// } + + // To be implemented + // Insert a block at a particular location... need to make a room for that + Map insert(Index brow, Index bcol); + + Index m_innerBSize; // Number of block rows + Index m_outerBSize; // Number of block columns + StorageIndex *m_innerOffset; // Starting index of each inner block (size m_innerBSize+1) + StorageIndex *m_outerOffset; // Starting index of each outer block (size m_outerBSize+1) + Index m_nonzerosblocks; // Total nonzeros blocks (lower than m_innerBSize x m_outerBSize) + Index m_nonzeros; // Total nonzeros elements + Scalar *m_values; //Values stored block column after block column (size m_nonzeros) + StorageIndex *m_blockPtr; // Pointer to the beginning of each block in m_values, size m_nonzeroblocks ... null for fixed-size blocks + StorageIndex *m_indices; //Inner block indices, size m_nonzerosblocks ... OK + StorageIndex *m_outerIndex; // Starting pointer of each block column in m_indices (size m_outerBSize)... OK + Index m_blockSize; // Size of a block for fixed-size blocks, otherwise -1 +}; + +template +class BlockSparseMatrix::BlockInnerIterator +{ + public: + + enum{ + Flags = Options_ + }; + + BlockInnerIterator(const BlockSparseMatrix& mat, const Index outer) + : m_mat(mat),m_outer(outer), + m_id(mat.m_outerIndex[outer]), + m_end(mat.m_outerIndex[outer+1]) + { + } + + inline BlockInnerIterator& operator++() {m_id++; return *this; } + + inline const Map value() const + { + return Map(&(m_mat.m_values[m_mat.blockPtr(m_id)]), + rows(),cols()); + } + inline Map valueRef() + { + return Map(&(m_mat.m_values[m_mat.blockPtr(m_id)]), + rows(),cols()); + } + // Block inner index + inline Index index() const {return m_mat.m_indices[m_id]; } + inline Index outer() const { return m_outer; } + // block row index + inline Index row() const {return index(); } + // block column index + inline Index col() const {return outer(); } + // FIXME Number of rows in the current block + inline Index rows() const { return (m_mat.m_blockSize==Dynamic) ? (m_mat.m_innerOffset[index()+1] - m_mat.m_innerOffset[index()]) : m_mat.m_blockSize; } + // Number of columns in the current block ... + inline Index cols() const { return (m_mat.m_blockSize==Dynamic) ? (m_mat.m_outerOffset[m_outer+1]-m_mat.m_outerOffset[m_outer]) : m_mat.m_blockSize;} + inline operator bool() const { return (m_id < m_end); } + + protected: + const BlockSparseMatrix& m_mat; + const Index m_outer; + Index m_id; + Index m_end; +}; + +template +class BlockSparseMatrix::InnerIterator +{ + public: + InnerIterator(const BlockSparseMatrix& mat, Index outer) + : m_mat(mat),m_outerB(mat.outerToBlock(outer)),m_outer(outer), + itb(mat, mat.outerToBlock(outer)), + m_offset(outer - mat.blockOuterIndex(m_outerB)) + { + if (itb) + { + m_id = m_mat.blockInnerIndex(itb.index()); + m_start = m_id; + m_end = m_mat.blockInnerIndex(itb.index()+1); + } + } + inline InnerIterator& operator++() + { + m_id++; + if (m_id >= m_end) + { + ++itb; + if (itb) + { + m_id = m_mat.blockInnerIndex(itb.index()); + m_start = m_id; + m_end = m_mat.blockInnerIndex(itb.index()+1); + } + } + return *this; + } + inline const Scalar& value() const + { + return itb.value().coeff(m_id - m_start, m_offset); + } + inline Scalar& valueRef() + { + return itb.valueRef().coeff(m_id - m_start, m_offset); + } + inline Index index() const { return m_id; } + inline Index outer() const {return m_outer; } + inline Index col() const {return outer(); } + inline Index row() const { return index();} + inline operator bool() const + { + return itb; + } + protected: + const BlockSparseMatrix& m_mat; + const Index m_outer; + const Index m_outerB; + BlockInnerIterator itb; // Iterator through the blocks + const Index m_offset; // Position of this column in the block + Index m_start; // starting inner index of this block + Index m_id; // current inner index in the block + Index m_end; // starting inner index of the next block + +}; +} // end namespace Eigen + +#endif // EIGEN_SPARSEBLOCKMATRIX_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..0e55251b9cd371917f0518f549c0c407a05cdec0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_SPARSE_EXTRA_MODULE_H +#error "Please include unsupported/Eigen/SparseExtra instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MarketIO.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MarketIO.h new file mode 100644 index 0000000000000000000000000000000000000000..5c261333309c1908c8b0ef451c17b20cd9166616 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MarketIO.h @@ -0,0 +1,385 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Gael Guennebaud +// Copyright (C) 2012 Desire NUENTSA WAKAM +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_MARKET_IO_H +#define EIGEN_SPARSE_MARKET_IO_H + +#include +#include + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal +{ + template + inline void GetMarketLine (const char* line, StorageIndex& i, StorageIndex& j, Scalar& value) + { + std::stringstream sline(line); + sline >> i >> j >> value; + } + + template<> inline void GetMarketLine (const char* line, int& i, int& j, float& value) + { std::sscanf(line, "%d %d %g", &i, &j, &value); } + + template<> inline void GetMarketLine (const char* line, int& i, int& j, double& value) + { std::sscanf(line, "%d %d %lg", &i, &j, &value); } + + template<> inline void GetMarketLine (const char* line, int& i, int& j, std::complex& value) + { std::sscanf(line, "%d %d %g %g", &i, &j, &numext::real_ref(value), &numext::imag_ref(value)); } + + template<> inline void GetMarketLine (const char* line, int& i, int& j, std::complex& value) + { std::sscanf(line, "%d %d %lg %lg", &i, &j, &numext::real_ref(value), &numext::imag_ref(value)); } + + template + inline void GetMarketLine (const char* line, StorageIndex& i, StorageIndex& j, std::complex& value) + { + std::stringstream sline(line); + Scalar valR, valI; + sline >> i >> j >> valR >> valI; + value = std::complex(valR,valI); + } + + template + inline void GetDenseElt (const std::string& line, RealScalar& val) + { + std::istringstream newline(line); + newline >> val; + } + + template + inline void GetDenseElt (const std::string& line, std::complex& val) + { + RealScalar valR, valI; + std::istringstream newline(line); + newline >> valR >> valI; + val = std::complex(valR, valI); + } + + template + inline void putMarketHeader(std::string& header,int sym) + { + header= "%%MatrixMarket matrix coordinate "; + if(internal::is_same >::value || internal::is_same >::value) + { + header += " complex"; + if(sym == Symmetric) header += " symmetric"; + else if (sym == SelfAdjoint) header += " Hermitian"; + else header += " general"; + } + else + { + header += " real"; + if(sym == Symmetric) header += " symmetric"; + else header += " general"; + } + } + + template + inline void PutMatrixElt(Scalar value, StorageIndex row, StorageIndex col, std::ofstream& out) + { + out << row << " "<< col << " " << value << "\n"; + } + template + inline void PutMatrixElt(std::complex value, StorageIndex row, StorageIndex col, std::ofstream& out) + { + out << row << " " << col << " " << value.real() << " " << value.imag() << "\n"; + } + + + template + inline void putDenseElt(Scalar value, std::ofstream& out) + { + out << value << "\n"; + } + template + inline void putDenseElt(std::complex value, std::ofstream& out) + { + out << value.real() << " " << value.imag()<< "\n"; + } + +} // end namespace internal + + +/** + * \ingroup SparseExtra_Module + * @brief Reads the header of a matrixmarket file and determines the properties of a matrix + * + * @param filename of the file + * @param sym if the matrix is hermitian,symmetric or none of the latter (sym=0) + * @param iscomplex if the matrix has complex or real coefficients + * @param isdense if the matrix is dense or sparse + * @return true if the file was found + */ +inline bool getMarketHeader(const std::string& filename, int& sym, bool& iscomplex, bool& isdense) +{ + sym = 0; + iscomplex = false; + isdense = false; + std::ifstream in(filename.c_str(),std::ios::in); + if(!in) + return false; + + std::string line; + // The matrix header is always the first line in the file + std::getline(in, line); eigen_assert(in.good()); + + std::stringstream fmtline(line); + std::string substr[5]; + fmtline>> substr[0] >> substr[1] >> substr[2] >> substr[3] >> substr[4]; + if(substr[2].compare("array") == 0) isdense = true; + if(substr[3].compare("complex") == 0) iscomplex = true; + if(substr[4].compare("symmetric") == 0) sym = Symmetric; + else if (substr[4].compare("Hermitian") == 0) sym = SelfAdjoint; + + return true; +} +/** + * \ingroup SparseExtra_Module + * @brief Loads a sparse matrix from a matrixmarket format file. + * + * @tparam SparseMatrixType to read into, symmetries are not supported + * @param mat SparseMatrix to read into, current values are overwritten + * @param filename to parse matrix from + * @return returns true if file exists. Returns false if the parsing did not succeed. + */ +template +bool loadMarket(SparseMatrixType& mat, const std::string& filename) +{ + typedef typename SparseMatrixType::Scalar Scalar; + typedef typename SparseMatrixType::StorageIndex StorageIndex; + std::ifstream input(filename.c_str(),std::ios::in); + if(!input) + return false; + + char rdbuffer[4096]; + input.rdbuf()->pubsetbuf(rdbuffer, 4096); + + const int maxBuffersize = 2048; + char buffer[maxBuffersize]; + + bool readsizes = false; + + typedef Triplet T; + std::vector elements; + + Index M(-1), N(-1), NNZ(-1); + Index count = 0; + while(input.getline(buffer, maxBuffersize)) + { + // skip comments + //NOTE An appropriate test should be done on the header to get the symmetry + if(buffer[0]=='%') + continue; + + if(!readsizes) + { + std::stringstream line(buffer); + line >> M >> N >> NNZ; + if(M > 0 && N > 0) + { + readsizes = true; + mat.resize(M,N); + mat.reserve(NNZ); + elements.reserve(NNZ); + } + } + else + { + StorageIndex i(-1), j(-1); + Scalar value; + internal::GetMarketLine(buffer, i, j, value); + + i--; + j--; + if(i>=0 && j>=0 && i +bool loadMarketDense(DenseType& mat, const std::string& filename) +{ + typedef typename DenseType::Scalar Scalar; + std::ifstream in(filename.c_str(), std::ios::in); + if(!in) + return false; + + std::string line; + Index rows(0), cols(0); + do + { // Skip comments + std::getline(in, line); eigen_assert(in.good()); + } while (line[0] == '%'); + std::istringstream newline(line); + newline >> rows >> cols; + + bool sizes_not_positive=(rows<1 || cols<1); + bool wrong_input_rows = (DenseType::MaxRowsAtCompileTime != Dynamic && rows > DenseType::MaxRowsAtCompileTime) || + (DenseType::RowsAtCompileTime!=Dynamic && rows!=DenseType::RowsAtCompileTime); + bool wrong_input_cols = (DenseType::MaxColsAtCompileTime != Dynamic && cols > DenseType::MaxColsAtCompileTime) || + (DenseType::ColsAtCompileTime!=Dynamic && cols!=DenseType::ColsAtCompileTime); + + if(sizes_not_positive || wrong_input_rows || wrong_input_cols){ + if(sizes_not_positive){ + std::cerr<< "non-positive row or column size in file" << filename << "\n"; + }else{ + std::cerr<< "Input matrix can not be resized to"< +bool loadMarketVector(VectorType& vec, const std::string& filename) +{ + return loadMarketDense(vec, filename); +} + +/** + * \ingroup SparseExtra_Module + * @brief writes a sparse Matrix to a marketmarket format file + * + * @tparam SparseMatrixType to write to file + * @param mat matrix to write to file + * @param filename filename to write to + * @param sym at the moment no symmetry operations are supported + * @return true if writing succeeded + */ +template +bool saveMarket(const SparseMatrixType& mat, const std::string& filename, int sym = 0) +{ + typedef typename SparseMatrixType::Scalar Scalar; + typedef typename SparseMatrixType::RealScalar RealScalar; + std::ofstream out(filename.c_str(),std::ios::out); + if(!out) + return false; + + out.flags(std::ios_base::scientific); + out.precision(std::numeric_limits::digits10 + 2); + std::string header; + internal::putMarketHeader(header, sym); + out << header << std::endl; + out << mat.rows() << " " << mat.cols() << " " << mat.nonZeros() << "\n"; + int count = 0; + for(int j=0; j +bool saveMarketDense (const DenseType& mat, const std::string& filename) +{ + typedef typename DenseType::Scalar Scalar; + typedef typename DenseType::RealScalar RealScalar; + std::ofstream out(filename.c_str(),std::ios::out); + if(!out) + return false; + + out.flags(std::ios_base::scientific); + out.precision(std::numeric_limits::digits10 + 2); + if(internal::is_same >::value || internal::is_same >::value) + out << "%%MatrixMarket matrix array complex general\n"; + else + out << "%%MatrixMarket matrix array real general\n"; + out << mat.rows() << " "<< mat.cols() << "\n"; + for (Index i=0; i < mat.cols(); i++){ + for (Index j=0; j < mat.rows(); j++){ + internal::putDenseElt(mat(j,i), out); + } + } + out.close(); + return true; +} + +/** + * \ingroup SparseExtra_Module + * @brief Same functionality as saveMarketDense, deprecated + */ +template +bool saveMarketVector (const VectorType& vec, const std::string& filename) +{ + return saveMarketDense(vec, filename); +} + +} // end namespace Eigen + +#endif // EIGEN_SPARSE_MARKET_IO_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h new file mode 100644 index 0000000000000000000000000000000000000000..12e4cb4c86660be87844a6dcac7b7f2dcd688387 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h @@ -0,0 +1,249 @@ + +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Desire NUENTSA WAKAM +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BROWSE_MATRICES_H +#define EIGEN_BROWSE_MATRICES_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +enum { + SPD = 0x100, + NonSymmetric = 0x0 +}; + +/** + * @brief Iterator to browse matrices from a specified folder + * + * This is used to load all the matrices from a folder. + * The matrices should be in Matrix Market format + * It is assumed that the matrices are named as matname.mtx + * and matname_SPD.mtx if the matrix is Symmetric and positive definite (or Hermitian) + * The right hand side vectors are loaded as well, if they exist. + * They should be named as matname_b.mtx. + * Note that the right hand side for a SPD matrix is named as matname_SPD_b.mtx + * + * Sometimes a reference solution is available. In this case, it should be named as matname_x.mtx + * + * Sample code + * \code + * + * \endcode + * + * \tparam Scalar The scalar type + */ +template +class MatrixMarketIterator +{ + typedef typename NumTraits::Real RealScalar; + public: + typedef Matrix VectorType; + typedef SparseMatrix MatrixType; + + public: + MatrixMarketIterator(const std::string &folder) + : m_sym(0), m_isvalid(false), m_matIsLoaded(false), m_hasRhs(false), m_hasrefX(false), m_folder(folder) + { + m_folder_id = opendir(folder.c_str()); + if(m_folder_id) + Getnextvalidmatrix(); + } + + ~MatrixMarketIterator() + { + if (m_folder_id) closedir(m_folder_id); + } + + inline MatrixMarketIterator& operator++() + { + m_matIsLoaded = false; + m_hasrefX = false; + m_hasRhs = false; + Getnextvalidmatrix(); + return *this; + } + inline operator bool() const { return m_isvalid;} + + /** Return the sparse matrix corresponding to the current file */ + inline MatrixType& matrix() + { + // Read the matrix + if (m_matIsLoaded) return m_mat; + + std::string matrix_file = m_folder + "/" + m_matname + ".mtx"; + if ( !loadMarket(m_mat, matrix_file)) + { + std::cerr << "Warning loadMarket failed when loading \"" << matrix_file << "\"" << std::endl; + m_matIsLoaded = false; + return m_mat; + } + m_matIsLoaded = true; + + if (m_sym != NonSymmetric) + { + // Check whether we need to restore a full matrix: + RealScalar diag_norm = m_mat.diagonal().norm(); + RealScalar lower_norm = m_mat.template triangularView().norm(); + RealScalar upper_norm = m_mat.template triangularView().norm(); + if(lower_norm>diag_norm && upper_norm==diag_norm) + { + // only the lower part is stored + MatrixType tmp(m_mat); + m_mat = tmp.template selfadjointView(); + } + else if(upper_norm>diag_norm && lower_norm==diag_norm) + { + // only the upper part is stored + MatrixType tmp(m_mat); + m_mat = tmp.template selfadjointView(); + } + } + return m_mat; + } + + /** Return the right hand side corresponding to the current matrix. + * If the rhs file is not provided, a random rhs is generated + */ + inline VectorType& rhs() + { + // Get the right hand side + if (m_hasRhs) return m_rhs; + + std::string rhs_file; + rhs_file = m_folder + "/" + m_matname + "_b.mtx"; // The pattern is matname_b.mtx + m_hasRhs = Fileexists(rhs_file); + if (m_hasRhs) + { + m_rhs.resize(m_mat.cols()); + m_hasRhs = loadMarketVector(m_rhs, rhs_file); + } + if (!m_hasRhs) + { + // Generate a random right hand side + if (!m_matIsLoaded) this->matrix(); + m_refX.resize(m_mat.cols()); + m_refX.setRandom(); + m_rhs = m_mat * m_refX; + m_hasrefX = true; + m_hasRhs = true; + } + return m_rhs; + } + + /** Return a reference solution + * If it is not provided and if the right hand side is not available + * then refX is randomly generated such that A*refX = b + * where A and b are the matrix and the rhs. + * Note that when a rhs is provided, refX is not available + */ + inline VectorType& refX() + { + // Check if a reference solution is provided + if (m_hasrefX) return m_refX; + + std::string lhs_file; + lhs_file = m_folder + "/" + m_matname + "_x.mtx"; + m_hasrefX = Fileexists(lhs_file); + if (m_hasrefX) + { + m_refX.resize(m_mat.cols()); + m_hasrefX = loadMarketVector(m_refX, lhs_file); + } + else + m_refX.resize(0); + return m_refX; + } + + inline std::string& matname() { return m_matname; } + + inline int sym() { return m_sym; } + + bool hasRhs() {return m_hasRhs; } + bool hasrefX() {return m_hasrefX; } + bool isFolderValid() { return bool(m_folder_id); } + + protected: + + inline bool Fileexists(std::string file) + { + std::ifstream file_id(file.c_str()); + if (!file_id.good() ) + { + return false; + } + else + { + file_id.close(); + return true; + } + } + + void Getnextvalidmatrix( ) + { + m_isvalid = false; + // Here, we return with the next valid matrix in the folder + while ( (m_curs_id = readdir(m_folder_id)) != NULL) { + m_isvalid = false; + std::string curfile; + curfile = m_folder + "/" + m_curs_id->d_name; + // Discard if it is a folder + if (m_curs_id->d_type == DT_DIR) continue; //FIXME This may not be available on non BSD systems +// struct stat st_buf; +// stat (curfile.c_str(), &st_buf); +// if (S_ISDIR(st_buf.st_mode)) continue; + + // Determine from the header if it is a matrix or a right hand side + bool isvector,iscomplex=false; + if(!getMarketHeader(curfile,m_sym,iscomplex,isvector)) continue; + if(isvector) continue; + if (!iscomplex) + { + if(internal::is_same >::value || internal::is_same >::value) + continue; + } + if (iscomplex) + { + if(internal::is_same::value || internal::is_same::value) + continue; + } + + + // Get the matrix name + std::string filename = m_curs_id->d_name; + m_matname = filename.substr(0, filename.length()-4); + + // Find if the matrix is SPD + size_t found = m_matname.find("SPD"); + if( (found!=std::string::npos) && (m_sym != NonSymmetric) ) + m_sym = SPD; + + m_isvalid = true; + break; + } + } + int m_sym; // Symmetry of the matrix + MatrixType m_mat; // Current matrix + VectorType m_rhs; // Current vector + VectorType m_refX; // The reference solution, if exists + std::string m_matname; // Matrix Name + bool m_isvalid; + bool m_matIsLoaded; // Determine if the matrix has already been loaded from the file + bool m_hasRhs; // The right hand side exists + bool m_hasrefX; // A reference solution is provided + std::string m_folder; + DIR * m_folder_id; + struct dirent *m_curs_id; + +}; + +} // end namespace Eigen + +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/RandomSetter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/RandomSetter.h new file mode 100644 index 0000000000000000000000000000000000000000..9476ee3fbcbe7f3f7643d8852263e0bdcaa90d6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/RandomSetter.h @@ -0,0 +1,335 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_RANDOMSETTER_H +#define EIGEN_RANDOMSETTER_H + +#if defined(EIGEN_GOOGLEHASH_SUPPORT) +// Ensure the ::google namespace exists, required for checking existence of +// ::google::dense_hash_map and ::google::sparse_hash_map. +namespace google {} +#endif + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** Represents a std::map + * + * \see RandomSetter + */ +template struct StdMapTraits +{ + typedef int KeyType; + typedef std::map Type; + enum { + IsSorted = 1 + }; + + static void setInvalidKey(Type&, const KeyType&) {} +}; + + +/** Represents a std::unordered_map + * \see RandomSetter + */ +template struct StdUnorderedMapTraits +{ + typedef int KeyType; + typedef std::unordered_map Type; + enum { + IsSorted = 0 + }; + + static void setInvalidKey(Type&, const KeyType&) {} +}; + +#if defined(EIGEN_GOOGLEHASH_SUPPORT) + +namespace google { + +// Namespace work-around, since sometimes dense_hash_map and sparse_hash_map +// are in the global namespace, and other times they are under ::google. +using namespace ::google; + +template +struct DenseHashMap { + typedef dense_hash_map type; +}; + +template +struct SparseHashMap { + typedef sparse_hash_map type; +}; + +} // namespace google + +/** Represents a google::dense_hash_map + * + * \see RandomSetter + */ +template struct GoogleDenseHashMapTraits +{ + typedef int KeyType; + typedef typename google::DenseHashMap::type Type; + enum { + IsSorted = 0 + }; + + static void setInvalidKey(Type& map, const KeyType& k) + { map.set_empty_key(k); } +}; + +/** Represents a google::sparse_hash_map + * + * \see RandomSetter + */ +template struct GoogleSparseHashMapTraits +{ + typedef int KeyType; + typedef typename google::SparseHashMap::type Type; + enum { + IsSorted = 0 + }; + + static void setInvalidKey(Type&, const KeyType&) {} +}; +#endif + +/** \class RandomSetter + * \ingroup SparseExtra_Module + * \brief The RandomSetter is a wrapper object allowing to set/update a sparse matrix with random access + * + * \tparam SparseMatrixType the type of the sparse matrix we are updating + * \tparam MapTraits a traits class representing the map implementation used for the temporary sparse storage. + * Its default value depends on the system. + * \tparam OuterPacketBits defines the number of rows (or columns) manage by a single map object + * as a power of two exponent. + * + * This class temporarily represents a sparse matrix object using a generic map implementation allowing for + * efficient random access. The conversion from the compressed representation to a hash_map object is performed + * in the RandomSetter constructor, while the sparse matrix is updated back at destruction time. This strategy + * suggest the use of nested blocks as in this example: + * + * \code + * SparseMatrix m(rows,cols); + * { + * RandomSetter > w(m); + * // don't use m but w instead with read/write random access to the coefficients: + * for(;;) + * w(rand(),rand()) = rand; + * } + * // when w is deleted, the data are copied back to m + * // and m is ready to use. + * \endcode + * + * Since hash_map objects are not fully sorted, representing a full matrix as a single hash_map would + * involve a big and costly sort to update the compressed matrix back. To overcome this issue, a RandomSetter + * use multiple hash_map, each representing 2^OuterPacketBits columns or rows according to the storage order. + * To reach optimal performance, this value should be adjusted according to the average number of nonzeros + * per rows/columns. + * + * The possible values for the template parameter MapTraits are: + * - \b StdMapTraits: corresponds to std::map. (does not perform very well) + * - \b StdUnorderedMapTraits: corresponds to std::unordered_map + * - \b GoogleDenseHashMapTraits: corresponds to google::dense_hash_map (best efficiency, reasonable memory consumption) + * - \b GoogleSparseHashMapTraits: corresponds to google::sparse_hash_map (best memory consumption, relatively good performance) + * + * The default map implementation depends on the availability, and the preferred order is: + * GoogleSparseHashMapTraits, StdUnorderedMapTraits, and finally StdMapTraits. + * + * For performance and memory consumption reasons it is highly recommended to use one of + * Google's hash_map implementations. To enable the support for them, you must define + * EIGEN_GOOGLEHASH_SUPPORT. This will include both and + * for you. + * + * \see https://github.com/sparsehash/sparsehash + */ +template class MapTraits = +#if defined(EIGEN_GOOGLEHASH_SUPPORT) + GoogleDenseHashMapTraits +#else + StdUnorderedMapTraits +#endif + ,int OuterPacketBits = 6> +class RandomSetter +{ + typedef typename SparseMatrixType::Scalar Scalar; + typedef typename SparseMatrixType::StorageIndex StorageIndex; + + struct ScalarWrapper + { + ScalarWrapper() : value(0) {} + Scalar value; + }; + typedef typename MapTraits::KeyType KeyType; + typedef typename MapTraits::Type HashMapType; + static constexpr int OuterPacketMask = (1 << OuterPacketBits) - 1; + enum { + SwapStorage = 1 - MapTraits::IsSorted, + TargetRowMajor = (SparseMatrixType::Flags & RowMajorBit) ? 1 : 0, + SetterRowMajor = SwapStorage ? 1-TargetRowMajor : TargetRowMajor + }; + + public: + + /** Constructs a random setter object from the sparse matrix \a target + * + * Note that the initial value of \a target are imported. If you want to re-set + * a sparse matrix from scratch, then you must set it to zero first using the + * setZero() function. + */ + inline RandomSetter(SparseMatrixType& target) + : mp_target(&target) + { + const Index outerSize = SwapStorage ? target.innerSize() : target.outerSize(); + const Index innerSize = SwapStorage ? target.outerSize() : target.innerSize(); + m_outerPackets = outerSize >> OuterPacketBits; + if (outerSize&OuterPacketMask) + m_outerPackets += 1; + m_hashmaps = new HashMapType[m_outerPackets]; + // compute number of bits needed to store inner indices + Index aux = innerSize - 1; + m_keyBitsOffset = 0; + while (aux) + { + ++m_keyBitsOffset; + aux = aux >> 1; + } + KeyType ik = (1<<(OuterPacketBits+m_keyBitsOffset)); + for (Index k=0; k::setInvalidKey(m_hashmaps[k],ik); + + // insert current coeffs + for (Index j=0; jouterSize(); ++j) + for (typename SparseMatrixType::InnerIterator it(*mp_target,j); it; ++it) + (*this)(TargetRowMajor?j:it.index(), TargetRowMajor?it.index():j) = it.value(); + } + + /** Destructor updating back the sparse matrix target */ + ~RandomSetter() + { + KeyType keyBitsMask = (1<setZero(); + mp_target->makeCompressed(); + mp_target->reserve(nonZeros()); + Index prevOuter = -1; + for (Index k=0; kfirst >> m_keyBitsOffset) + outerOffset; + const Index inner = it->first & keyBitsMask; + if (prevOuter!=outer) + { + for (Index j=prevOuter+1;j<=outer;++j) + mp_target->startVec(j); + prevOuter = outer; + } + mp_target->insertBackByOuterInner(outer, inner) = it->second.value; + } + } + mp_target->finalize(); + } + else + { + VectorXi positions(mp_target->outerSize()); + positions.setZero(); + // pass 1 + for (Index k=0; kfirst & keyBitsMask; + ++positions[outer]; + } + } + // prefix sum + StorageIndex count = 0; + for (Index j=0; jouterSize(); ++j) + { + StorageIndex tmp = positions[j]; + mp_target->outerIndexPtr()[j] = count; + positions[j] = count; + count += tmp; + } + mp_target->makeCompressed(); + mp_target->outerIndexPtr()[mp_target->outerSize()] = count; + mp_target->resizeNonZeros(count); + // pass 2 + for (Index k=0; kfirst >> m_keyBitsOffset) + outerOffset; + const Index outer = it->first & keyBitsMask; + // sorted insertion + // Note that we have to deal with at most 2^OuterPacketBits unsorted coefficients, + // moreover those 2^OuterPacketBits coeffs are likely to be sparse, an so only a + // small fraction of them have to be sorted, whence the following simple procedure: + Index posStart = mp_target->outerIndexPtr()[outer]; + Index i = (positions[outer]++) - 1; + while ( (i >= posStart) && (mp_target->innerIndexPtr()[i] > inner) ) + { + mp_target->valuePtr()[i+1] = mp_target->valuePtr()[i]; + mp_target->innerIndexPtr()[i+1] = mp_target->innerIndexPtr()[i]; + --i; + } + mp_target->innerIndexPtr()[i+1] = internal::convert_index(inner); + mp_target->valuePtr()[i+1] = it->second.value; + } + } + } + delete[] m_hashmaps; + } + + /** \returns a reference to the coefficient at given coordinates \a row, \a col */ + Scalar& operator() (Index row, Index col) + { + const Index outer = SetterRowMajor ? row : col; + const Index inner = SetterRowMajor ? col : row; + const Index outerMajor = outer >> OuterPacketBits; // index of the packet/map + const Index outerMinor = outer & OuterPacketMask; // index of the inner vector in the packet + const KeyType key = internal::convert_index((outerMinor<(m_hashmaps[k].size()); + return nz; + } + + + protected: + + HashMapType* m_hashmaps; + SparseMatrixType* mp_target; + Index m_outerPackets; + unsigned char m_keyBitsOffset; +}; + +} // end namespace Eigen + +#endif // EIGEN_RANDOMSETTER_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/SparseInverse.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/SparseInverse.h new file mode 100644 index 0000000000000000000000000000000000000000..c8a4920ba800cbf5149f5e713fc2c1e4695b3a27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SparseExtra/SparseInverse.h @@ -0,0 +1,231 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2022 Julian Kent +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEINVERSE_H +#define EIGEN_SPARSEINVERSE_H + +#include "./InternalHeaderCheck.h" + +#include "../../../../Eigen/Sparse" +#include "../../../../Eigen/SparseLU" + +namespace Eigen { + +/** + * @brief Kahan algorithm based accumulator + * + * The Kahan sum algorithm guarantees to bound the error from floating point + * accumulation to a fixed value, regardless of the number of accumulations + * performed. Naive accumulation accumulates errors O(N), and pairwise O(logN). + * However pairwise also requires O(logN) memory while Kahan summation requires + * O(1) memory, but 4x the operations / latency. + * + * NB! Do not enable associative math optimizations, they may cause the Kahan + * summation to be optimized out leaving you with naive summation again. + * + */ +template +class KahanSum { + // Straighforward Kahan summation for accurate accumulation of a sum of numbers + Scalar _sum{}; + Scalar _correction{}; + + public: + Scalar value() { return _sum; } + + void operator+=(Scalar increment) { + const Scalar correctedIncrement = increment + _correction; + const Scalar previousSum = _sum; + _sum += correctedIncrement; + _correction = correctedIncrement - (_sum - previousSum); + } +}; +template +class FABSum { + // https://epubs.siam.org/doi/pdf/10.1137/19M1257780 + // Fast and Accurate Blocked Summation + // Uses naive summation for the fast sum, and Kahan summation for the accurate sum + // Theoretically SIMD sum could be changed to a tree sum which would improve accuracy + // over naive summation + KahanSum _totalSum; + Matrix _block; + Index _blockUsed{}; + + public: + Scalar value() { return _block.topRows(_blockUsed).sum() + _totalSum.value(); } + + void operator+=(Scalar increment) { + _block(_blockUsed++, 0) = increment; + if (_blockUsed == Width) { + _totalSum += _block.sum(); + _blockUsed = 0; + } + } +}; + +/** + * @brief computes an accurate dot product on two sparse vectors + * + * Uses an accurate summation algorithm for the accumulator in order to + * compute an accurate dot product for two sparse vectors. + * + */ +template +typename Derived::Scalar accurateDot(const SparseMatrixBase& A, const SparseMatrixBase& other) { + typedef typename Derived::Scalar Scalar; + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) + EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived, OtherDerived) + static_assert(internal::is_same::value, "mismatched types"); + + internal::evaluator thisEval(A.derived()); + typename Derived::ReverseInnerIterator i(thisEval, 0); + + internal::evaluator otherEval(other.derived()); + typename OtherDerived::ReverseInnerIterator j(otherEval, 0); + + FABSum res; + while (i && j) { + if (i.index() == j.index()) { + res += numext::conj(i.value()) * j.value(); + --i; + --j; + } else if (i.index() > j.index()) + --i; + else + --j; + } + return res.value(); +} + +/** + * @brief calculate sparse subset of inverse of sparse matrix + * + * This class returns a sparse subset of the inverse of the input matrix. + * The nonzeros correspond to the nonzeros of the input, plus any additional + * elements required due to fill-in of the internal LU factorization. This is + * is minimized via a applying a fill-reducing permutation as part of the LU + * factorization. + * + * If there are specific entries of the input matrix which you need inverse + * values for, which are zero for the input, you need to insert entries into + * the input sparse matrix for them to be calculated. + * + * Due to the sensitive nature of matrix inversion, particularly on large + * matrices which are made possible via sparsity, high accuracy dot products + * based on Kahan summation are used to reduce numerical error. If you still + * encounter numerical errors you may with to equilibrate your matrix before + * calculating the inverse, as well as making sure it is actually full rank. + */ +template +class SparseInverse { + public: + typedef SparseMatrix MatrixType; + typedef SparseMatrix RowMatrixType; + + SparseInverse() {} + + /** + * @brief This Constructor is for if you already have a factored SparseLU and would like to use it to calculate a + * sparse inverse. + * + * Just call this constructor with your already factored SparseLU class and you can directly call the .inverse() + * method to get the result. + */ + SparseInverse(const SparseLU& slu) { _result = computeInverse(slu); } + + /** + * @brief Calculate the sparse inverse from a given sparse input + */ + SparseInverse& compute(const SparseMatrix& A) { + SparseLU slu; + slu.compute(A); + _result = computeInverse(slu); + return *this; + } + + /** + * @brief return the already-calculated sparse inverse, or a 0x0 matrix if it could not be computed + */ + const MatrixType& inverse() const { return _result; } + + /** + * @brief Internal function to calculate the sparse inverse in a functional way + * @return A sparse inverse representation, or, if the decomposition didn't complete, a 0x0 matrix. + */ + static MatrixType computeInverse(const SparseLU& slu) { + if (slu.info() != Success) { + return MatrixType(0, 0); + } + + // Extract from SparseLU and decompose into L, inverse D and U terms + Matrix invD; + RowMatrixType Upper; + { + RowMatrixType DU = slu.matrixU().toSparse(); + invD = DU.diagonal().cwiseInverse(); + Upper = (invD.asDiagonal() * DU).template triangularView(); + } + MatrixType Lower = slu.matrixL().toSparse().template triangularView(); + + // Compute the inverse and reapply the permutation matrix from the LU decomposition + return slu.colsPermutation().transpose() * computeInverse(Upper, invD, Lower) * slu.rowsPermutation(); + } + + /** + * @brief Internal function to calculate the inverse from strictly upper, diagonal and strictly lower components + */ + static MatrixType computeInverse(const RowMatrixType& Upper, const Matrix& inverseDiagonal, + const MatrixType& Lower) { + // Calculate the 'minimal set', which is the nonzeros of (L+U).transpose() + // It could be zeroed, but we will overwrite all non-zeros anyways. + MatrixType colInv = Lower.transpose().template triangularView(); + colInv += Upper.transpose(); + + // We also need rowmajor representation in order to do efficient row-wise dot products + RowMatrixType rowInv = Upper.transpose().template triangularView(); + rowInv += Lower.transpose(); + + // Use the Takahashi algorithm to build the supporting elements of the inverse + // upwards and to the left, from the bottom right element, 1 col/row at a time + for (Index recurseLevel = Upper.cols() - 1; recurseLevel >= 0; recurseLevel--) { + const auto& col = Lower.col(recurseLevel); + const auto& row = Upper.row(recurseLevel); + + // Calculate the inverse values for the nonzeros in this column + typename MatrixType::ReverseInnerIterator colIter(colInv, recurseLevel); + for (; recurseLevel < colIter.index(); --colIter) { + const Scalar element = -accurateDot(col, rowInv.row(colIter.index())); + colIter.valueRef() = element; + rowInv.coeffRef(colIter.index(), recurseLevel) = element; + } + + // Calculate the inverse values for the nonzeros in this row + typename RowMatrixType::ReverseInnerIterator rowIter(rowInv, recurseLevel); + for (; recurseLevel < rowIter.index(); --rowIter) { + const Scalar element = -accurateDot(row, colInv.col(rowIter.index())); + rowIter.valueRef() = element; + colInv.coeffRef(recurseLevel, rowIter.index()) = element; + } + + // And finally the diagonal, which corresponds to both row and col iterator now + const Scalar diag = inverseDiagonal(recurseLevel) - accurateDot(row, colInv.col(recurseLevel)); + rowIter.valueRef() = diag; + colIter.valueRef() = diag; + } + + return colInv; + } + + private: + MatrixType _result; +}; + +} // namespace Eigen +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsArrayAPI.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsArrayAPI.h new file mode 100644 index 0000000000000000000000000000000000000000..7fa85e2f1a67281ae97e2577e08897ff067b5430 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsArrayAPI.h @@ -0,0 +1,288 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_BESSELFUNCTIONS_ARRAYAPI_H +#define EIGEN_BESSELFUNCTIONS_ARRAYAPI_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \returns an expression of the coefficient-wise i0(\a x) to the given + * arrays. + * + * It returns the modified Bessel function of the first kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of i0(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_i0() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i0_op, const Derived> +bessel_i0(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i0_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise i0e(\a x) to the given + * arrays. + * + * It returns the exponentially scaled modified Bessel + * function of the first kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of i0e(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_i0e() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i0e_op, const Derived> +bessel_i0e(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i0e_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise i1(\a x) to the given + * arrays. + * + * It returns the modified Bessel function of the first kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of i1(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_i1() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i1_op, const Derived> +bessel_i1(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i1_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise i1e(\a x) to the given + * arrays. + * + * It returns the exponentially scaled modified Bessel + * function of the first kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of i1e(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_i1e() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i1e_op, const Derived> +bessel_i1e(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_i1e_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise k0(\a x) to the given + * arrays. + * + * It returns the modified Bessel function of the second kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of k0(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_k0() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k0_op, const Derived> +bessel_k0(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k0_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise k0e(\a x) to the given + * arrays. + * + * It returns the exponentially scaled modified Bessel + * function of the second kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of k0e(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_k0e() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k0e_op, const Derived> +bessel_k0e(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k0e_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise k1(\a x) to the given + * arrays. + * + * It returns the modified Bessel function of the second kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of k1(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_k1() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k1_op, const Derived> +bessel_k1(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k1_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise k1e(\a x) to the given + * arrays. + * + * It returns the exponentially scaled modified Bessel + * function of the second kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of k1e(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_k1e() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k1e_op, const Derived> +bessel_k1e(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_k1e_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise j0(\a x) to the given + * arrays. + * + * It returns the Bessel function of the first kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of j0(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_j0() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_j0_op, const Derived> +bessel_j0(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_j0_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise y0(\a x) to the given + * arrays. + * + * It returns the Bessel function of the second kind of order zero. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of y0(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_y0() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_y0_op, const Derived> +bessel_y0(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_y0_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise j1(\a x) to the given + * arrays. + * + * It returns the modified Bessel function of the first kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of j1(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_j1() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_j1_op, const Derived> +bessel_j1(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_j1_op, + const Derived>(x.derived()); +} + +/** \returns an expression of the coefficient-wise y1(\a x) to the given + * arrays. + * + * It returns the Bessel function of the second kind of order one. + * + * \param x is the argument + * + * \note This function supports only float and double scalar types. To support + * other scalar types, the user has to provide implementations of y1(T) for + * any scalar type T to be supported. + * + * \sa ArrayBase::bessel_y1() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_y1_op, const Derived> +bessel_y1(const Eigen::ArrayBase& x) { + return Eigen::CwiseUnaryOp< + Eigen::internal::scalar_bessel_y1_op, + const Derived>(x.derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_BESSELFUNCTIONS_ARRAYAPI_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsBFloat16.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsBFloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..c016004973a1b05821963f7cedb62b3b40a94285 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsBFloat16.h @@ -0,0 +1,70 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BESSELFUNCTIONS_BFLOAT16_H +#define EIGEN_BESSELFUNCTIONS_BFLOAT16_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace numext { + +#if EIGEN_HAS_C99_MATH +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i0(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_i0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i0e(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_i0e(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i1(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_i1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i1e(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_i1e(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_j0(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_j0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_j1(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_j1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_y0(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_y0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_y1(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_y1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k0(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_k0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k0e(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_k0e(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k1(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_k1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k1e(const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::bessel_k1e(static_cast(x))); +} +#endif + +} // end namespace numext +} // end namespace Eigen + +#endif // EIGEN_BESSELFUNCTIONS_BFLOAT16_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsFunctors.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsFunctors.h new file mode 100644 index 0000000000000000000000000000000000000000..2d6b386ee9c541eeb6fddee544f521e5d9c6bc41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsFunctors.h @@ -0,0 +1,347 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Eugene Brevdo +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BESSELFUNCTIONS_FUNCTORS_H +#define EIGEN_BESSELFUNCTIONS_FUNCTORS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \internal + * \brief Template functor to compute the modified Bessel function of the first + * kind of order zero. + * \sa class CwiseUnaryOp, Cwise::bessel_i0() + */ +template +struct scalar_bessel_i0_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_i0; + return bessel_i0(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_i0(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=20 is computed. + // The cost is N multiplications and 2N additions. We also add + // the cost of an additional exp over i0e. + Cost = 28 * NumTraits::MulCost + 48 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the exponentially scaled modified Bessel + * function of the first kind of order zero + * \sa class CwiseUnaryOp, Cwise::bessel_i0e() + */ +template +struct scalar_bessel_i0e_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_i0e; + return bessel_i0e(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_i0e(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=20 is computed. + // The cost is N multiplications and 2N additions. + Cost = 20 * NumTraits::MulCost + 40 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the modified Bessel function of the first + * kind of order one + * \sa class CwiseUnaryOp, Cwise::bessel_i1() + */ +template +struct scalar_bessel_i1_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_i1; + return bessel_i1(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_i1(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=20 is computed. + // The cost is N multiplications and 2N additions. We also add + // the cost of an additional exp over i1e. + Cost = 28 * NumTraits::MulCost + 48 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the exponentially scaled modified Bessel + * function of the first kind of order zero + * \sa class CwiseUnaryOp, Cwise::bessel_i1e() + */ +template +struct scalar_bessel_i1e_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_i1e; + return bessel_i1e(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_i1e(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=20 is computed. + // The cost is N multiplications and 2N additions. + Cost = 20 * NumTraits::MulCost + 40 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the Bessel function of the second kind of + * order zero + * \sa class CwiseUnaryOp, Cwise::bessel_j0() + */ +template +struct scalar_bessel_j0_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_j0; + return bessel_j0(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_j0(x); + } +}; +template +struct functor_traits > { + enum { + // 6 polynomial of order ~N=8 is computed. + // The cost is N multiplications and N additions each, along with a + // sine, cosine and rsqrt cost. + Cost = 63 * NumTraits::MulCost + 48 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the Bessel function of the second kind of + * order zero + * \sa class CwiseUnaryOp, Cwise::bessel_y0() + */ +template +struct scalar_bessel_y0_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_y0; + return bessel_y0(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_y0(x); + } +}; +template +struct functor_traits > { + enum { + // 6 polynomial of order ~N=8 is computed. + // The cost is N multiplications and N additions each, along with a + // sine, cosine, rsqrt and j0 cost. + Cost = 126 * NumTraits::MulCost + 96 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the Bessel function of the first kind of + * order one + * \sa class CwiseUnaryOp, Cwise::bessel_j1() + */ +template +struct scalar_bessel_j1_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_j1; + return bessel_j1(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_j1(x); + } +}; +template +struct functor_traits > { + enum { + // 6 polynomial of order ~N=8 is computed. + // The cost is N multiplications and N additions each, along with a + // sine, cosine and rsqrt cost. + Cost = 63 * NumTraits::MulCost + 48 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the Bessel function of the second kind of + * order one + * \sa class CwiseUnaryOp, Cwise::bessel_j1e() + */ +template +struct scalar_bessel_y1_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_y1; + return bessel_y1(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_y1(x); + } +}; +template +struct functor_traits > { + enum { + // 6 polynomial of order ~N=8 is computed. + // The cost is N multiplications and N additions each, along with a + // sine, cosine, rsqrt and j1 cost. + Cost = 126 * NumTraits::MulCost + 96 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the modified Bessel function of the second + * kind of order zero + * \sa class CwiseUnaryOp, Cwise::bessel_k0() + */ +template +struct scalar_bessel_k0_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_k0; + return bessel_k0(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_k0(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=10 is computed. + // The cost is N multiplications and 2N additions. In addition we compute + // i0, a log, exp and prsqrt and sin and cos. + Cost = 68 * NumTraits::MulCost + 88 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the exponentially scaled modified Bessel + * function of the second kind of order zero + * \sa class CwiseUnaryOp, Cwise::bessel_k0e() + */ +template +struct scalar_bessel_k0e_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_k0e; + return bessel_k0e(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_k0e(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=10 is computed. + // The cost is N multiplications and 2N additions. In addition we compute + // i0, a log, exp and prsqrt and sin and cos. + Cost = 68 * NumTraits::MulCost + 88 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the modified Bessel function of the + * second kind of order one + * \sa class CwiseUnaryOp, Cwise::bessel_k1() + */ +template +struct scalar_bessel_k1_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_k1; + return bessel_k1(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_k1(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=10 is computed. + // The cost is N multiplications and 2N additions. In addition we compute + // i1, a log, exp and prsqrt and sin and cos. + Cost = 68 * NumTraits::MulCost + 88 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + +/** \internal + * \brief Template functor to compute the exponentially scaled modified Bessel + * function of the second kind of order one + * \sa class CwiseUnaryOp, Cwise::bessel_k1e() + */ +template +struct scalar_bessel_k1e_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const { + using numext::bessel_k1e; + return bessel_k1e(x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return internal::pbessel_k1e(x); + } +}; +template +struct functor_traits > { + enum { + // On average, a Chebyshev polynomial of order N=10 is computed. + // The cost is N multiplications and 2N additions. In addition we compute + // i1, a log, exp and prsqrt and sin and cos. + Cost = 68 * NumTraits::MulCost + 88 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBessel + }; +}; + + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_BESSELFUNCTIONS_FUNCTORS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsHalf.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsHalf.h new file mode 100644 index 0000000000000000000000000000000000000000..4d50503a49b63f638789d32aa7cb49ed1694e94a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsHalf.h @@ -0,0 +1,68 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BESSELFUNCTIONS_HALF_H +#define EIGEN_BESSELFUNCTIONS_HALF_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace numext { + +#if EIGEN_HAS_C99_MATH +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i0(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_i0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i0e(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_i0e(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i1(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_i1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i1e(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_i1e(static_cast(x))); +} +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_j0(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_j0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_j1(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_j1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_y0(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_y0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_y1(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_y1(static_cast(x))); +} +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k0(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_k0(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k0e(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_k0e(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k1(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_k1(static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k1e(const Eigen::half& x) { + return Eigen::half(Eigen::numext::bessel_k1e(static_cast(x))); +} +#endif + +} // end namespace numext +} // end namespace Eigen + +#endif // EIGEN_BESSELFUNCTIONS_HALF_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..b600079e009056a99de161313085becd73c7d7ec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsImpl.h @@ -0,0 +1,1961 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Eugene Brevdo +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BESSEL_FUNCTIONS_H +#define EIGEN_BESSEL_FUNCTIONS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +// Parts of this code are based on the Cephes Math Library. +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier +// +// Permission has been kindly provided by the original author +// to incorporate the Cephes software into the Eigen codebase: +// +// From: Stephen Moshier +// To: Eugene Brevdo +// Subject: Re: Permission to wrap several cephes functions in Eigen +// +// Hello Eugene, +// +// Thank you for writing. +// +// If your licensing is similar to BSD, the formal way that has been +// handled is simply to add a statement to the effect that you are incorporating +// the Cephes software by permission of the author. +// +// Good luck with your project, +// Steve + + +/**************************************************************************** + * Implementation of Bessel function, based on Cephes * + ****************************************************************************/ + +template +struct bessel_i0e_retval { + typedef Scalar type; +}; + +template ::type> +struct generic_i0e { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_i0e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* i0ef.c + * + * Modified Bessel function of order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * float x, y, i0ef(); + * + * y = i0ef( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order zero of the argument. + * + * The function is defined as i0e(x) = exp(-|x|) j0( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 100000 3.7e-7 7.0e-8 + * See i0f(). + * + */ + + const float A[] = {-1.30002500998624804212E-8f, 6.04699502254191894932E-8f, + -2.67079385394061173391E-7f, 1.11738753912010371815E-6f, + -4.41673835845875056359E-6f, 1.64484480707288970893E-5f, + -5.75419501008210370398E-5f, 1.88502885095841655729E-4f, + -5.76375574538582365885E-4f, 1.63947561694133579842E-3f, + -4.32430999505057594430E-3f, 1.05464603945949983183E-2f, + -2.37374148058994688156E-2f, 4.93052842396707084878E-2f, + -9.49010970480476444210E-2f, 1.71620901522208775349E-1f, + -3.04682672343198398683E-1f, 6.76795274409476084995E-1f}; + + const float B[] = {3.39623202570838634515E-9f, 2.26666899049817806459E-8f, + 2.04891858946906374183E-7f, 2.89137052083475648297E-6f, + 6.88975834691682398426E-5f, 3.36911647825569408990E-3f, + 8.04490411014108831608E-1f}; + T y = pabs(x); + T y_le_eight = internal::pchebevl::run( + pmadd(pset1(0.5f), y, pset1(-2.0f)), A); + T y_gt_eight = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(32.0f), y), pset1(2.0f)), B), + prsqrt(y)); + // TODO: Perhaps instead check whether all packet elements are in + // [-8, 8] and evaluate a branch based off of that. It's possible + // in practice most elements are in this region. + return pselect(pcmp_le(y, pset1(8.0f)), y_le_eight, y_gt_eight); + } +}; + +template +struct generic_i0e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* i0e.c + * + * Modified Bessel function of order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, i0e(); + * + * y = i0e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order zero of the argument. + * + * The function is defined as i0e(x) = exp(-|x|) j0( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 5.4e-16 1.2e-16 + * See i0(). + * + */ + + const double A[] = {-4.41534164647933937950E-18, 3.33079451882223809783E-17, + -2.43127984654795469359E-16, 1.71539128555513303061E-15, + -1.16853328779934516808E-14, 7.67618549860493561688E-14, + -4.85644678311192946090E-13, 2.95505266312963983461E-12, + -1.72682629144155570723E-11, 9.67580903537323691224E-11, + -5.18979560163526290666E-10, 2.65982372468238665035E-9, + -1.30002500998624804212E-8, 6.04699502254191894932E-8, + -2.67079385394061173391E-7, 1.11738753912010371815E-6, + -4.41673835845875056359E-6, 1.64484480707288970893E-5, + -5.75419501008210370398E-5, 1.88502885095841655729E-4, + -5.76375574538582365885E-4, 1.63947561694133579842E-3, + -4.32430999505057594430E-3, 1.05464603945949983183E-2, + -2.37374148058994688156E-2, 4.93052842396707084878E-2, + -9.49010970480476444210E-2, 1.71620901522208775349E-1, + -3.04682672343198398683E-1, 6.76795274409476084995E-1}; + const double B[] = { + -7.23318048787475395456E-18, -4.83050448594418207126E-18, + 4.46562142029675999901E-17, 3.46122286769746109310E-17, + -2.82762398051658348494E-16, -3.42548561967721913462E-16, + 1.77256013305652638360E-15, 3.81168066935262242075E-15, + -9.55484669882830764870E-15, -4.15056934728722208663E-14, + 1.54008621752140982691E-14, 3.85277838274214270114E-13, + 7.18012445138366623367E-13, -1.79417853150680611778E-12, + -1.32158118404477131188E-11, -3.14991652796324136454E-11, + 1.18891471078464383424E-11, 4.94060238822496958910E-10, + 3.39623202570838634515E-9, 2.26666899049817806459E-8, + 2.04891858946906374183E-7, 2.89137052083475648297E-6, + 6.88975834691682398426E-5, 3.36911647825569408990E-3, + 8.04490411014108831608E-1}; + T y = pabs(x); + T y_le_eight = internal::pchebevl::run( + pmadd(pset1(0.5), y, pset1(-2.0)), A); + T y_gt_eight = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(32.0), y), pset1(2.0)), B), + prsqrt(y)); + // TODO: Perhaps instead check whether all packet elements are in + // [-8, 8] and evaluate a branch based off of that. It's possible + // in practice most elements are in this region. + return pselect(pcmp_le(y, pset1(8.0)), y_le_eight, y_gt_eight); + } +}; + +template +struct bessel_i0e_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_i0e::run(x); + } +}; + +template +struct bessel_i0_retval { + typedef Scalar type; +}; + +template ::type> +struct generic_i0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + return pmul( + pexp(pabs(x)), + generic_i0e::run(x)); + } +}; + +template +struct bessel_i0_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_i0::run(x); + } +}; + +template +struct bessel_i1e_retval { + typedef Scalar type; +}; + +template ::type > +struct generic_i1e { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_i1e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* i1ef.c + * + * Modified Bessel function of order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * float x, y, i1ef(); + * + * y = i1ef( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order one of the argument. + * + * The function is defined as i1(x) = -i exp(-|x|) j1( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.5e-6 1.5e-7 + * See i1(). + * + */ + const float A[] = {9.38153738649577178388E-9f, -4.44505912879632808065E-8f, + 2.00329475355213526229E-7f, -8.56872026469545474066E-7f, + 3.47025130813767847674E-6f, -1.32731636560394358279E-5f, + 4.78156510755005422638E-5f, -1.61760815825896745588E-4f, + 5.12285956168575772895E-4f, -1.51357245063125314899E-3f, + 4.15642294431288815669E-3f, -1.05640848946261981558E-2f, + 2.47264490306265168283E-2f, -5.29459812080949914269E-2f, + 1.02643658689847095384E-1f, -1.76416518357834055153E-1f, + 2.52587186443633654823E-1f}; + + const float B[] = {-3.83538038596423702205E-9f, -2.63146884688951950684E-8f, + -2.51223623787020892529E-7f, -3.88256480887769039346E-6f, + -1.10588938762623716291E-4f, -9.76109749136146840777E-3f, + 7.78576235018280120474E-1f}; + + + T y = pabs(x); + T y_le_eight = pmul(y, internal::pchebevl::run( + pmadd(pset1(0.5f), y, pset1(-2.0f)), A)); + T y_gt_eight = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(32.0f), y), + pset1(2.0f)), B), + prsqrt(y)); + // TODO: Perhaps instead check whether all packet elements are in + // [-8, 8] and evaluate a branch based off of that. It's possible + // in practice most elements are in this region. + y = pselect(pcmp_le(y, pset1(8.0f)), y_le_eight, y_gt_eight); + return pselect(pcmp_lt(x, pset1(0.0f)), pnegate(y), y); + } +}; + +template +struct generic_i1e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* i1e.c + * + * Modified Bessel function of order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, i1e(); + * + * y = i1e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of order one of the argument. + * + * The function is defined as i1(x) = -i exp(-|x|) j1( ix ). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 2.0e-15 2.0e-16 + * See i1(). + * + */ + const double A[] = {2.77791411276104639959E-18, -2.11142121435816608115E-17, + 1.55363195773620046921E-16, -1.10559694773538630805E-15, + 7.60068429473540693410E-15, -5.04218550472791168711E-14, + 3.22379336594557470981E-13, -1.98397439776494371520E-12, + 1.17361862988909016308E-11, -6.66348972350202774223E-11, + 3.62559028155211703701E-10, -1.88724975172282928790E-9, + 9.38153738649577178388E-9, -4.44505912879632808065E-8, + 2.00329475355213526229E-7, -8.56872026469545474066E-7, + 3.47025130813767847674E-6, -1.32731636560394358279E-5, + 4.78156510755005422638E-5, -1.61760815825896745588E-4, + 5.12285956168575772895E-4, -1.51357245063125314899E-3, + 4.15642294431288815669E-3, -1.05640848946261981558E-2, + 2.47264490306265168283E-2, -5.29459812080949914269E-2, + 1.02643658689847095384E-1, -1.76416518357834055153E-1, + 2.52587186443633654823E-1}; + const double B[] = { + 7.51729631084210481353E-18, 4.41434832307170791151E-18, + -4.65030536848935832153E-17, -3.20952592199342395980E-17, + 2.96262899764595013876E-16, 3.30820231092092828324E-16, + -1.88035477551078244854E-15, -3.81440307243700780478E-15, + 1.04202769841288027642E-14, 4.27244001671195135429E-14, + -2.10154184277266431302E-14, -4.08355111109219731823E-13, + -7.19855177624590851209E-13, 2.03562854414708950722E-12, + 1.41258074366137813316E-11, 3.25260358301548823856E-11, + -1.89749581235054123450E-11, -5.58974346219658380687E-10, + -3.83538038596423702205E-9, -2.63146884688951950684E-8, + -2.51223623787020892529E-7, -3.88256480887769039346E-6, + -1.10588938762623716291E-4, -9.76109749136146840777E-3, + 7.78576235018280120474E-1}; + T y = pabs(x); + T y_le_eight = pmul(y, internal::pchebevl::run( + pmadd(pset1(0.5), y, pset1(-2.0)), A)); + T y_gt_eight = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(32.0), y), + pset1(2.0)), B), + prsqrt(y)); + // TODO: Perhaps instead check whether all packet elements are in + // [-8, 8] and evaluate a branch based off of that. It's possible + // in practice most elements are in this region. + y = pselect(pcmp_le(y, pset1(8.0)), y_le_eight, y_gt_eight); + return pselect(pcmp_lt(x, pset1(0.0)), pnegate(y), y); + } +}; + +template +struct bessel_i1e_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_i1e::run(x); + } +}; + +template +struct bessel_i1_retval { + typedef T type; +}; + +template ::type> +struct generic_i1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + return pmul( + pexp(pabs(x)), + generic_i1e::run(x)); + } +}; + +template +struct bessel_i1_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_i1::run(x); + } +}; + +template +struct bessel_k0e_retval { + typedef T type; +}; + +template ::type> +struct generic_k0e { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_k0e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k0ef.c + * Modified Bessel function, third kind, order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * float x, y, k0ef(); + * + * y = k0ef( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order zero of the argument. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 8.1e-7 7.8e-8 + * See k0(). + * + */ + + const float A[] = {1.90451637722020886025E-9f, 2.53479107902614945675E-7f, + 2.28621210311945178607E-5f, 1.26461541144692592338E-3f, + 3.59799365153615016266E-2f, 3.44289899924628486886E-1f, + -5.35327393233902768720E-1f}; + + const float B[] = {-1.69753450938905987466E-9f, 8.57403401741422608519E-9f, + -4.66048989768794782956E-8f, 2.76681363944501510342E-7f, + -1.83175552271911948767E-6f, 1.39498137188764993662E-5f, + -1.28495495816278026384E-4f, 1.56988388573005337491E-3f, + -3.14481013119645005427E-2f, 2.44030308206595545468E0f}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A); + x_le_two = pmadd( + generic_i0::run(x), pnegate( + plog(pmul(pset1(0.5), x))), x_le_two); + x_le_two = pmul(pexp(x), x_le_two); + T x_gt_two = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x)); + return pselect( + pcmp_le(x, pset1(0.0)), + MAXNUM, + pselect(pcmp_le(x, two), x_le_two, x_gt_two)); + } +}; + +template +struct generic_k0e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k0e.c + * Modified Bessel function, third kind, order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k0e(); + * + * y = k0e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order zero of the argument. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.4e-15 1.4e-16 + * See k0(). + * + */ + + const double A[] = { + 1.37446543561352307156E-16, + 4.25981614279661018399E-14, + 1.03496952576338420167E-11, + 1.90451637722020886025E-9, + 2.53479107902614945675E-7, + 2.28621210311945178607E-5, + 1.26461541144692592338E-3, + 3.59799365153615016266E-2, + 3.44289899924628486886E-1, + -5.35327393233902768720E-1}; + const double B[] = { + 5.30043377268626276149E-18, -1.64758043015242134646E-17, + 5.21039150503902756861E-17, -1.67823109680541210385E-16, + 5.51205597852431940784E-16, -1.84859337734377901440E-15, + 6.34007647740507060557E-15, -2.22751332699166985548E-14, + 8.03289077536357521100E-14, -2.98009692317273043925E-13, + 1.14034058820847496303E-12, -4.51459788337394416547E-12, + 1.85594911495471785253E-11, -7.95748924447710747776E-11, + 3.57739728140030116597E-10, -1.69753450938905987466E-9, + 8.57403401741422608519E-9, -4.66048989768794782956E-8, + 2.76681363944501510342E-7, -1.83175552271911948767E-6, + 1.39498137188764993662E-5, -1.28495495816278026384E-4, + 1.56988388573005337491E-3, -3.14481013119645005427E-2, + 2.44030308206595545468E0 + }; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A); + x_le_two = pmadd( + generic_i0::run(x), pmul( + pset1(-1.0), plog(pmul(pset1(0.5), x))), x_le_two); + x_le_two = pmul(pexp(x), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x)); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct bessel_k0e_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_k0e::run(x); + } +}; + +template +struct bessel_k0_retval { + typedef T type; +}; + +template ::type> +struct generic_k0 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_k0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k0f.c + * Modified Bessel function, third kind, order zero + * + * + * + * SYNOPSIS: + * + * float x, y, k0f(); + * + * y = k0f( x ); + * + * + * + * DESCRIPTION: + * + * Returns modified Bessel function of the third kind + * of order zero of the argument. + * + * The range is partitioned into the two intervals [0,8] and + * (8, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Tested at 2000 random points between 0 and 8. Peak absolute + * error (relative when K0 > 1) was 1.46e-14; rms, 4.26e-15. + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 7.8e-7 8.5e-8 + * + * ERROR MESSAGES: + * + * message condition value returned + * K0 domain x <= 0 MAXNUM + * + */ + + const float A[] = {1.90451637722020886025E-9f, 2.53479107902614945675E-7f, + 2.28621210311945178607E-5f, 1.26461541144692592338E-3f, + 3.59799365153615016266E-2f, 3.44289899924628486886E-1f, + -5.35327393233902768720E-1f}; + + const float B[] = {-1.69753450938905987466E-9f, 8.57403401741422608519E-9f, + -4.66048989768794782956E-8f, 2.76681363944501510342E-7f, + -1.83175552271911948767E-6f, 1.39498137188764993662E-5f, + -1.28495495816278026384E-4f, 1.56988388573005337491E-3f, + -3.14481013119645005427E-2f, 2.44030308206595545468E0f}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A); + x_le_two = pmadd( + generic_i0::run(x), pnegate( + plog(pmul(pset1(0.5), x))), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + pmul( + pexp(pnegate(x)), + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B)), + prsqrt(x)); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct generic_k0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* + * + * Modified Bessel function, third kind, order zero, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k0(); + * + * y = k0( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order zero of the argument. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 1.4e-15 1.4e-16 + * See k0(). + * + */ + const double A[] = { + 1.37446543561352307156E-16, + 4.25981614279661018399E-14, + 1.03496952576338420167E-11, + 1.90451637722020886025E-9, + 2.53479107902614945675E-7, + 2.28621210311945178607E-5, + 1.26461541144692592338E-3, + 3.59799365153615016266E-2, + 3.44289899924628486886E-1, + -5.35327393233902768720E-1}; + const double B[] = { + 5.30043377268626276149E-18, -1.64758043015242134646E-17, + 5.21039150503902756861E-17, -1.67823109680541210385E-16, + 5.51205597852431940784E-16, -1.84859337734377901440E-15, + 6.34007647740507060557E-15, -2.22751332699166985548E-14, + 8.03289077536357521100E-14, -2.98009692317273043925E-13, + 1.14034058820847496303E-12, -4.51459788337394416547E-12, + 1.85594911495471785253E-11, -7.95748924447710747776E-11, + 3.57739728140030116597E-10, -1.69753450938905987466E-9, + 8.57403401741422608519E-9, -4.66048989768794782956E-8, + 2.76681363944501510342E-7, -1.83175552271911948767E-6, + 1.39498137188764993662E-5, -1.28495495816278026384E-4, + 1.56988388573005337491E-3, -3.14481013119645005427E-2, + 2.44030308206595545468E0 + }; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A); + x_le_two = pmadd( + generic_i0::run(x), pnegate( + plog(pmul(pset1(0.5), x))), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + pmul( + pexp(-x), + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B)), + prsqrt(x)); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct bessel_k0_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_k0::run(x); + } +}; + +template +struct bessel_k1e_retval { + typedef T type; +}; + +template ::type> +struct generic_k1e { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_k1e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k1ef.c + * + * Modified Bessel function, third kind, order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * float x, y, k1ef(); + * + * y = k1ef( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order one of the argument: + * + * k1e(x) = exp(x) * k1(x). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 4.9e-7 6.7e-8 + * See k1(). + * + */ + + const float A[] = {-2.21338763073472585583E-8f, -2.43340614156596823496E-6f, + -1.73028895751305206302E-4f, -6.97572385963986435018E-3f, + -1.22611180822657148235E-1f, -3.53155960776544875667E-1f, + 1.52530022733894777053E0f}; + const float B[] = {2.01504975519703286596E-9f, -1.03457624656780970260E-8f, + 5.74108412545004946722E-8f, -3.50196060308781257119E-7f, + 2.40648494783721712015E-6f, -1.93619797416608296024E-5f, + 1.95215518471351631108E-4f, -2.85781685962277938680E-3f, + 1.03923736576817238437E-1f, 2.72062619048444266945E0f}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = pdiv(internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A), x); + x_le_two = pmadd( + generic_i1::run(x), plog(pmul(pset1(0.5), x)), x_le_two); + x_le_two = pmul(x_le_two, pexp(x)); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x)); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct generic_k1e { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k1e.c + * + * Modified Bessel function, third kind, order one, + * exponentially scaled + * + * + * + * SYNOPSIS: + * + * double x, y, k1e(); + * + * y = k1e( x ); + * + * + * + * DESCRIPTION: + * + * Returns exponentially scaled modified Bessel function + * of the third kind of order one of the argument: + * + * k1e(x) = exp(x) * k1(x). + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 7.8e-16 1.2e-16 + * See k1(). + * + */ + const double A[] = {-7.02386347938628759343E-18, -2.42744985051936593393E-15, + -6.66690169419932900609E-13, -1.41148839263352776110E-10, + -2.21338763073472585583E-8, -2.43340614156596823496E-6, + -1.73028895751305206302E-4, -6.97572385963986435018E-3, + -1.22611180822657148235E-1, -3.53155960776544875667E-1, + 1.52530022733894777053E0}; + const double B[] = {-5.75674448366501715755E-18, 1.79405087314755922667E-17, + -5.68946255844285935196E-17, 1.83809354436663880070E-16, + -6.05704724837331885336E-16, 2.03870316562433424052E-15, + -7.01983709041831346144E-15, 2.47715442448130437068E-14, + -8.97670518232499435011E-14, 3.34841966607842919884E-13, + -1.28917396095102890680E-12, 5.13963967348173025100E-12, + -2.12996783842756842877E-11, 9.21831518760500529508E-11, + -4.19035475934189648750E-10, 2.01504975519703286596E-9, + -1.03457624656780970260E-8, 5.74108412545004946722E-8, + -3.50196060308781257119E-7, 2.40648494783721712015E-6, + -1.93619797416608296024E-5, 1.95215518471351631108E-4, + -2.85781685962277938680E-3, 1.03923736576817238437E-1, + 2.72062619048444266945E0}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = pdiv(internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A), x); + x_le_two = pmadd( + generic_i1::run(x), plog(pmul(pset1(0.5), x)), x_le_two); + x_le_two = pmul(x_le_two, pexp(x)); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x)); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct bessel_k1e_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_k1e::run(x); + } +}; + +template +struct bessel_k1_retval { + typedef T type; +}; + +template ::type> +struct generic_k1 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_k1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k1f.c + * Modified Bessel function, third kind, order one + * + * + * + * SYNOPSIS: + * + * float x, y, k1f(); + * + * y = k1f( x ); + * + * + * + * DESCRIPTION: + * + * Computes the modified Bessel function of the third kind + * of order one of the argument. + * + * The range is partitioned into the two intervals [0,2] and + * (2, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 4.6e-7 7.6e-8 + * + * ERROR MESSAGES: + * + * message condition value returned + * k1 domain x <= 0 MAXNUM + * + */ + + const float A[] = {-2.21338763073472585583E-8f, -2.43340614156596823496E-6f, + -1.73028895751305206302E-4f, -6.97572385963986435018E-3f, + -1.22611180822657148235E-1f, -3.53155960776544875667E-1f, + 1.52530022733894777053E0f}; + const float B[] = {2.01504975519703286596E-9f, -1.03457624656780970260E-8f, + 5.74108412545004946722E-8f, -3.50196060308781257119E-7f, + 2.40648494783721712015E-6f, -1.93619797416608296024E-5f, + 1.95215518471351631108E-4f, -2.85781685962277938680E-3f, + 1.03923736576817238437E-1f, 2.72062619048444266945E0f}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = pdiv(internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A), x); + x_le_two = pmadd( + generic_i1::run(x), plog(pmul(pset1(0.5), x)), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + pexp(pnegate(x)), + pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x))); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct generic_k1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* k1.c + * Modified Bessel function, third kind, order one + * + * + * + * SYNOPSIS: + * + * float x, y, k1f(); + * + * y = k1f( x ); + * + * + * + * DESCRIPTION: + * + * Computes the modified Bessel function of the third kind + * of order one of the argument. + * + * The range is partitioned into the two intervals [0,2] and + * (2, infinity). Chebyshev polynomial expansions are employed + * in each interval. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0, 30 30000 4.6e-7 7.6e-8 + * + * ERROR MESSAGES: + * + * message condition value returned + * k1 domain x <= 0 MAXNUM + * + */ + const double A[] = {-7.02386347938628759343E-18, -2.42744985051936593393E-15, + -6.66690169419932900609E-13, -1.41148839263352776110E-10, + -2.21338763073472585583E-8, -2.43340614156596823496E-6, + -1.73028895751305206302E-4, -6.97572385963986435018E-3, + -1.22611180822657148235E-1, -3.53155960776544875667E-1, + 1.52530022733894777053E0}; + const double B[] = {-5.75674448366501715755E-18, 1.79405087314755922667E-17, + -5.68946255844285935196E-17, 1.83809354436663880070E-16, + -6.05704724837331885336E-16, 2.03870316562433424052E-15, + -7.01983709041831346144E-15, 2.47715442448130437068E-14, + -8.97670518232499435011E-14, 3.34841966607842919884E-13, + -1.28917396095102890680E-12, 5.13963967348173025100E-12, + -2.12996783842756842877E-11, 9.21831518760500529508E-11, + -4.19035475934189648750E-10, 2.01504975519703286596E-9, + -1.03457624656780970260E-8, 5.74108412545004946722E-8, + -3.50196060308781257119E-7, 2.40648494783721712015E-6, + -1.93619797416608296024E-5, 1.95215518471351631108E-4, + -2.85781685962277938680E-3, 1.03923736576817238437E-1, + 2.72062619048444266945E0}; + const T MAXNUM = pset1(NumTraits::infinity()); + const T two = pset1(2.0); + T x_le_two = pdiv(internal::pchebevl::run( + pmadd(x, x, pset1(-2.0)), A), x); + x_le_two = pmadd( + generic_i1::run(x), plog(pmul(pset1(0.5), x)), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), MAXNUM, x_le_two); + T x_gt_two = pmul( + pexp(-x), + pmul( + internal::pchebevl::run( + psub(pdiv(pset1(8.0), x), two), B), + prsqrt(x))); + return pselect(pcmp_le(x, two), x_le_two, x_gt_two); + } +}; + +template +struct bessel_k1_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_k1::run(x); + } +}; + +template +struct bessel_j0_retval { + typedef T type; +}; + +template ::type> +struct generic_j0 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_j0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j0f.c + * Bessel function of order zero + * + * + * + * SYNOPSIS: + * + * float x, y, j0f(); + * + * y = j0f( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order zero of the argument. + * + * The domain is divided into the intervals [0, 2] and + * (2, infinity). In the first interval the following polynomial + * approximation is used: + * + * + * 2 2 2 + * (w - r ) (w - r ) (w - r ) P(w) + * 1 2 3 + * + * 2 + * where w = x and the three r's are zeros of the function. + * + * In the second interval, the modulus and phase are approximated + * by polynomials of the form Modulus(x) = sqrt(1/x) Q(1/x) + * and Phase(x) = x + 1/x R(1/x^2) - pi/4. The function is + * + * j0(x) = Modulus(x) cos( Phase(x) ). + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 2 100000 1.3e-7 3.6e-8 + * IEEE 2, 32 100000 1.9e-7 5.4e-8 + * + */ + + const float JP[] = {-6.068350350393235E-008f, 6.388945720783375E-006f, + -3.969646342510940E-004f, 1.332913422519003E-002f, + -1.729150680240724E-001f}; + const float MO[] = {-6.838999669318810E-002f, 1.864949361379502E-001f, + -2.145007480346739E-001f, 1.197549369473540E-001f, + -3.560281861530129E-003f, -4.969382655296620E-002f, + -3.355424622293709E-006f, 7.978845717621440E-001f}; + const float PH[] = {3.242077816988247E+001f, -3.630592630518434E+001f, + 1.756221482109099E+001f, -4.974978466280903E+000f, + 1.001973420681837E+000f, -1.939906941791308E-001f, + 6.490598792654666E-002f, -1.249992184872738E-001f}; + const T DR1 = pset1(5.78318596294678452118f); + const T NEG_PIO4F = pset1(-0.7853981633974483096f); /* -pi / 4 */ + T y = pabs(x); + T z = pmul(y, y); + T y_le_two = pselect( + pcmp_lt(y, pset1(1.0e-3f)), + pmadd(z, pset1(-0.25f), pset1(1.0f)), + pmul(psub(z, DR1), internal::ppolevl::run(z, JP))); + T q = pdiv(pset1(1.0f), y); + T w = prsqrt(y); + T p = pmul(w, internal::ppolevl::run(q, MO)); + w = pmul(q, q); + T yn = pmadd(q, internal::ppolevl::run(w, PH), NEG_PIO4F); + T y_gt_two = pmul(p, pcos(padd(yn, y))); + return pselect(pcmp_le(y, pset1(2.0)), y_le_two, y_gt_two); + } +}; + +template +struct generic_j0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j0.c + * Bessel function of order zero + * + * + * + * SYNOPSIS: + * + * double x, y, j0(); + * + * y = j0( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order zero of the argument. + * + * The domain is divided into the intervals [0, 5] and + * (5, infinity). In the first interval the following rational + * approximation is used: + * + * + * 2 2 + * (w - r ) (w - r ) P (w) / Q (w) + * 1 2 3 8 + * + * 2 + * where w = x and the two r's are zeros of the function. + * + * In the second interval, the Hankel asymptotic expansion + * is employed with two rational functions of degree 6/6 + * and 7/7. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * DEC 0, 30 10000 4.4e-17 6.3e-18 + * IEEE 0, 30 60000 4.2e-16 1.1e-16 + * + */ + const double PP[] = {7.96936729297347051624E-4, 8.28352392107440799803E-2, + 1.23953371646414299388E0, 5.44725003058768775090E0, + 8.74716500199817011941E0, 5.30324038235394892183E0, + 9.99999999999999997821E-1}; + const double PQ[] = {9.24408810558863637013E-4, 8.56288474354474431428E-2, + 1.25352743901058953537E0, 5.47097740330417105182E0, + 8.76190883237069594232E0, 5.30605288235394617618E0, + 1.00000000000000000218E0}; + const double QP[] = {-1.13663838898469149931E-2, -1.28252718670509318512E0, + -1.95539544257735972385E1, -9.32060152123768231369E1, + -1.77681167980488050595E2, -1.47077505154951170175E2, + -5.14105326766599330220E1, -6.05014350600728481186E0}; + const double QQ[] = {1.00000000000000000000E0, 6.43178256118178023184E1, + 8.56430025976980587198E2, 3.88240183605401609683E3, + 7.24046774195652478189E3, 5.93072701187316984827E3, + 2.06209331660327847417E3, 2.42005740240291393179E2}; + const double RP[] = {-4.79443220978201773821E9, 1.95617491946556577543E12, + -2.49248344360967716204E14, 9.70862251047306323952E15}; + const double RQ[] = {1.00000000000000000000E0, 4.99563147152651017219E2, + 1.73785401676374683123E5, 4.84409658339962045305E7, + 1.11855537045356834862E10, 2.11277520115489217587E12, + 3.10518229857422583814E14, 3.18121955943204943306E16, + 1.71086294081043136091E18}; + const T DR1 = pset1(5.78318596294678452118E0); + const T DR2 = pset1(3.04712623436620863991E1); + const T SQ2OPI = pset1(7.9788456080286535587989E-1); /* sqrt(2 / pi) */ + const T NEG_PIO4 = pset1(-0.7853981633974483096); /* pi / 4 */ + + T y = pabs(x); + T z = pmul(y, y); + T y_le_five = pselect( + pcmp_lt(y, pset1(1.0e-5)), + pmadd(z, pset1(-0.25), pset1(1.0)), + pmul(pmul(psub(z, DR1), psub(z, DR2)), + pdiv(internal::ppolevl::run(z, RP), + internal::ppolevl::run(z, RQ)))); + T s = pdiv(pset1(25.0), z); + T p = pdiv( + internal::ppolevl::run(s, PP), + internal::ppolevl::run(s, PQ)); + T q = pdiv( + internal::ppolevl::run(s, QP), + internal::ppolevl::run(s, QQ)); + T yn = padd(y, NEG_PIO4); + T w = pdiv(pset1(-5.0), y); + p = pmadd(p, pcos(yn), pmul(w, pmul(q, psin(yn)))); + T y_gt_five = pmul(p, pmul(SQ2OPI, prsqrt(y))); + return pselect(pcmp_le(y, pset1(5.0)), y_le_five, y_gt_five); + } +}; + +template +struct bessel_j0_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_j0::run(x); + } +}; + +template +struct bessel_y0_retval { + typedef T type; +}; + +template ::type> +struct generic_y0 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_y0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j0f.c + * Bessel function of the second kind, order zero + * + * + * + * SYNOPSIS: + * + * float x, y, y0f(); + * + * y = y0f( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind, of order + * zero, of the argument. + * + * The domain is divided into the intervals [0, 2] and + * (2, infinity). In the first interval a rational approximation + * R(x) is employed to compute + * + * 2 2 2 + * y0(x) = (w - r ) (w - r ) (w - r ) R(x) + 2/pi ln(x) j0(x). + * 1 2 3 + * + * Thus a call to j0() is required. The three zeros are removed + * from R(x) to improve its numerical stability. + * + * In the second interval, the modulus and phase are approximated + * by polynomials of the form Modulus(x) = sqrt(1/x) Q(1/x) + * and Phase(x) = x + 1/x S(1/x^2) - pi/4. Then the function is + * + * y0(x) = Modulus(x) sin( Phase(x) ). + * + * + * + * + * ACCURACY: + * + * Absolute error, when y0(x) < 1; else relative error: + * + * arithmetic domain # trials peak rms + * IEEE 0, 2 100000 2.4e-7 3.4e-8 + * IEEE 2, 32 100000 1.8e-7 5.3e-8 + * + */ + + const float YP[] = {9.454583683980369E-008f, -9.413212653797057E-006f, + 5.344486707214273E-004f, -1.584289289821316E-002f, + 1.707584643733568E-001f}; + const float MO[] = {-6.838999669318810E-002f, 1.864949361379502E-001f, + -2.145007480346739E-001f, 1.197549369473540E-001f, + -3.560281861530129E-003f, -4.969382655296620E-002f, + -3.355424622293709E-006f, 7.978845717621440E-001f}; + const float PH[] = {3.242077816988247E+001f, -3.630592630518434E+001f, + 1.756221482109099E+001f, -4.974978466280903E+000f, + 1.001973420681837E+000f, -1.939906941791308E-001f, + 6.490598792654666E-002f, -1.249992184872738E-001f}; + const T YZ1 = pset1(0.43221455686510834878f); + const T TWOOPI = pset1(0.636619772367581343075535f); /* 2 / pi */ + const T NEG_PIO4F = pset1(-0.7853981633974483096f); /* -pi / 4 */ + const T NEG_MAXNUM = pset1(-NumTraits::infinity()); + T z = pmul(x, x); + T x_le_two = pmul(TWOOPI, pmul(plog(x), generic_j0::run(x))); + x_le_two = pmadd( + psub(z, YZ1), internal::ppolevl::run(z, YP), x_le_two); + x_le_two = pselect(pcmp_le(x, pset1(0.0)), NEG_MAXNUM, x_le_two); + T q = pdiv(pset1(1.0), x); + T w = prsqrt(x); + T p = pmul(w, internal::ppolevl::run(q, MO)); + T u = pmul(q, q); + T xn = pmadd(q, internal::ppolevl::run(u, PH), NEG_PIO4F); + T x_gt_two = pmul(p, psin(padd(xn, x))); + return pselect(pcmp_le(x, pset1(2.0)), x_le_two, x_gt_two); + } +}; + +template +struct generic_y0 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j0.c + * Bessel function of the second kind, order zero + * + * + * + * SYNOPSIS: + * + * double x, y, y0(); + * + * y = y0( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind, of order + * zero, of the argument. + * + * The domain is divided into the intervals [0, 5] and + * (5, infinity). In the first interval a rational approximation + * R(x) is employed to compute + * y0(x) = R(x) + 2 * log(x) * j0(x) / PI. + * Thus a call to j0() is required. + * + * In the second interval, the Hankel asymptotic expansion + * is employed with two rational functions of degree 6/6 + * and 7/7. + * + * + * + * ACCURACY: + * + * Absolute error, when y0(x) < 1; else relative error: + * + * arithmetic domain # trials peak rms + * DEC 0, 30 9400 7.0e-17 7.9e-18 + * IEEE 0, 30 30000 1.3e-15 1.6e-16 + * + */ + const double PP[] = {7.96936729297347051624E-4, 8.28352392107440799803E-2, + 1.23953371646414299388E0, 5.44725003058768775090E0, + 8.74716500199817011941E0, 5.30324038235394892183E0, + 9.99999999999999997821E-1}; + const double PQ[] = {9.24408810558863637013E-4, 8.56288474354474431428E-2, + 1.25352743901058953537E0, 5.47097740330417105182E0, + 8.76190883237069594232E0, 5.30605288235394617618E0, + 1.00000000000000000218E0}; + const double QP[] = {-1.13663838898469149931E-2, -1.28252718670509318512E0, + -1.95539544257735972385E1, -9.32060152123768231369E1, + -1.77681167980488050595E2, -1.47077505154951170175E2, + -5.14105326766599330220E1, -6.05014350600728481186E0}; + const double QQ[] = {1.00000000000000000000E0, 6.43178256118178023184E1, + 8.56430025976980587198E2, 3.88240183605401609683E3, + 7.24046774195652478189E3, 5.93072701187316984827E3, + 2.06209331660327847417E3, 2.42005740240291393179E2}; + const double YP[] = {1.55924367855235737965E4, -1.46639295903971606143E7, + 5.43526477051876500413E9, -9.82136065717911466409E11, + 8.75906394395366999549E13, -3.46628303384729719441E15, + 4.42733268572569800351E16, -1.84950800436986690637E16}; + const double YQ[] = {1.00000000000000000000E0, 1.04128353664259848412E3, + 6.26107330137134956842E5, 2.68919633393814121987E8, + 8.64002487103935000337E10, 2.02979612750105546709E13, + 3.17157752842975028269E15, 2.50596256172653059228E17}; + const T SQ2OPI = pset1(7.9788456080286535587989E-1); /* sqrt(2 / pi) */ + const T TWOOPI = pset1(0.636619772367581343075535); /* 2 / pi */ + const T NEG_PIO4 = pset1(-0.7853981633974483096); /* -pi / 4 */ + const T NEG_MAXNUM = pset1(-NumTraits::infinity()); + + T z = pmul(x, x); + T x_le_five = pdiv(internal::ppolevl::run(z, YP), + internal::ppolevl::run(z, YQ)); + x_le_five = pmadd( + pmul(TWOOPI, plog(x)), generic_j0::run(x), x_le_five); + x_le_five = pselect(pcmp_le(x, pset1(0.0)), NEG_MAXNUM, x_le_five); + T s = pdiv(pset1(25.0), z); + T p = pdiv( + internal::ppolevl::run(s, PP), + internal::ppolevl::run(s, PQ)); + T q = pdiv( + internal::ppolevl::run(s, QP), + internal::ppolevl::run(s, QQ)); + T xn = padd(x, NEG_PIO4); + T w = pdiv(pset1(5.0), x); + p = pmadd(p, psin(xn), pmul(w, pmul(q, pcos(xn)))); + T x_gt_five = pmul(p, pmul(SQ2OPI, prsqrt(x))); + return pselect(pcmp_le(x, pset1(5.0)), x_le_five, x_gt_five); + } +}; + +template +struct bessel_y0_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_y0::run(x); + } +}; + +template +struct bessel_j1_retval { + typedef T type; +}; + +template ::type> +struct generic_j1 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_j1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j1f.c + * Bessel function of order one + * + * + * + * SYNOPSIS: + * + * float x, y, j1f(); + * + * y = j1f( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order one of the argument. + * + * The domain is divided into the intervals [0, 2] and + * (2, infinity). In the first interval a polynomial approximation + * 2 + * (w - r ) x P(w) + * 1 + * 2 + * is used, where w = x and r is the first zero of the function. + * + * In the second interval, the modulus and phase are approximated + * by polynomials of the form Modulus(x) = sqrt(1/x) Q(1/x) + * and Phase(x) = x + 1/x R(1/x^2) - 3pi/4. The function is + * + * j0(x) = Modulus(x) cos( Phase(x) ). + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 2 100000 1.2e-7 2.5e-8 + * IEEE 2, 32 100000 2.0e-7 5.3e-8 + * + * + */ + + const float JP[] = {-4.878788132172128E-009f, 6.009061827883699E-007f, + -4.541343896997497E-005f, 1.937383947804541E-003f, + -3.405537384615824E-002f}; + const float MO1[] = {6.913942741265801E-002f, -2.284801500053359E-001f, + 3.138238455499697E-001f, -2.102302420403875E-001f, + 5.435364690523026E-003f, 1.493389585089498E-001f, + 4.976029650847191E-006f, 7.978845453073848E-001f}; + const float PH1[] = {-4.497014141919556E+001f, 5.073465654089319E+001f, + -2.485774108720340E+001f, 7.222973196770240E+000f, + -1.544842782180211E+000f, 3.503787691653334E-001f, + -1.637986776941202E-001f, 3.749989509080821E-001f}; + const T Z1 = pset1(1.46819706421238932572E1f); + const T NEG_THPIO4F = pset1(-2.35619449019234492885f); /* -3*pi/4 */ + + T y = pabs(x); + T z = pmul(y, y); + T y_le_two = pmul( + psub(z, Z1), + pmul(x, internal::ppolevl::run(z, JP))); + T q = pdiv(pset1(1.0f), y); + T w = prsqrt(y); + T p = pmul(w, internal::ppolevl::run(q, MO1)); + w = pmul(q, q); + T yn = pmadd(q, internal::ppolevl::run(w, PH1), NEG_THPIO4F); + T y_gt_two = pmul(p, pcos(padd(yn, y))); + // j1 is an odd function. This implementation differs from cephes to + // take this fact in to account. Cephes returns -j1(x) for y > 2 range. + y_gt_two = pselect( + pcmp_lt(x, pset1(0.0f)), pnegate(y_gt_two), y_gt_two); + return pselect(pcmp_le(y, pset1(2.0f)), y_le_two, y_gt_two); + } +}; + +template +struct generic_j1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j1.c + * Bessel function of order one + * + * + * + * SYNOPSIS: + * + * double x, y, j1(); + * + * y = j1( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of order one of the argument. + * + * The domain is divided into the intervals [0, 8] and + * (8, infinity). In the first interval a 24 term Chebyshev + * expansion is used. In the second, the asymptotic + * trigonometric representation is employed using two + * rational functions of degree 5/5. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * DEC 0, 30 10000 4.0e-17 1.1e-17 + * IEEE 0, 30 30000 2.6e-16 1.1e-16 + * + */ + const double PP[] = {7.62125616208173112003E-4, 7.31397056940917570436E-2, + 1.12719608129684925192E0, 5.11207951146807644818E0, + 8.42404590141772420927E0, 5.21451598682361504063E0, + 1.00000000000000000254E0}; + const double PQ[] = {5.71323128072548699714E-4, 6.88455908754495404082E-2, + 1.10514232634061696926E0, 5.07386386128601488557E0, + 8.39985554327604159757E0, 5.20982848682361821619E0, + 9.99999999999999997461E-1}; + const double QP[] = {5.10862594750176621635E-2, 4.98213872951233449420E0, + 7.58238284132545283818E1, 3.66779609360150777800E2, + 7.10856304998926107277E2, 5.97489612400613639965E2, + 2.11688757100572135698E2, 2.52070205858023719784E1}; + const double QQ[] = {1.00000000000000000000E0, 7.42373277035675149943E1, + 1.05644886038262816351E3, 4.98641058337653607651E3, + 9.56231892404756170795E3, 7.99704160447350683650E3, + 2.82619278517639096600E3, 3.36093607810698293419E2}; + const double RP[] = {-8.99971225705559398224E8, 4.52228297998194034323E11, + -7.27494245221818276015E13, 3.68295732863852883286E15}; + const double RQ[] = {1.00000000000000000000E0, 6.20836478118054335476E2, + 2.56987256757748830383E5, 8.35146791431949253037E7, + 2.21511595479792499675E10, 4.74914122079991414898E12, + 7.84369607876235854894E14, 8.95222336184627338078E16, + 5.32278620332680085395E18}; + const T Z1 = pset1(1.46819706421238932572E1); + const T Z2 = pset1(4.92184563216946036703E1); + const T NEG_THPIO4 = pset1(-2.35619449019234492885); /* -3*pi/4 */ + const T SQ2OPI = pset1(7.9788456080286535587989E-1); /* sqrt(2 / pi) */ + T y = pabs(x); + T z = pmul(y, y); + T y_le_five = pdiv(internal::ppolevl::run(z, RP), + internal::ppolevl::run(z, RQ)); + y_le_five = pmul(pmul(pmul(y_le_five, x), psub(z, Z1)), psub(z, Z2)); + T s = pdiv(pset1(25.0), z); + T p = pdiv( + internal::ppolevl::run(s, PP), + internal::ppolevl::run(s, PQ)); + T q = pdiv( + internal::ppolevl::run(s, QP), + internal::ppolevl::run(s, QQ)); + T yn = padd(y, NEG_THPIO4); + T w = pdiv(pset1(-5.0), y); + p = pmadd(p, pcos(yn), pmul(w, pmul(q, psin(yn)))); + T y_gt_five = pmul(p, pmul(SQ2OPI, prsqrt(y))); + // j1 is an odd function. This implementation differs from cephes to + // take this fact in to account. Cephes returns -j1(x) for y > 5 range. + y_gt_five = pselect( + pcmp_lt(x, pset1(0.0)), pnegate(y_gt_five), y_gt_five); + return pselect(pcmp_le(y, pset1(5.0)), y_le_five, y_gt_five); + } +}; + +template +struct bessel_j1_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_j1::run(x); + } +}; + +template +struct bessel_y1_retval { + typedef T type; +}; + +template ::type> +struct generic_y1 { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE T run(const T&) { + return ScalarType(0); + } +}; + +template +struct generic_y1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j1f.c + * Bessel function of second kind of order one + * + * + * + * SYNOPSIS: + * + * double x, y, y1(); + * + * y = y1( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind of order one + * of the argument. + * + * The domain is divided into the intervals [0, 2] and + * (2, infinity). In the first interval a rational approximation + * R(x) is employed to compute + * + * 2 + * y0(x) = (w - r ) x R(x^2) + 2/pi (ln(x) j1(x) - 1/x) . + * 1 + * + * Thus a call to j1() is required. + * + * In the second interval, the modulus and phase are approximated + * by polynomials of the form Modulus(x) = sqrt(1/x) Q(1/x) + * and Phase(x) = x + 1/x S(1/x^2) - 3pi/4. Then the function is + * + * y0(x) = Modulus(x) sin( Phase(x) ). + * + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * IEEE 0, 2 100000 2.2e-7 4.6e-8 + * IEEE 2, 32 100000 1.9e-7 5.3e-8 + * + * (error criterion relative when |y1| > 1). + * + */ + + const float YP[] = {8.061978323326852E-009f, -9.496460629917016E-007f, + 6.719543806674249E-005f, -2.641785726447862E-003f, + 4.202369946500099E-002f}; + const float MO1[] = {6.913942741265801E-002f, -2.284801500053359E-001f, + 3.138238455499697E-001f, -2.102302420403875E-001f, + 5.435364690523026E-003f, 1.493389585089498E-001f, + 4.976029650847191E-006f, 7.978845453073848E-001f}; + const float PH1[] = {-4.497014141919556E+001f, 5.073465654089319E+001f, + -2.485774108720340E+001f, 7.222973196770240E+000f, + -1.544842782180211E+000f, 3.503787691653334E-001f, + -1.637986776941202E-001f, 3.749989509080821E-001f}; + const T YO1 = pset1(4.66539330185668857532f); + const T NEG_THPIO4F = pset1(-2.35619449019234492885f); /* -3*pi/4 */ + const T TWOOPI = pset1(0.636619772367581343075535f); /* 2/pi */ + const T NEG_MAXNUM = pset1(-NumTraits::infinity()); + + T z = pmul(x, x); + T x_le_two = pmul(psub(z, YO1), internal::ppolevl::run(z, YP)); + x_le_two = pmadd( + x_le_two, x, + pmul(TWOOPI, pmadd( + generic_j1::run(x), plog(x), + pdiv(pset1(-1.0f), x)))); + x_le_two = pselect(pcmp_lt(x, pset1(0.0f)), NEG_MAXNUM, x_le_two); + + T q = pdiv(pset1(1.0), x); + T w = prsqrt(x); + T p = pmul(w, internal::ppolevl::run(q, MO1)); + w = pmul(q, q); + T xn = pmadd(q, internal::ppolevl::run(w, PH1), NEG_THPIO4F); + T x_gt_two = pmul(p, psin(padd(xn, x))); + return pselect(pcmp_le(x, pset1(2.0)), x_le_two, x_gt_two); + } +}; + +template +struct generic_y1 { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + /* j1.c + * Bessel function of second kind of order one + * + * + * + * SYNOPSIS: + * + * double x, y, y1(); + * + * y = y1( x ); + * + * + * + * DESCRIPTION: + * + * Returns Bessel function of the second kind of order one + * of the argument. + * + * The domain is divided into the intervals [0, 8] and + * (8, infinity). In the first interval a 25 term Chebyshev + * expansion is used, and a call to j1() is required. + * In the second, the asymptotic trigonometric representation + * is employed using two rational functions of degree 5/5. + * + * + * + * ACCURACY: + * + * Absolute error: + * arithmetic domain # trials peak rms + * DEC 0, 30 10000 8.6e-17 1.3e-17 + * IEEE 0, 30 30000 1.0e-15 1.3e-16 + * + * (error criterion relative when |y1| > 1). + * + */ + const double PP[] = {7.62125616208173112003E-4, 7.31397056940917570436E-2, + 1.12719608129684925192E0, 5.11207951146807644818E0, + 8.42404590141772420927E0, 5.21451598682361504063E0, + 1.00000000000000000254E0}; + const double PQ[] = {5.71323128072548699714E-4, 6.88455908754495404082E-2, + 1.10514232634061696926E0, 5.07386386128601488557E0, + 8.39985554327604159757E0, 5.20982848682361821619E0, + 9.99999999999999997461E-1}; + const double QP[] = {5.10862594750176621635E-2, 4.98213872951233449420E0, + 7.58238284132545283818E1, 3.66779609360150777800E2, + 7.10856304998926107277E2, 5.97489612400613639965E2, + 2.11688757100572135698E2, 2.52070205858023719784E1}; + const double QQ[] = {1.00000000000000000000E0, 7.42373277035675149943E1, + 1.05644886038262816351E3, 4.98641058337653607651E3, + 9.56231892404756170795E3, 7.99704160447350683650E3, + 2.82619278517639096600E3, 3.36093607810698293419E2}; + const double YP[] = {1.26320474790178026440E9, -6.47355876379160291031E11, + 1.14509511541823727583E14, -8.12770255501325109621E15, + 2.02439475713594898196E17, -7.78877196265950026825E17}; + const double YQ[] = {1.00000000000000000000E0, 5.94301592346128195359E2, + 2.35564092943068577943E5, 7.34811944459721705660E7, + 1.87601316108706159478E10, 3.88231277496238566008E12, + 6.20557727146953693363E14, 6.87141087355300489866E16, + 3.97270608116560655612E18}; + const T SQ2OPI = pset1(.79788456080286535588); + const T NEG_THPIO4 = pset1(-2.35619449019234492885); /* -3*pi/4 */ + const T TWOOPI = pset1(0.636619772367581343075535); /* 2/pi */ + const T NEG_MAXNUM = pset1(-NumTraits::infinity()); + + T z = pmul(x, x); + T x_le_five = pdiv(internal::ppolevl::run(z, YP), + internal::ppolevl::run(z, YQ)); + x_le_five = pmadd( + x_le_five, x, pmul( + TWOOPI, pmadd(generic_j1::run(x), plog(x), + pdiv(pset1(-1.0), x)))); + + x_le_five = pselect(pcmp_le(x, pset1(0.0)), NEG_MAXNUM, x_le_five); + T s = pdiv(pset1(25.0), z); + T p = pdiv( + internal::ppolevl::run(s, PP), + internal::ppolevl::run(s, PQ)); + T q = pdiv( + internal::ppolevl::run(s, QP), + internal::ppolevl::run(s, QQ)); + T xn = padd(x, NEG_THPIO4); + T w = pdiv(pset1(5.0), x); + p = pmadd(p, psin(xn), pmul(w, pmul(q, pcos(xn)))); + T x_gt_five = pmul(p, pmul(SQ2OPI, prsqrt(x))); + return pselect(pcmp_le(x, pset1(5.0)), x_le_five, x_gt_five); + } +}; + +template +struct bessel_y1_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T x) { + return generic_y1::run(x); + } +}; + +} // end namespace internal + +namespace numext { + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_i0, Scalar) + bessel_i0(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_i0, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_i0e, Scalar) + bessel_i0e(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_i0e, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_i1, Scalar) + bessel_i1(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_i1, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_i1e, Scalar) + bessel_i1e(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_i1e, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_k0, Scalar) + bessel_k0(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_k0, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_k0e, Scalar) + bessel_k0e(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_k0e, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_k1, Scalar) + bessel_k1(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_k1, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_k1e, Scalar) + bessel_k1e(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_k1e, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_j0, Scalar) + bessel_j0(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_j0, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_y0, Scalar) + bessel_y0(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_y0, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_j1, Scalar) + bessel_j1(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_j1, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(bessel_y1, Scalar) + bessel_y1(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(bessel_y1, Scalar)::run(x); +} + +} // end namespace numext + +} // end namespace Eigen + +#endif // EIGEN_BESSEL_FUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsPacketMath.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsPacketMath.h new file mode 100644 index 0000000000000000000000000000000000000000..ac8c57bfa9e3e6d5a92f5bd855c9b4f42a397864 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsPacketMath.h @@ -0,0 +1,120 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BESSELFUNCTIONS_PACKETMATH_H +#define EIGEN_BESSELFUNCTIONS_PACKETMATH_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero i0(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_i0(const Packet& x) { + return numext::bessel_i0(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero i0e(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_i0e(const Packet& x) { + return numext::bessel_i0e(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one i1(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_i1(const Packet& x) { + return numext::bessel_i1(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one i1e(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_i1e(const Packet& x) { + return numext::bessel_i1e(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero j0(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_j0(const Packet& x) { + return numext::bessel_j0(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero j1(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_j1(const Packet& x) { + return numext::bessel_j1(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one y0(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_y0(const Packet& x) { + return numext::bessel_y0(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one y1(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_y1(const Packet& x) { + return numext::bessel_y1(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero k0(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_k0(const Packet& x) { + return numext::bessel_k0(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order zero k0e(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_k0e(const Packet& x) { + return numext::bessel_k0e(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one k1e(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_k1(const Packet& x) { + return numext::bessel_k1(x); +} + +/** \internal \returns the exponentially scaled modified Bessel function of + * order one k1e(\a a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pbessel_k1e(const Packet& x) { + return numext::bessel_k1e(x); +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_BESSELFUNCTIONS_PACKETMATH_H + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/HipVectorCompatibility.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/HipVectorCompatibility.h new file mode 100644 index 0000000000000000000000000000000000000000..bc6f912030cf148f080fe3d3a1c76243d371d9cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/HipVectorCompatibility.h @@ -0,0 +1,69 @@ +#ifndef HIP_VECTOR_COMPATIBILITY_H +#define HIP_VECTOR_COMPATIBILITY_H + +namespace hip_impl { + template struct Scalar_accessor; +} // end namespace hip_impl + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +#define HIP_SCALAR_ACCESSOR_BUILDER(NAME) \ +template \ +struct NAME > : NAME {}; + +#define HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(NAME) \ +template \ +struct NAME##_impl > : NAME##_impl {}; \ +template \ +struct NAME##_retval > : NAME##_retval {}; + +#define HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(NAME) \ +template \ +struct NAME , mode> : NAME {}; + +#if EIGEN_HAS_C99_MATH +HIP_SCALAR_ACCESSOR_BUILDER(betainc_helper) +HIP_SCALAR_ACCESSOR_BUILDER(incbeta_cfe) + +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(erf) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(erfc) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igammac) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(lgamma) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(ndtri) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(polygamma) + +HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igamma_generic_impl) +#endif + +HIP_SCALAR_ACCESSOR_BUILDER(digamma_impl_maybe_poly) +HIP_SCALAR_ACCESSOR_BUILDER(zeta_impl_series) + +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i0) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i0e) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i1) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i1e) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_j0) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_j1) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k0) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k0e) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k1) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k1e) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_y0) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_y1) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(betainc) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(digamma) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(gamma_sample_der_alpha) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igamma_der_a) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igamma) +HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(zeta) + +HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igamma_series_impl) +HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igammac_cf_impl) + +} // end namespace internal +} // end namespace Eigen + +#endif // HIP_VECTOR_COMPATIBILITY_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..c80ebd81d9badaa3baf6052853947f444f3c2b16 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_SPECIALFUNCTIONS_MODULE_H +#error "Please include unsupported/Eigen/SpecialFunctions instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsArrayAPI.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsArrayAPI.h new file mode 100644 index 0000000000000000000000000000000000000000..4429333bc3b5ca194ff3b88459fec10f7b684b6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsArrayAPI.h @@ -0,0 +1,169 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_SPECIALFUNCTIONS_ARRAYAPI_H +#define EIGEN_SPECIALFUNCTIONS_ARRAYAPI_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +/** \cpp11 \returns an expression of the coefficient-wise igamma(\a a, \a x) to the given arrays. + * + * This function computes the coefficient-wise incomplete gamma function. + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of igammac(T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::igammac(), Eigen::lgamma() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const Derived, const ExponentDerived> +igamma(const Eigen::ArrayBase& a, const Eigen::ArrayBase& x) +{ + return Eigen::CwiseBinaryOp, const Derived, const ExponentDerived>( + a.derived(), + x.derived() + ); +} + +/** \cpp11 \returns an expression of the coefficient-wise igamma_der_a(\a a, \a x) to the given arrays. + * + * This function computes the coefficient-wise derivative of the incomplete + * gamma function with respect to the parameter a. + * + * \note This function supports only float and double scalar types in c++11 + * mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations + * of igamma_der_a(T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::igamma(), Eigen::lgamma() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const Derived, const ExponentDerived> +igamma_der_a(const Eigen::ArrayBase& a, const Eigen::ArrayBase& x) { + return Eigen::CwiseBinaryOp, const Derived, const ExponentDerived>( + a.derived(), + x.derived()); +} + +/** \cpp11 \returns an expression of the coefficient-wise gamma_sample_der_alpha(\a alpha, \a sample) to the given arrays. + * + * This function computes the coefficient-wise derivative of the sample + * of a Gamma(alpha, 1) random variable with respect to the parameter alpha. + * + * \note This function supports only float and double scalar types in c++11 + * mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations + * of gamma_sample_der_alpha(T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::igamma(), Eigen::lgamma() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const AlphaDerived, const SampleDerived> +gamma_sample_der_alpha(const Eigen::ArrayBase& alpha, const Eigen::ArrayBase& sample) { + return Eigen::CwiseBinaryOp, const AlphaDerived, const SampleDerived>( + alpha.derived(), + sample.derived()); +} + +/** \cpp11 \returns an expression of the coefficient-wise igammac(\a a, \a x) to the given arrays. + * + * This function computes the coefficient-wise complementary incomplete gamma function. + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of igammac(T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::igamma(), Eigen::lgamma() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const Derived, const ExponentDerived> +igammac(const Eigen::ArrayBase& a, const Eigen::ArrayBase& x) +{ + return Eigen::CwiseBinaryOp, const Derived, const ExponentDerived>( + a.derived(), + x.derived() + ); +} + +/** \cpp11 \returns an expression of the coefficient-wise polygamma(\a n, \a x) to the given arrays. + * + * It returns the \a n -th derivative of the digamma(psi) evaluated at \c x. + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of polygamma(T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::digamma() + */ +// * \warning Be careful with the order of the parameters: x.polygamma(n) is equivalent to polygamma(n,x) +// * \sa ArrayBase::polygamma() +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const DerivedN, const DerivedX> +polygamma(const Eigen::ArrayBase& n, const Eigen::ArrayBase& x) +{ + return Eigen::CwiseBinaryOp, const DerivedN, const DerivedX>( + n.derived(), + x.derived() + ); +} + +/** \cpp11 \returns an expression of the coefficient-wise betainc(\a x, \a a, \a b) to the given arrays. + * + * This function computes the regularized incomplete beta function (integral). + * + * \note This function supports only float and double scalar types in c++11 mode. To support other scalar types, + * or float/double in non c++11 mode, the user has to provide implementations of betainc(T,T,T) for any scalar + * type T to be supported. + * + * \sa Eigen::betainc(), Eigen::lgamma() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseTernaryOp, const ArgADerived, const ArgBDerived, const ArgXDerived> +betainc(const Eigen::ArrayBase& a, const Eigen::ArrayBase& b, const Eigen::ArrayBase& x) +{ + return Eigen::CwiseTernaryOp, const ArgADerived, const ArgBDerived, const ArgXDerived>( + a.derived(), + b.derived(), + x.derived() + ); +} + + +/** \returns an expression of the coefficient-wise zeta(\a x, \a q) to the given arrays. + * + * It returns the Riemann zeta function of two arguments \a x and \a q: + * + * \param x is the exponent, it must be > 1 + * \param q is the shift, it must be > 0 + * + * \note This function supports only float and double scalar types. To support other scalar types, the user has + * to provide implementations of zeta(T,T) for any scalar type T to be supported. + * + * \sa ArrayBase::zeta() + */ +template +EIGEN_STRONG_INLINE const Eigen::CwiseBinaryOp, const DerivedX, const DerivedQ> +zeta(const Eigen::ArrayBase& x, const Eigen::ArrayBase& q) +{ + return Eigen::CwiseBinaryOp, const DerivedX, const DerivedQ>( + x.derived(), + q.derived() + ); +} + + +} // end namespace Eigen + +#endif // EIGEN_SPECIALFUNCTIONS_ARRAYAPI_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsBFloat16.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsBFloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..56e0b958477bec363a5edc81f076889f911aa78c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsBFloat16.h @@ -0,0 +1,60 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIALFUNCTIONS_BFLOAT16_H +#define EIGEN_SPECIALFUNCTIONS_BFLOAT16_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace numext { + +#if EIGEN_HAS_C99_MATH +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 lgamma(const Eigen::bfloat16& a) { + return Eigen::bfloat16(Eigen::numext::lgamma(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 digamma(const Eigen::bfloat16& a) { + return Eigen::bfloat16(Eigen::numext::digamma(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 zeta(const Eigen::bfloat16& x, const Eigen::bfloat16& q) { + return Eigen::bfloat16(Eigen::numext::zeta(static_cast(x), static_cast(q))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 polygamma(const Eigen::bfloat16& n, const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::polygamma(static_cast(n), static_cast(x))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 erf(const Eigen::bfloat16& a) { + return Eigen::bfloat16(Eigen::numext::erf(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 erfc(const Eigen::bfloat16& a) { + return Eigen::bfloat16(Eigen::numext::erfc(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 ndtri(const Eigen::bfloat16& a) { + return Eigen::bfloat16(Eigen::numext::ndtri(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 igamma(const Eigen::bfloat16& a, const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::igamma(static_cast(a), static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 igamma_der_a(const Eigen::bfloat16& a, const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::igamma_der_a(static_cast(a), static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 gamma_sample_der_alpha(const Eigen::bfloat16& alpha, const Eigen::bfloat16& sample) { + return Eigen::bfloat16(Eigen::numext::gamma_sample_der_alpha(static_cast(alpha), static_cast(sample))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 igammac(const Eigen::bfloat16& a, const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::igammac(static_cast(a), static_cast(x))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 betainc(const Eigen::bfloat16& a, const Eigen::bfloat16& b, const Eigen::bfloat16& x) { + return Eigen::bfloat16(Eigen::numext::betainc(static_cast(a), static_cast(b), static_cast(x))); +} +#endif + +} // end namespace numext +} // end namespace Eigen + +#endif // EIGEN_SPECIALFUNCTIONS_BFLOAT16_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h new file mode 100644 index 0000000000000000000000000000000000000000..0955c436d3cd90772dee5cd1820840910be2be75 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h @@ -0,0 +1,320 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Eugene Brevdo +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIALFUNCTIONS_FUNCTORS_H +#define EIGEN_SPECIALFUNCTIONS_FUNCTORS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + + +/** \internal + * \brief Template functor to compute the incomplete gamma function igamma(a, x) + * + * \sa class CwiseBinaryOp, Cwise::igamma + */ +template struct scalar_igamma_op : binary_op_base +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const { + using numext::igamma; return igamma(a, x); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const { + return internal::pigamma(a, x); + } +}; +template +struct functor_traits > { + enum { + // Guesstimate + Cost = 20 * NumTraits::MulCost + 10 * NumTraits::AddCost, + PacketAccess = packet_traits::HasIGamma + }; +}; + +/** \internal + * \brief Template functor to compute the derivative of the incomplete gamma + * function igamma_der_a(a, x) + * + * \sa class CwiseBinaryOp, Cwise::igamma_der_a + */ +template +struct scalar_igamma_der_a_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& a, const Scalar& x) const { + using numext::igamma_der_a; + return igamma_der_a(a, x); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const { + return internal::pigamma_der_a(a, x); + } +}; +template +struct functor_traits > { + enum { + // 2x the cost of igamma + Cost = 40 * NumTraits::MulCost + 20 * NumTraits::AddCost, + PacketAccess = packet_traits::HasIGammaDerA + }; +}; + +/** \internal + * \brief Template functor to compute the derivative of the sample + * of a Gamma(alpha, 1) random variable with respect to the parameter alpha + * gamma_sample_der_alpha(alpha, sample) + * + * \sa class CwiseBinaryOp, Cwise::gamma_sample_der_alpha + */ +template +struct scalar_gamma_sample_der_alpha_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& alpha, const Scalar& sample) const { + using numext::gamma_sample_der_alpha; + return gamma_sample_der_alpha(alpha, sample); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& alpha, const Packet& sample) const { + return internal::pgamma_sample_der_alpha(alpha, sample); + } +}; +template +struct functor_traits > { + enum { + // 2x the cost of igamma, minus the lgamma cost (the lgamma cancels out) + Cost = 30 * NumTraits::MulCost + 15 * NumTraits::AddCost, + PacketAccess = packet_traits::HasGammaSampleDerAlpha + }; +}; + +/** \internal + * \brief Template functor to compute the complementary incomplete gamma function igammac(a, x) + * + * \sa class CwiseBinaryOp, Cwise::igammac + */ +template struct scalar_igammac_op : binary_op_base +{ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const { + using numext::igammac; return igammac(a, x); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const + { + return internal::pigammac(a, x); + } +}; +template +struct functor_traits > { + enum { + // Guesstimate + Cost = 20 * NumTraits::MulCost + 10 * NumTraits::AddCost, + PacketAccess = packet_traits::HasIGammac + }; +}; + + +/** \internal + * \brief Template functor to compute the incomplete beta integral betainc(a, b, x) + * + */ +template struct scalar_betainc_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& x, const Scalar& a, const Scalar& b) const { + using numext::betainc; return betainc(x, a, b); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& x, const Packet& a, const Packet& b) const + { + return internal::pbetainc(x, a, b); + } +}; +template +struct functor_traits > { + enum { + // Guesstimate + Cost = 400 * NumTraits::MulCost + 400 * NumTraits::AddCost, + PacketAccess = packet_traits::HasBetaInc + }; +}; + + +/** \internal + * \brief Template functor to compute the natural log of the absolute + * value of Gamma of a scalar + * \sa class CwiseUnaryOp, Cwise::lgamma() + */ +template struct scalar_lgamma_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { + using numext::lgamma; return lgamma(a); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { return internal::plgamma(a); } +}; +template +struct functor_traits > +{ + enum { + // Guesstimate + Cost = 10 * NumTraits::MulCost + 5 * NumTraits::AddCost, + PacketAccess = packet_traits::HasLGamma + }; +}; + +/** \internal + * \brief Template functor to compute psi, the derivative of lgamma of a scalar. + * \sa class CwiseUnaryOp, Cwise::digamma() + */ +template struct scalar_digamma_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { + using numext::digamma; return digamma(a); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { return internal::pdigamma(a); } +}; +template +struct functor_traits > +{ + enum { + // Guesstimate + Cost = 10 * NumTraits::MulCost + 5 * NumTraits::AddCost, + PacketAccess = packet_traits::HasDiGamma + }; +}; + +/** \internal + * \brief Template functor to compute the Riemann Zeta function of two arguments. + * \sa class CwiseUnaryOp, Cwise::zeta() + */ +template struct scalar_zeta_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& x, const Scalar& q) const { + using numext::zeta; return zeta(x, q); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x, const Packet& q) const { return internal::pzeta(x, q); } +}; +template +struct functor_traits > +{ + enum { + // Guesstimate + Cost = 10 * NumTraits::MulCost + 5 * NumTraits::AddCost, + PacketAccess = packet_traits::HasZeta + }; +}; + +/** \internal + * \brief Template functor to compute the polygamma function. + * \sa class CwiseUnaryOp, Cwise::polygamma() + */ +template struct scalar_polygamma_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& n, const Scalar& x) const { + using numext::polygamma; return polygamma(n, x); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& n, const Packet& x) const { return internal::ppolygamma(n, x); } +}; +template +struct functor_traits > +{ + enum { + // Guesstimate + Cost = 10 * NumTraits::MulCost + 5 * NumTraits::AddCost, + PacketAccess = packet_traits::HasPolygamma + }; +}; + +/** \internal + * \brief Template functor to compute the error function of a scalar + * \sa class CwiseUnaryOp, ArrayBase::erf() + */ +template struct scalar_erf_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar + operator()(const Scalar& a) const { + return numext::erf(a); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const { + return perf(x); + } +}; +template +struct functor_traits > { + enum { + PacketAccess = packet_traits::HasErf, + Cost = + (PacketAccess +#ifdef EIGEN_VECTORIZE_FMA + // TODO(rmlarsen): Move the FMA cost model to a central location. + // Haswell can issue 2 add/mul/madd per cycle. + // 10 pmadd, 2 pmul, 1 div, 2 other + ? (2 * NumTraits::AddCost + + 7 * NumTraits::MulCost + + scalar_div_cost::HasDiv>::value) +#else + ? (12 * NumTraits::AddCost + + 12 * NumTraits::MulCost + + scalar_div_cost::HasDiv>::value) +#endif + // Assume for simplicity that this is as expensive as an exp(). + : (functor_traits >::Cost)) + }; +}; + +/** \internal + * \brief Template functor to compute the Complementary Error Function + * of a scalar + * \sa class CwiseUnaryOp, Cwise::erfc() + */ +template struct scalar_erfc_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { + using numext::erfc; return erfc(a); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { return internal::perfc(a); } +}; +template +struct functor_traits > +{ + enum { + // Guesstimate + Cost = 10 * NumTraits::MulCost + 5 * NumTraits::AddCost, + PacketAccess = packet_traits::HasErfc + }; +}; + +/** \internal + * \brief Template functor to compute the Inverse of the normal distribution + * function of a scalar + * \sa class CwiseUnaryOp, Cwise::ndtri() + */ +template struct scalar_ndtri_op { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const { + using numext::ndtri; return ndtri(a); + } + typedef typename packet_traits::type Packet; + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { return internal::pndtri(a); } +}; +template +struct functor_traits > +{ + enum { + // On average, We are evaluating rational functions with degree N=9 in the + // numerator and denominator. This results in 2*N additions and 2*N + // multiplications. + Cost = 18 * NumTraits::MulCost + 18 * NumTraits::AddCost, + PacketAccess = packet_traits::HasNdtri + }; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPECIALFUNCTIONS_FUNCTORS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsHalf.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsHalf.h new file mode 100644 index 0000000000000000000000000000000000000000..4b8a35f6aad03966701e455ed5f09af3e057db34 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsHalf.h @@ -0,0 +1,60 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIALFUNCTIONS_HALF_H +#define EIGEN_SPECIALFUNCTIONS_HALF_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace numext { + +#if EIGEN_HAS_C99_MATH +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half lgamma(const Eigen::half& a) { + return Eigen::half(Eigen::numext::lgamma(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half digamma(const Eigen::half& a) { + return Eigen::half(Eigen::numext::digamma(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half zeta(const Eigen::half& x, const Eigen::half& q) { + return Eigen::half(Eigen::numext::zeta(static_cast(x), static_cast(q))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half polygamma(const Eigen::half& n, const Eigen::half& x) { + return Eigen::half(Eigen::numext::polygamma(static_cast(n), static_cast(x))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half erf(const Eigen::half& a) { + return Eigen::half(Eigen::numext::erf(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half erfc(const Eigen::half& a) { + return Eigen::half(Eigen::numext::erfc(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half ndtri(const Eigen::half& a) { + return Eigen::half(Eigen::numext::ndtri(static_cast(a))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half igamma(const Eigen::half& a, const Eigen::half& x) { + return Eigen::half(Eigen::numext::igamma(static_cast(a), static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half igamma_der_a(const Eigen::half& a, const Eigen::half& x) { + return Eigen::half(Eigen::numext::igamma_der_a(static_cast(a), static_cast(x))); +} +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half gamma_sample_der_alpha(const Eigen::half& alpha, const Eigen::half& sample) { + return Eigen::half(Eigen::numext::gamma_sample_der_alpha(static_cast(alpha), static_cast(sample))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half igammac(const Eigen::half& a, const Eigen::half& x) { + return Eigen::half(Eigen::numext::igammac(static_cast(a), static_cast(x))); +} +template<> EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half betainc(const Eigen::half& a, const Eigen::half& b, const Eigen::half& x) { + return Eigen::half(Eigen::numext::betainc(static_cast(a), static_cast(b), static_cast(x))); +} +#endif + +} // end namespace numext +} // end namespace Eigen + +#endif // EIGEN_SPECIALFUNCTIONS_HALF_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..aa514b40ce86c9e4d464afca55a4d527cd0d20e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h @@ -0,0 +1,2052 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Eugene Brevdo +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIAL_FUNCTIONS_H +#define EIGEN_SPECIAL_FUNCTIONS_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { +namespace internal { + +// Parts of this code are based on the Cephes Math Library. +// +// Cephes Math Library Release 2.8: June, 2000 +// Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier +// +// Permission has been kindly provided by the original author +// to incorporate the Cephes software into the Eigen codebase: +// +// From: Stephen Moshier +// To: Eugene Brevdo +// Subject: Re: Permission to wrap several cephes functions in Eigen +// +// Hello Eugene, +// +// Thank you for writing. +// +// If your licensing is similar to BSD, the formal way that has been +// handled is simply to add a statement to the effect that you are incorporating +// the Cephes software by permission of the author. +// +// Good luck with your project, +// Steve + + +/**************************************************************************** + * Implementation of lgamma, requires C++11/C99 * + ****************************************************************************/ + +template +struct lgamma_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { + return Scalar(0); + } +}; + +template +struct lgamma_retval { + typedef Scalar type; +}; + +#if EIGEN_HAS_C99_MATH +// Since glibc 2.19 +#if defined(__GLIBC__) && ((__GLIBC__>=2 && __GLIBC_MINOR__ >= 19) || __GLIBC__>2) \ + && (defined(_DEFAULT_SOURCE) || defined(_BSD_SOURCE) || defined(_SVID_SOURCE)) +#define EIGEN_HAS_LGAMMA_R +#endif + +// Glibc versions before 2.19 +#if defined(__GLIBC__) && ((__GLIBC__==2 && __GLIBC_MINOR__ < 19) || __GLIBC__<2) \ + && (defined(_BSD_SOURCE) || defined(_SVID_SOURCE)) +#define EIGEN_HAS_LGAMMA_R +#endif + +template <> +struct lgamma_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float run(float x) { +#if !defined(EIGEN_GPU_COMPILE_PHASE) && defined (EIGEN_HAS_LGAMMA_R) && !defined(__APPLE__) + int dummy; + return ::lgammaf_r(x, &dummy); +#elif defined(SYCL_DEVICE_ONLY) + return cl::sycl::lgamma(x); +#else + return ::lgammaf(x); +#endif + } +}; + +template <> +struct lgamma_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double run(double x) { +#if !defined(EIGEN_GPU_COMPILE_PHASE) && defined(EIGEN_HAS_LGAMMA_R) && !defined(__APPLE__) + int dummy; + return ::lgamma_r(x, &dummy); +#elif defined(SYCL_DEVICE_ONLY) + return cl::sycl::lgamma(x); +#else + return ::lgamma(x); +#endif + } +}; + +#undef EIGEN_HAS_LGAMMA_R +#endif + +/**************************************************************************** + * Implementation of digamma (psi), based on Cephes * + ****************************************************************************/ + +template +struct digamma_retval { + typedef Scalar type; +}; + +/* + * + * Polynomial evaluation helper for the Psi (digamma) function. + * + * digamma_impl_maybe_poly::run(s) evaluates the asymptotic Psi expansion for + * input Scalar s, assuming s is above 10.0. + * + * If s is above a certain threshold for the given Scalar type, zero + * is returned. Otherwise the polynomial is evaluated with enough + * coefficients for results matching Scalar machine precision. + * + * + */ +template +struct digamma_impl_maybe_poly { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { + return Scalar(0); + } +}; + + +template <> +struct digamma_impl_maybe_poly { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float run(const float s) { + const float A[] = { + -4.16666666666666666667E-3f, + 3.96825396825396825397E-3f, + -8.33333333333333333333E-3f, + 8.33333333333333333333E-2f + }; + + float z; + if (s < 1.0e8f) { + z = 1.0f / (s * s); + return z * internal::ppolevl::run(z, A); + } else return 0.0f; + } +}; + +template <> +struct digamma_impl_maybe_poly { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double run(const double s) { + const double A[] = { + 8.33333333333333333333E-2, + -2.10927960927960927961E-2, + 7.57575757575757575758E-3, + -4.16666666666666666667E-3, + 3.96825396825396825397E-3, + -8.33333333333333333333E-3, + 8.33333333333333333333E-2 + }; + + double z; + if (s < 1.0e17) { + z = 1.0 / (s * s); + return z * internal::ppolevl::run(z, A); + } + else return 0.0; + } +}; + +template +struct digamma_impl { + EIGEN_DEVICE_FUNC + static Scalar run(Scalar x) { + /* + * + * Psi (digamma) function (modified for Eigen) + * + * + * SYNOPSIS: + * + * double x, y, psi(); + * + * y = psi( x ); + * + * + * DESCRIPTION: + * + * d - + * psi(x) = -- ln | (x) + * dx + * + * is the logarithmic derivative of the gamma function. + * For integer x, + * n-1 + * - + * psi(n) = -EUL + > 1/k. + * - + * k=1 + * + * If x is negative, it is transformed to a positive argument by the + * reflection formula psi(1-x) = psi(x) + pi cot(pi x). + * For general positive x, the argument is made greater than 10 + * using the recurrence psi(x+1) = psi(x) + 1/x. + * Then the following asymptotic expansion is applied: + * + * inf. B + * - 2k + * psi(x) = log(x) - 1/2x - > ------- + * - 2k + * k=1 2k x + * + * where the B2k are Bernoulli numbers. + * + * ACCURACY (float): + * Relative error (except absolute when |psi| < 1): + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 1.3e-15 1.4e-16 + * IEEE -30,0 40000 1.5e-15 2.2e-16 + * + * ACCURACY (double): + * Absolute error, relative when |psi| > 1 : + * arithmetic domain # trials peak rms + * IEEE -33,0 30000 8.2e-7 1.2e-7 + * IEEE 0,33 100000 7.3e-7 7.7e-8 + * + * ERROR MESSAGES: + * message condition value returned + * psi singularity x integer <=0 INFINITY + */ + + Scalar p, q, nz, s, w, y; + bool negative = false; + + const Scalar nan = NumTraits::quiet_NaN(); + const Scalar m_pi = Scalar(EIGEN_PI); + + const Scalar zero = Scalar(0); + const Scalar one = Scalar(1); + const Scalar half = Scalar(0.5); + nz = zero; + + if (x <= zero) { + negative = true; + q = x; + p = numext::floor(q); + if (p == q) { + return nan; + } + /* Remove the zeros of tan(m_pi x) + * by subtracting the nearest integer from x + */ + nz = q - p; + if (nz != half) { + if (nz > half) { + p += one; + nz = q - p; + } + nz = m_pi / numext::tan(m_pi * nz); + } + else { + nz = zero; + } + x = one - x; + } + + /* use the recurrence psi(x+1) = psi(x) + 1/x. */ + s = x; + w = zero; + while (s < Scalar(10)) { + w += one / s; + s += one; + } + + y = digamma_impl_maybe_poly::run(s); + + y = numext::log(s) - (half / s) - y - w; + + return (negative) ? y - nz : y; + } +}; + +/**************************************************************************** + * Implementation of erf, requires C++11/C99 * + ****************************************************************************/ + +/** \internal \returns the error function of \a a (coeff-wise) + Doesn't do anything fancy, just a 9/12-degree rational interpolant which + is accurate to 3 ulp for normalized floats in the range [-c;c], where + c = erfinv(1-2^-23), outside of which x should be +/-1 in single precision. + Strictly speaking c should be erfinv(1-2^-24), but we clamp slightly earlier + to avoid returning values greater than 1. + + This implementation works on both scalars and Ts. +*/ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_fast_erf_float(const T& x) { + constexpr float kErfInvOneMinusHalfULP = 3.832506856900711f; + const T clamp = pcmp_le(pset1(kErfInvOneMinusHalfULP), pabs(x)); + // The monomial coefficients of the numerator polynomial (odd). + const T alpha_1 = pset1(1.128379143519084f); + const T alpha_3 = pset1(0.18520832239976145f); + const T alpha_5 = pset1(0.050955695062380861f); + const T alpha_7 = pset1(0.0034082910107109506f); + const T alpha_9 = pset1(0.00022905065861350646f); + + // The monomial coefficients of the denominator polynomial (even). + const T beta_0 = pset1(1.0f); + const T beta_2 = pset1(0.49746925110067538f); + const T beta_4 = pset1(0.11098505178285362f); + const T beta_6 = pset1(0.014070470171167667f); + const T beta_8 = pset1(0.0010179625278914885f); + const T beta_10 = pset1(0.000023547966471313185f); + const T beta_12 = pset1(-1.1791602954361697e-7f); + + // Since the polynomials are odd/even, we need x^2. + const T x2 = pmul(x, x); + + // Evaluate the numerator polynomial p. + T p = pmadd(x2, alpha_9, alpha_7); + p = pmadd(x2, p, alpha_5); + p = pmadd(x2, p, alpha_3); + p = pmadd(x2, p, alpha_1); + p = pmul(x, p); + + // Evaluate the denominator polynomial p. + T q = pmadd(x2, beta_12, beta_10); + q = pmadd(x2, q, beta_8); + q = pmadd(x2, q, beta_6); + q = pmadd(x2, q, beta_4); + q = pmadd(x2, q, beta_2); + q = pmadd(x2, q, beta_0); + + // Divide the numerator by the denominator. + return pselect(clamp, psign(x), pdiv(p, q)); +} + +template +struct erf_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE T run(const T& x) { + return generic_fast_erf_float(x); + } +}; + +template +struct erf_retval { + typedef Scalar type; +}; + +#if EIGEN_HAS_C99_MATH +template <> +struct erf_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float run(float x) { +#if defined(SYCL_DEVICE_ONLY) + return cl::sycl::erf(x); +#else + return generic_fast_erf_float(x); +#endif + } +}; + +template <> +struct erf_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double run(double x) { +#if defined(SYCL_DEVICE_ONLY) + return cl::sycl::erf(x); +#else + return ::erf(x); +#endif + } +}; +#endif // EIGEN_HAS_C99_MATH + +/*************************************************************************** +* Implementation of erfc, requires C++11/C99 * +****************************************************************************/ + +template +struct erfc_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { + return Scalar(0); + } +}; + +template +struct erfc_retval { + typedef Scalar type; +}; + +#if EIGEN_HAS_C99_MATH +template <> +struct erfc_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float run(const float x) { +#if defined(SYCL_DEVICE_ONLY) + return cl::sycl::erfc(x); +#else + return ::erfcf(x); +#endif + } +}; + +template <> +struct erfc_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double run(const double x) { +#if defined(SYCL_DEVICE_ONLY) + return cl::sycl::erfc(x); +#else + return ::erfc(x); +#endif + } +}; +#endif // EIGEN_HAS_C99_MATH + + +/*************************************************************************** +* Implementation of ndtri. * +****************************************************************************/ + +/* Inverse of Normal distribution function (modified for Eigen). + * + * + * SYNOPSIS: + * + * double x, y, ndtri(); + * + * x = ndtri( y ); + * + * + * + * DESCRIPTION: + * + * Returns the argument, x, for which the area under the + * Gaussian probability density function (integrated from + * minus infinity to x) is equal to y. + * + * + * For small arguments 0 < y < exp(-2), the program computes + * z = sqrt( -2.0 * log(y) ); then the approximation is + * x = z - log(z)/z - (1/z) P(1/z) / Q(1/z). + * There are two rational functions P/Q, one for 0 < y < exp(-32) + * and the other for y up to exp(-2). For larger arguments, + * w = y - 0.5, and x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2)). + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * DEC 0.125, 1 5500 9.5e-17 2.1e-17 + * DEC 6e-39, 0.135 3500 5.7e-17 1.3e-17 + * IEEE 0.125, 1 20000 7.2e-16 1.3e-16 + * IEEE 3e-308, 0.135 50000 4.6e-16 9.8e-17 + * + * + * ERROR MESSAGES: + * + * message condition value returned + * ndtri domain x == 0 -INF + * ndtri domain x == 1 INF + * ndtri domain x < 0, x > 1 NAN + */ + /* + Cephes Math Library Release 2.2: June, 1992 + Copyright 1985, 1987, 1992 by Stephen L. Moshier + Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + + +// TODO: Add a cheaper approximation for float. + + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T flipsign( + const T& should_flipsign, const T& x) { + typedef typename unpacket_traits::type Scalar; + const T sign_mask = pset1(Scalar(-0.0)); + T sign_bit = pand(should_flipsign, sign_mask); + return pxor(sign_bit, x); +} + +template<> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double flipsign( + const double& should_flipsign, const double& x) { + return should_flipsign == 0 ? x : -x; +} + +template<> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float flipsign( + const float& should_flipsign, const float& x) { + return should_flipsign == 0 ? x : -x; +} + +// We split this computation in to two so that in the scalar path +// only one branch is evaluated (due to our template specialization of pselect +// being an if statement.) + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_ndtri_gt_exp_neg_two(const T& b) { + const ScalarType p0[] = { + ScalarType(-5.99633501014107895267e1), + ScalarType(9.80010754185999661536e1), + ScalarType(-5.66762857469070293439e1), + ScalarType(1.39312609387279679503e1), + ScalarType(-1.23916583867381258016e0) + }; + const ScalarType q0[] = { + ScalarType(1.0), + ScalarType(1.95448858338141759834e0), + ScalarType(4.67627912898881538453e0), + ScalarType(8.63602421390890590575e1), + ScalarType(-2.25462687854119370527e2), + ScalarType(2.00260212380060660359e2), + ScalarType(-8.20372256168333339912e1), + ScalarType(1.59056225126211695515e1), + ScalarType(-1.18331621121330003142e0) + }; + const T sqrt2pi = pset1(ScalarType(2.50662827463100050242e0)); + const T half = pset1(ScalarType(0.5)); + T c, c2, ndtri_gt_exp_neg_two; + + c = psub(b, half); + c2 = pmul(c, c); + ndtri_gt_exp_neg_two = pmadd(c, pmul( + c2, pdiv( + internal::ppolevl::run(c2, p0), + internal::ppolevl::run(c2, q0))), c); + return pmul(ndtri_gt_exp_neg_two, sqrt2pi); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T generic_ndtri_lt_exp_neg_two( + const T& b, const T& should_flipsign) { + /* Approximation for interval z = sqrt(-2 log a ) between 2 and 8 + * i.e., a between exp(-2) = .135 and exp(-32) = 1.27e-14. + */ + const ScalarType p1[] = { + ScalarType(4.05544892305962419923e0), + ScalarType(3.15251094599893866154e1), + ScalarType(5.71628192246421288162e1), + ScalarType(4.40805073893200834700e1), + ScalarType(1.46849561928858024014e1), + ScalarType(2.18663306850790267539e0), + ScalarType(-1.40256079171354495875e-1), + ScalarType(-3.50424626827848203418e-2), + ScalarType(-8.57456785154685413611e-4) + }; + const ScalarType q1[] = { + ScalarType(1.0), + ScalarType(1.57799883256466749731e1), + ScalarType(4.53907635128879210584e1), + ScalarType(4.13172038254672030440e1), + ScalarType(1.50425385692907503408e1), + ScalarType(2.50464946208309415979e0), + ScalarType(-1.42182922854787788574e-1), + ScalarType(-3.80806407691578277194e-2), + ScalarType(-9.33259480895457427372e-4) + }; + /* Approximation for interval z = sqrt(-2 log a ) between 8 and 64 + * i.e., a between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890. + */ + const ScalarType p2[] = { + ScalarType(3.23774891776946035970e0), + ScalarType(6.91522889068984211695e0), + ScalarType(3.93881025292474443415e0), + ScalarType(1.33303460815807542389e0), + ScalarType(2.01485389549179081538e-1), + ScalarType(1.23716634817820021358e-2), + ScalarType(3.01581553508235416007e-4), + ScalarType(2.65806974686737550832e-6), + ScalarType(6.23974539184983293730e-9) + }; + const ScalarType q2[] = { + ScalarType(1.0), + ScalarType(6.02427039364742014255e0), + ScalarType(3.67983563856160859403e0), + ScalarType(1.37702099489081330271e0), + ScalarType(2.16236993594496635890e-1), + ScalarType(1.34204006088543189037e-2), + ScalarType(3.28014464682127739104e-4), + ScalarType(2.89247864745380683936e-6), + ScalarType(6.79019408009981274425e-9) + }; + const T eight = pset1(ScalarType(8.0)); + const T neg_two = pset1(ScalarType(-2)); + T x, x0, x1, z; + + x = psqrt(pmul(neg_two, plog(b))); + x0 = psub(x, pdiv(plog(x), x)); + z = preciprocal(x); + x1 = pmul( + z, pselect( + pcmp_lt(x, eight), + pdiv(internal::ppolevl::run(z, p1), + internal::ppolevl::run(z, q1)), + pdiv(internal::ppolevl::run(z, p2), + internal::ppolevl::run(z, q2)))); + return flipsign(should_flipsign, psub(x0, x1)); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T generic_ndtri(const T& a) { + const T maxnum = pset1(NumTraits::infinity()); + const T neg_maxnum = pset1(-NumTraits::infinity()); + + const T zero = pset1(ScalarType(0)); + const T one = pset1(ScalarType(1)); + // exp(-2) + const T exp_neg_two = pset1(ScalarType(0.13533528323661269189)); + T b, ndtri, should_flipsign; + + should_flipsign = pcmp_le(a, psub(one, exp_neg_two)); + b = pselect(should_flipsign, a, psub(one, a)); + + ndtri = pselect( + pcmp_lt(exp_neg_two, b), + generic_ndtri_gt_exp_neg_two(b), + generic_ndtri_lt_exp_neg_two(b, should_flipsign)); + + return pselect( + pcmp_eq(a, zero), neg_maxnum, + pselect(pcmp_eq(one, a), maxnum, ndtri)); +} + +template +struct ndtri_retval { + typedef Scalar type; +}; + +#if !EIGEN_HAS_C99_MATH + +template +struct ndtri_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { + return Scalar(0); + } +}; + +# else + +template +struct ndtri_impl { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar run(const Scalar x) { + return generic_ndtri(x); + } +}; + +#endif // EIGEN_HAS_C99_MATH + + +/************************************************************************************************************** + * Implementation of igammac (complemented incomplete gamma integral), based on Cephes but requires C++11/C99 * + **************************************************************************************************************/ + +template +struct igammac_retval { + typedef Scalar type; +}; + +// NOTE: cephes_helper is also used to implement zeta +template +struct cephes_helper { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar machep() { eigen_assert(false && "machep not supported for this type"); return 0.0; } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar big() { eigen_assert(false && "big not supported for this type"); return 0.0; } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar biginv() { eigen_assert(false && "biginv not supported for this type"); return 0.0; } +}; + +template <> +struct cephes_helper { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float machep() { + return NumTraits::epsilon() / 2; // 1.0 - machep == 1.0 + } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float big() { + // use epsneg (1.0 - epsneg == 1.0) + return 1.0f / (NumTraits::epsilon() / 2); + } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float biginv() { + // epsneg + return machep(); + } +}; + +template <> +struct cephes_helper { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double machep() { + return NumTraits::epsilon() / 2; // 1.0 - machep == 1.0 + } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double big() { + return 1.0 / NumTraits::epsilon(); + } + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double biginv() { + // inverse of eps + return NumTraits::epsilon(); + } +}; + +enum IgammaComputationMode { VALUE, DERIVATIVE, SAMPLE_DERIVATIVE }; + +template +EIGEN_DEVICE_FUNC +static EIGEN_STRONG_INLINE Scalar main_igamma_term(Scalar a, Scalar x) { + /* Compute x**a * exp(-x) / gamma(a) */ + Scalar logax = a * numext::log(x) - x - lgamma_impl::run(a); + if (logax < -numext::log(NumTraits::highest()) || + // Assuming x and a aren't Nan. + (numext::isnan)(logax)) { + return Scalar(0); + } + return numext::exp(logax); +} + +template +EIGEN_DEVICE_FUNC +int igamma_num_iterations() { + /* Returns the maximum number of internal iterations for igamma computation. + */ + if (mode == VALUE) { + return 2000; + } + + if (internal::is_same::value) { + return 200; + } else if (internal::is_same::value) { + return 500; + } else { + return 2000; + } +} + +template +struct igammac_cf_impl { + /* Computes igamc(a, x) or derivative (depending on the mode) + * using the continued fraction expansion of the complementary + * incomplete Gamma function. + * + * Preconditions: + * a > 0 + * x >= 1 + * x >= a + */ + EIGEN_DEVICE_FUNC + static Scalar run(Scalar a, Scalar x) { + const Scalar zero = 0; + const Scalar one = 1; + const Scalar two = 2; + const Scalar machep = cephes_helper::machep(); + const Scalar big = cephes_helper::big(); + const Scalar biginv = cephes_helper::biginv(); + + if ((numext::isinf)(x)) { + return zero; + } + + Scalar ax = main_igamma_term(a, x); + // This is independent of mode. If this value is zero, + // then the function value is zero. If the function value is zero, + // then we are in a neighborhood where the function value evaluates to zero, + // so the derivative is zero. + if (ax == zero) { + return zero; + } + + // continued fraction + Scalar y = one - a; + Scalar z = x + y + one; + Scalar c = zero; + Scalar pkm2 = one; + Scalar qkm2 = x; + Scalar pkm1 = x + one; + Scalar qkm1 = z * x; + Scalar ans = pkm1 / qkm1; + + Scalar dpkm2_da = zero; + Scalar dqkm2_da = zero; + Scalar dpkm1_da = zero; + Scalar dqkm1_da = -x; + Scalar dans_da = (dpkm1_da - ans * dqkm1_da) / qkm1; + + for (int i = 0; i < igamma_num_iterations(); i++) { + c += one; + y += one; + z += two; + + Scalar yc = y * c; + Scalar pk = pkm1 * z - pkm2 * yc; + Scalar qk = qkm1 * z - qkm2 * yc; + + Scalar dpk_da = dpkm1_da * z - pkm1 - dpkm2_da * yc + pkm2 * c; + Scalar dqk_da = dqkm1_da * z - qkm1 - dqkm2_da * yc + qkm2 * c; + + if (qk != zero) { + Scalar ans_prev = ans; + ans = pk / qk; + + Scalar dans_da_prev = dans_da; + dans_da = (dpk_da - ans * dqk_da) / qk; + + if (mode == VALUE) { + if (numext::abs(ans_prev - ans) <= machep * numext::abs(ans)) { + break; + } + } else { + if (numext::abs(dans_da - dans_da_prev) <= machep) { + break; + } + } + } + + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + + dpkm2_da = dpkm1_da; + dpkm1_da = dpk_da; + dqkm2_da = dqkm1_da; + dqkm1_da = dqk_da; + + if (numext::abs(pk) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + + dpkm2_da *= biginv; + dpkm1_da *= biginv; + dqkm2_da *= biginv; + dqkm1_da *= biginv; + } + } + + /* Compute x**a * exp(-x) / gamma(a) */ + Scalar dlogax_da = numext::log(x) - digamma_impl::run(a); + Scalar dax_da = ax * dlogax_da; + + switch (mode) { + case VALUE: + return ans * ax; + case DERIVATIVE: + return ans * dax_da + dans_da * ax; + case SAMPLE_DERIVATIVE: + default: // this is needed to suppress clang warning + return -(dans_da + ans * dlogax_da) * x; + } + } +}; + +template +struct igamma_series_impl { + /* Computes igam(a, x) or its derivative (depending on the mode) + * using the series expansion of the incomplete Gamma function. + * + * Preconditions: + * x > 0 + * a > 0 + * !(x > 1 && x > a) + */ + EIGEN_DEVICE_FUNC + static Scalar run(Scalar a, Scalar x) { + const Scalar zero = 0; + const Scalar one = 1; + const Scalar machep = cephes_helper::machep(); + + Scalar ax = main_igamma_term(a, x); + + // This is independent of mode. If this value is zero, + // then the function value is zero. If the function value is zero, + // then we are in a neighborhood where the function value evaluates to zero, + // so the derivative is zero. + if (ax == zero) { + return zero; + } + + ax /= a; + + /* power series */ + Scalar r = a; + Scalar c = one; + Scalar ans = one; + + Scalar dc_da = zero; + Scalar dans_da = zero; + + for (int i = 0; i < igamma_num_iterations(); i++) { + r += one; + Scalar term = x / r; + Scalar dterm_da = -x / (r * r); + dc_da = term * dc_da + dterm_da * c; + dans_da += dc_da; + c *= term; + ans += c; + + if (mode == VALUE) { + if (c <= machep * ans) { + break; + } + } else { + if (numext::abs(dc_da) <= machep * numext::abs(dans_da)) { + break; + } + } + } + + Scalar dlogax_da = numext::log(x) - digamma_impl::run(a + one); + Scalar dax_da = ax * dlogax_da; + + switch (mode) { + case VALUE: + return ans * ax; + case DERIVATIVE: + return ans * dax_da + dans_da * ax; + case SAMPLE_DERIVATIVE: + default: // this is needed to suppress clang warning + return -(dans_da + ans * dlogax_da) * x / a; + } + } +}; + +#if !EIGEN_HAS_C99_MATH + +template +struct igammac_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static Scalar run(Scalar a, Scalar x) { + return Scalar(0); + } +}; + +#else + +template +struct igammac_impl { + EIGEN_DEVICE_FUNC + static Scalar run(Scalar a, Scalar x) { + /* igamc() + * + * Incomplete gamma integral (modified for Eigen) + * + * + * + * SYNOPSIS: + * + * double a, x, y, igamc(); + * + * y = igamc( a, x ); + * + * DESCRIPTION: + * + * The function is defined by + * + * + * igamc(a,x) = 1 - igam(a,x) + * + * inf. + * - + * 1 | | -t a-1 + * = ----- | e t dt. + * - | | + * | (a) - + * x + * + * + * In this implementation both arguments must be positive. + * The integral is evaluated by either a power series or + * continued fraction expansion, depending on the relative + * values of a and x. + * + * ACCURACY (float): + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 7.8e-6 5.9e-7 + * + * + * ACCURACY (double): + * + * Tested at random a, x. + * a x Relative error: + * arithmetic domain domain # trials peak rms + * IEEE 0.5,100 0,100 200000 1.9e-14 1.7e-15 + * IEEE 0.01,0.5 0,100 200000 1.4e-13 1.6e-15 + * + */ + /* + Cephes Math Library Release 2.2: June, 1992 + Copyright 1985, 1987, 1992 by Stephen L. Moshier + Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + const Scalar zero = 0; + const Scalar one = 1; + const Scalar nan = NumTraits::quiet_NaN(); + + if ((x < zero) || (a <= zero)) { + // domain error + return nan; + } + + if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans + return nan; + } + + if ((x < one) || (x < a)) { + return (one - igamma_series_impl::run(a, x)); + } + + return igammac_cf_impl::run(a, x); + } +}; + +#endif // EIGEN_HAS_C99_MATH + +/************************************************************************************************ + * Implementation of igamma (incomplete gamma integral), based on Cephes but requires C++11/C99 * + ************************************************************************************************/ + +#if !EIGEN_HAS_C99_MATH + +template +struct igamma_generic_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar a, Scalar x) { + return Scalar(0); + } +}; + +#else + +template +struct igamma_generic_impl { + EIGEN_DEVICE_FUNC + static Scalar run(Scalar a, Scalar x) { + /* Depending on the mode, returns + * - VALUE: incomplete Gamma function igamma(a, x) + * - DERIVATIVE: derivative of incomplete Gamma function d/da igamma(a, x) + * - SAMPLE_DERIVATIVE: implicit derivative of a Gamma random variable + * x ~ Gamma(x | a, 1), dx/da = -1 / Gamma(x | a, 1) * d igamma(a, x) / dx + * + * Derivatives are implemented by forward-mode differentiation. + */ + const Scalar zero = 0; + const Scalar one = 1; + const Scalar nan = NumTraits::quiet_NaN(); + + if (x == zero) return zero; + + if ((x < zero) || (a <= zero)) { // domain error + return nan; + } + + if ((numext::isnan)(a) || (numext::isnan)(x)) { // propagate nans + return nan; + } + + if ((x > one) && (x > a)) { + Scalar ret = igammac_cf_impl::run(a, x); + if (mode == VALUE) { + return one - ret; + } else { + return -ret; + } + } + + return igamma_series_impl::run(a, x); + } +}; + +#endif // EIGEN_HAS_C99_MATH + +template +struct igamma_retval { + typedef Scalar type; +}; + +template +struct igamma_impl : igamma_generic_impl { + /* igam() + * Incomplete gamma integral. + * + * The CDF of Gamma(a, 1) random variable at the point x. + * + * Accuracy estimation. For each a in [10^-2, 10^-1...10^3] we sample + * 50 Gamma random variables x ~ Gamma(x | a, 1), a total of 300 points. + * The ground truth is computed by mpmath. Mean absolute error: + * float: 1.26713e-05 + * double: 2.33606e-12 + * + * Cephes documentation below. + * + * SYNOPSIS: + * + * double a, x, y, igam(); + * + * y = igam( a, x ); + * + * DESCRIPTION: + * + * The function is defined by + * + * x + * - + * 1 | | -t a-1 + * igam(a,x) = ----- | e t dt. + * - | | + * | (a) - + * 0 + * + * + * In this implementation both arguments must be positive. + * The integral is evaluated by either a power series or + * continued fraction expansion, depending on the relative + * values of a and x. + * + * ACCURACY (double): + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 200000 3.6e-14 2.9e-15 + * IEEE 0,100 300000 9.9e-14 1.5e-14 + * + * + * ACCURACY (float): + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 20000 7.8e-6 5.9e-7 + * + */ + /* + Cephes Math Library Release 2.2: June, 1992 + Copyright 1985, 1987, 1992 by Stephen L. Moshier + Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + + /* left tail of incomplete gamma function: + * + * inf. k + * a -x - x + * x e > ---------- + * - - + * k=0 | (a+k+1) + * + */ +}; + +template +struct igamma_der_a_retval : igamma_retval {}; + +template +struct igamma_der_a_impl : igamma_generic_impl { + /* Derivative of the incomplete Gamma function with respect to a. + * + * Computes d/da igamma(a, x) by forward differentiation of the igamma code. + * + * Accuracy estimation. For each a in [10^-2, 10^-1...10^3] we sample + * 50 Gamma random variables x ~ Gamma(x | a, 1), a total of 300 points. + * The ground truth is computed by mpmath. Mean absolute error: + * float: 6.17992e-07 + * double: 4.60453e-12 + * + * Reference: + * R. Moore. "Algorithm AS 187: Derivatives of the incomplete gamma + * integral". Journal of the Royal Statistical Society. 1982 + */ +}; + +template +struct gamma_sample_der_alpha_retval : igamma_retval {}; + +template +struct gamma_sample_der_alpha_impl + : igamma_generic_impl { + /* Derivative of a Gamma random variable sample with respect to alpha. + * + * Consider a sample of a Gamma random variable with the concentration + * parameter alpha: sample ~ Gamma(alpha, 1). The reparameterization + * derivative that we want to compute is dsample / dalpha = + * d igammainv(alpha, u) / dalpha, where u = igamma(alpha, sample). + * However, this formula is numerically unstable and expensive, so instead + * we use implicit differentiation: + * + * igamma(alpha, sample) = u, where u ~ Uniform(0, 1). + * Apply d / dalpha to both sides: + * d igamma(alpha, sample) / dalpha + * + d igamma(alpha, sample) / dsample * dsample/dalpha = 0 + * d igamma(alpha, sample) / dalpha + * + Gamma(sample | alpha, 1) dsample / dalpha = 0 + * dsample/dalpha = - (d igamma(alpha, sample) / dalpha) + * / Gamma(sample | alpha, 1) + * + * Here Gamma(sample | alpha, 1) is the PDF of the Gamma distribution + * (note that the derivative of the CDF w.r.t. sample is the PDF). + * See the reference below for more details. + * + * The derivative of igamma(alpha, sample) is computed by forward + * differentiation of the igamma code. Division by the Gamma PDF is performed + * in the same code, increasing the accuracy and speed due to cancellation + * of some terms. + * + * Accuracy estimation. For each alpha in [10^-2, 10^-1...10^3] we sample + * 50 Gamma random variables sample ~ Gamma(sample | alpha, 1), a total of 300 + * points. The ground truth is computed by mpmath. Mean absolute error: + * float: 2.1686e-06 + * double: 1.4774e-12 + * + * Reference: + * M. Figurnov, S. Mohamed, A. Mnih "Implicit Reparameterization Gradients". + * 2018 + */ +}; + +/***************************************************************************** + * Implementation of Riemann zeta function of two arguments, based on Cephes * + *****************************************************************************/ + +template +struct zeta_retval { + typedef Scalar type; +}; + +template +struct zeta_impl_series { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Scalar) { + return Scalar(0); + } +}; + +template <> +struct zeta_impl_series { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE bool run(float& a, float& b, float& s, const float x, const float machep) { + int i = 0; + while(i < 9) + { + i += 1; + a += 1.0f; + b = numext::pow( a, -x ); + s += b; + if( numext::abs(b/s) < machep ) + return true; + } + + //Return whether we are done + return false; + } +}; + +template <> +struct zeta_impl_series { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE bool run(double& a, double& b, double& s, const double x, const double machep) { + int i = 0; + while( (i < 9) || (a <= 9.0) ) + { + i += 1; + a += 1.0; + b = numext::pow( a, -x ); + s += b; + if( numext::abs(b/s) < machep ) + return true; + } + + //Return whether we are done + return false; + } +}; + +template +struct zeta_impl { + EIGEN_DEVICE_FUNC + static Scalar run(Scalar x, Scalar q) { + /* zeta.c + * + * Riemann zeta function of two arguments + * + * + * + * SYNOPSIS: + * + * double x, q, y, zeta(); + * + * y = zeta( x, q ); + * + * + * + * DESCRIPTION: + * + * + * + * inf. + * - -x + * zeta(x,q) = > (k+q) + * - + * k=0 + * + * where x > 1 and q is not a negative integer or zero. + * The Euler-Maclaurin summation formula is used to obtain + * the expansion + * + * n + * - -x + * zeta(x,q) = > (k+q) + * - + * k=1 + * + * 1-x inf. B x(x+1)...(x+2j) + * (n+q) 1 - 2j + * + --------- - ------- + > -------------------- + * x-1 x - x+2j+1 + * 2(n+q) j=1 (2j)! (n+q) + * + * where the B2j are Bernoulli numbers. Note that (see zetac.c) + * zeta(x,1) = zetac(x) + 1. + * + * + * + * ACCURACY: + * + * Relative error for single precision: + * arithmetic domain # trials peak rms + * IEEE 0,25 10000 6.9e-7 1.0e-7 + * + * Large arguments may produce underflow in powf(), in which + * case the results are inaccurate. + * + * REFERENCE: + * + * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals, + * Series, and Products, p. 1073; Academic Press, 1980. + * + */ + + int i; + Scalar p, r, a, b, k, s, t, w; + + const Scalar A[] = { + Scalar(12.0), + Scalar(-720.0), + Scalar(30240.0), + Scalar(-1209600.0), + Scalar(47900160.0), + Scalar(-1.8924375803183791606e9), /*1.307674368e12/691*/ + Scalar(7.47242496e10), + Scalar(-2.950130727918164224e12), /*1.067062284288e16/3617*/ + Scalar(1.1646782814350067249e14), /*5.109094217170944e18/43867*/ + Scalar(-4.5979787224074726105e15), /*8.028576626982912e20/174611*/ + Scalar(1.8152105401943546773e17), /*1.5511210043330985984e23/854513*/ + Scalar(-7.1661652561756670113e18) /*1.6938241367317436694528e27/236364091*/ + }; + + const Scalar maxnum = NumTraits::infinity(); + const Scalar zero = Scalar(0.0), half = Scalar(0.5), one = Scalar(1.0); + const Scalar machep = cephes_helper::machep(); + const Scalar nan = NumTraits::quiet_NaN(); + + if( x == one ) + return maxnum; + + if( x < one ) + { + return nan; + } + + if( q <= zero ) + { + if(q == numext::floor(q)) + { + if (x == numext::floor(x) && long(x) % 2 == 0) { + return maxnum; + } + else { + return nan; + } + } + p = x; + r = numext::floor(p); + if (p != r) + return nan; + } + + /* Permit negative q but continue sum until n+q > +9 . + * This case should be handled by a reflection formula. + * If q<0 and x is an integer, there is a relation to + * the polygamma function. + */ + s = numext::pow( q, -x ); + a = q; + b = zero; + // Run the summation in a helper function that is specific to the floating precision + if (zeta_impl_series::run(a, b, s, x, machep)) { + return s; + } + + // If b is zero, then the tail sum will also end up being zero. + // Exiting early here can prevent NaNs for some large inputs, where + // the tail sum computed below has term `a` which can overflow to `inf`. + if (numext::equal_strict(b, zero)) { + return s; + } + + w = a; + s += b*w/(x-one); + s -= half * b; + a = one; + k = zero; + + for( i=0; i<12; i++ ) + { + a *= x + k; + b /= w; + t = a*b/A[i]; + s = s + t; + t = numext::abs(t/s); + if( t < machep ) { + break; + } + k += one; + a *= x + k; + b /= w; + k += one; + } + return s; + } +}; + +/**************************************************************************** + * Implementation of polygamma function, requires C++11/C99 * + ****************************************************************************/ + +template +struct polygamma_retval { + typedef Scalar type; +}; + +#if !EIGEN_HAS_C99_MATH + +template +struct polygamma_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar n, Scalar x) { + return Scalar(0); + } +}; + +#else + +template +struct polygamma_impl { + EIGEN_DEVICE_FUNC + static Scalar run(Scalar n, Scalar x) { + Scalar zero = 0.0, one = 1.0; + Scalar nplus = n + one; + const Scalar nan = NumTraits::quiet_NaN(); + + // Check that n is a non-negative integer + if (numext::floor(n) != n || n < zero) { + return nan; + } + // Just return the digamma function for n = 0 + else if (n == zero) { + return digamma_impl::run(x); + } + // Use the same implementation as scipy + else { + Scalar factorial = numext::exp(lgamma_impl::run(nplus)); + return numext::pow(-one, nplus) * factorial * zeta_impl::run(nplus, x); + } + } +}; + +#endif // EIGEN_HAS_C99_MATH + +/************************************************************************************************ + * Implementation of betainc (incomplete beta integral), based on Cephes but requires C++11/C99 * + ************************************************************************************************/ + +template +struct betainc_retval { + typedef Scalar type; +}; + +#if !EIGEN_HAS_C99_MATH + +template +struct betainc_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar a, Scalar b, Scalar x) { + return Scalar(0); + } +}; + +#else + +template +struct betainc_impl { + EIGEN_STATIC_ASSERT((internal::is_same::value == false), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar, Scalar, Scalar) { + /* betaincf.c + * + * Incomplete beta integral + * + * + * SYNOPSIS: + * + * float a, b, x, y, betaincf(); + * + * y = betaincf( a, b, x ); + * + * + * DESCRIPTION: + * + * Returns incomplete beta integral of the arguments, evaluated + * from zero to x. The function is defined as + * + * x + * - - + * | (a+b) | | a-1 b-1 + * ----------- | t (1-t) dt. + * - - | | + * | (a) | (b) - + * 0 + * + * The domain of definition is 0 <= x <= 1. In this + * implementation a and b are restricted to positive values. + * The integral from x to 1 may be obtained by the symmetry + * relation + * + * 1 - betainc( a, b, x ) = betainc( b, a, 1-x ). + * + * The integral is evaluated by a continued fraction expansion. + * If a < 1, the function calls itself recursively after a + * transformation to increase a to a+1. + * + * ACCURACY (float): + * + * Tested at random points (a,b,x) with a and b in the indicated + * interval and x between 0 and 1. + * + * arithmetic domain # trials peak rms + * Relative error: + * IEEE 0,30 10000 3.7e-5 5.1e-6 + * IEEE 0,100 10000 1.7e-4 2.5e-5 + * The useful domain for relative error is limited by underflow + * of the single precision exponential function. + * Absolute error: + * IEEE 0,30 100000 2.2e-5 9.6e-7 + * IEEE 0,100 10000 6.5e-5 3.7e-6 + * + * Larger errors may occur for extreme ratios of a and b. + * + * ACCURACY (double): + * arithmetic domain # trials peak rms + * IEEE 0,5 10000 6.9e-15 4.5e-16 + * IEEE 0,85 250000 2.2e-13 1.7e-14 + * IEEE 0,1000 30000 5.3e-12 6.3e-13 + * IEEE 0,10000 250000 9.3e-11 7.1e-12 + * IEEE 0,100000 10000 8.7e-10 4.8e-11 + * Outputs smaller than the IEEE gradual underflow threshold + * were excluded from these statistics. + * + * ERROR MESSAGES: + * message condition value returned + * incbet domain x<0, x>1 nan + * incbet underflow nan + */ + return Scalar(0); + } +}; + +/* Continued fraction expansion #1 for incomplete beta integral (small_branch = True) + * Continued fraction expansion #2 for incomplete beta integral (small_branch = False) + */ +template +struct incbeta_cfe { + EIGEN_STATIC_ASSERT((internal::is_same::value || + internal::is_same::value), + THIS_TYPE_IS_NOT_SUPPORTED) + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(Scalar a, Scalar b, Scalar x, bool small_branch) { + const Scalar big = cephes_helper::big(); + const Scalar machep = cephes_helper::machep(); + const Scalar biginv = cephes_helper::biginv(); + + const Scalar zero = 0; + const Scalar one = 1; + const Scalar two = 2; + + Scalar xk, pk, pkm1, pkm2, qk, qkm1, qkm2; + Scalar k1, k2, k3, k4, k5, k6, k7, k8, k26update; + Scalar ans; + int n; + + const int num_iters = (internal::is_same::value) ? 100 : 300; + const Scalar thresh = + (internal::is_same::value) ? machep : Scalar(3) * machep; + Scalar r = (internal::is_same::value) ? zero : one; + + if (small_branch) { + k1 = a; + k2 = a + b; + k3 = a; + k4 = a + one; + k5 = one; + k6 = b - one; + k7 = k4; + k8 = a + two; + k26update = one; + } else { + k1 = a; + k2 = b - one; + k3 = a; + k4 = a + one; + k5 = one; + k6 = a + b; + k7 = a + one; + k8 = a + two; + k26update = -one; + x = x / (one - x); + } + + pkm2 = zero; + qkm2 = one; + pkm1 = one; + qkm1 = one; + ans = one; + n = 0; + + do { + xk = -(x * k1 * k2) / (k3 * k4); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + + xk = (x * k5 * k6) / (k7 * k8); + pk = pkm1 + pkm2 * xk; + qk = qkm1 + qkm2 * xk; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + + if (qk != zero) { + r = pk / qk; + if (numext::abs(ans - r) < numext::abs(r) * thresh) { + return r; + } + ans = r; + } + + k1 += one; + k2 += k26update; + k3 += two; + k4 += two; + k5 += one; + k6 -= k26update; + k7 += two; + k8 += two; + + if ((numext::abs(qk) + numext::abs(pk)) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + } + if ((numext::abs(qk) < biginv) || (numext::abs(pk) < biginv)) { + pkm2 *= big; + pkm1 *= big; + qkm2 *= big; + qkm1 *= big; + } + } while (++n < num_iters); + + return ans; + } +}; + +/* Helper functions depending on the Scalar type */ +template +struct betainc_helper {}; + +template <> +struct betainc_helper { + /* Core implementation, assumes a large (> 1.0) */ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE float incbsa(float aa, float bb, + float xx) { + float ans, a, b, t, x, onemx; + bool reversed_a_b = false; + + onemx = 1.0f - xx; + + /* see if x is greater than the mean */ + if (xx > (aa / (aa + bb))) { + reversed_a_b = true; + a = bb; + b = aa; + t = xx; + x = onemx; + } else { + a = aa; + b = bb; + t = onemx; + x = xx; + } + + /* Choose expansion for optimal convergence */ + if (b > 10.0f) { + if (numext::abs(b * x / a) < 0.3f) { + t = betainc_helper::incbps(a, b, x); + if (reversed_a_b) t = 1.0f - t; + return t; + } + } + + ans = x * (a + b - 2.0f) / (a - 1.0f); + if (ans < 1.0f) { + ans = incbeta_cfe::run(a, b, x, true /* small_branch */); + t = b * numext::log(t); + } else { + ans = incbeta_cfe::run(a, b, x, false /* small_branch */); + t = (b - 1.0f) * numext::log(t); + } + + t += a * numext::log(x) + lgamma_impl::run(a + b) - + lgamma_impl::run(a) - lgamma_impl::run(b); + t += numext::log(ans / a); + t = numext::exp(t); + + if (reversed_a_b) t = 1.0f - t; + return t; + } + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE float incbps(float a, float b, float x) { + float t, u, y, s; + const float machep = cephes_helper::machep(); + + y = a * numext::log(x) + (b - 1.0f) * numext::log1p(-x) - numext::log(a); + y -= lgamma_impl::run(a) + lgamma_impl::run(b); + y += lgamma_impl::run(a + b); + + t = x / (1.0f - x); + s = 0.0f; + u = 1.0f; + do { + b -= 1.0f; + if (b == 0.0f) { + break; + } + a += 1.0f; + u *= t * b / a; + s += u; + } while (numext::abs(u) > machep); + + return numext::exp(y) * (1.0f + s); + } +}; + +template <> +struct betainc_impl { + EIGEN_DEVICE_FUNC + static float run(float a, float b, float x) { + const float nan = NumTraits::quiet_NaN(); + float ans, t; + + if (a <= 0.0f) return nan; + if (b <= 0.0f) return nan; + if ((x <= 0.0f) || (x >= 1.0f)) { + if (x == 0.0f) return 0.0f; + if (x == 1.0f) return 1.0f; + // mtherr("betaincf", DOMAIN); + return nan; + } + + /* transformation for small aa */ + if (a <= 1.0f) { + ans = betainc_helper::incbsa(a + 1.0f, b, x); + t = a * numext::log(x) + b * numext::log1p(-x) + + lgamma_impl::run(a + b) - lgamma_impl::run(a + 1.0f) - + lgamma_impl::run(b); + return (ans + numext::exp(t)); + } else { + return betainc_helper::incbsa(a, b, x); + } + } +}; + +template <> +struct betainc_helper { + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE double incbps(double a, double b, double x) { + const double machep = cephes_helper::machep(); + + double s, t, u, v, n, t1, z, ai; + + ai = 1.0 / a; + u = (1.0 - b) * x; + v = u / (a + 1.0); + t1 = v; + t = u; + n = 2.0; + s = 0.0; + z = machep * ai; + while (numext::abs(v) > z) { + u = (n - b) * x / n; + t *= u; + v = t / (a + n); + s += v; + n += 1.0; + } + s += t1; + s += ai; + + u = a * numext::log(x); + // TODO: gamma() is not directly implemented in Eigen. + /* + if ((a + b) < maxgam && numext::abs(u) < maxlog) { + t = gamma(a + b) / (gamma(a) * gamma(b)); + s = s * t * pow(x, a); + } + */ + t = lgamma_impl::run(a + b) - lgamma_impl::run(a) - + lgamma_impl::run(b) + u + numext::log(s); + return s = numext::exp(t); + } +}; + +template <> +struct betainc_impl { + EIGEN_DEVICE_FUNC + static double run(double aa, double bb, double xx) { + const double nan = NumTraits::quiet_NaN(); + const double machep = cephes_helper::machep(); + // const double maxgam = 171.624376956302725; + + double a, b, t, x, xc, w, y; + bool reversed_a_b = false; + + if (aa <= 0.0 || bb <= 0.0) { + return nan; // goto domerr; + } + + if ((xx <= 0.0) || (xx >= 1.0)) { + if (xx == 0.0) return (0.0); + if (xx == 1.0) return (1.0); + // mtherr("incbet", DOMAIN); + return nan; + } + + if ((bb * xx) <= 1.0 && xx <= 0.95) { + return betainc_helper::incbps(aa, bb, xx); + } + + w = 1.0 - xx; + + /* Reverse a and b if x is greater than the mean. */ + if (xx > (aa / (aa + bb))) { + reversed_a_b = true; + a = bb; + b = aa; + xc = xx; + x = w; + } else { + a = aa; + b = bb; + xc = w; + x = xx; + } + + if (reversed_a_b && (b * x) <= 1.0 && x <= 0.95) { + t = betainc_helper::incbps(a, b, x); + if (t <= machep) { + t = 1.0 - machep; + } else { + t = 1.0 - t; + } + return t; + } + + /* Choose expansion for better convergence. */ + y = x * (a + b - 2.0) - (a - 1.0); + if (y < 0.0) { + w = incbeta_cfe::run(a, b, x, true /* small_branch */); + } else { + w = incbeta_cfe::run(a, b, x, false /* small_branch */) / xc; + } + + /* Multiply w by the factor + a b _ _ _ + x (1-x) | (a+b) / ( a | (a) | (b) ) . */ + + y = a * numext::log(x); + t = b * numext::log(xc); + // TODO: gamma is not directly implemented in Eigen. + /* + if ((a + b) < maxgam && numext::abs(y) < maxlog && numext::abs(t) < maxlog) + { + t = pow(xc, b); + t *= pow(x, a); + t /= a; + t *= w; + t *= gamma(a + b) / (gamma(a) * gamma(b)); + } else { + */ + /* Resort to logarithms. */ + y += t + lgamma_impl::run(a + b) - lgamma_impl::run(a) - + lgamma_impl::run(b); + y += numext::log(w / a); + t = numext::exp(y); + + /* } */ + // done: + + if (reversed_a_b) { + if (t <= machep) { + t = 1.0 - machep; + } else { + t = 1.0 - t; + } + } + return t; + } +}; + +#endif // EIGEN_HAS_C99_MATH + +} // end namespace internal + +namespace numext { + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(lgamma, Scalar) + lgamma(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(lgamma, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(digamma, Scalar) + digamma(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(digamma, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(zeta, Scalar) +zeta(const Scalar& x, const Scalar& q) { + return EIGEN_MATHFUNC_IMPL(zeta, Scalar)::run(x, q); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(polygamma, Scalar) +polygamma(const Scalar& n, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(polygamma, Scalar)::run(n, x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(erf, Scalar) + erf(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(erf, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(erfc, Scalar) + erfc(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(erfc, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(ndtri, Scalar) + ndtri(const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(ndtri, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(igamma, Scalar) + igamma(const Scalar& a, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(igamma, Scalar)::run(a, x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(igamma_der_a, Scalar) + igamma_der_a(const Scalar& a, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(igamma_der_a, Scalar)::run(a, x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(gamma_sample_der_alpha, Scalar) + gamma_sample_der_alpha(const Scalar& a, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(gamma_sample_der_alpha, Scalar)::run(a, x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(igammac, Scalar) + igammac(const Scalar& a, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(igammac, Scalar)::run(a, x); +} + +template +EIGEN_DEVICE_FUNC inline EIGEN_MATHFUNC_RETVAL(betainc, Scalar) + betainc(const Scalar& a, const Scalar& b, const Scalar& x) { + return EIGEN_MATHFUNC_IMPL(betainc, Scalar)::run(a, b, x); +} + +} // end namespace numext +} // end namespace Eigen + +#endif // EIGEN_SPECIAL_FUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h new file mode 100644 index 0000000000000000000000000000000000000000..651457f5c9be9e6752e40213ac5d7b6bdf4a20f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h @@ -0,0 +1,81 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPECIALFUNCTIONS_PACKETMATH_H +#define EIGEN_SPECIALFUNCTIONS_PACKETMATH_H + +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +/** \internal \returns the ln(|gamma(\a a)|) (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet plgamma(const Packet& a) { using numext::lgamma; return lgamma(a); } + +/** \internal \returns the derivative of lgamma, psi(\a a) (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pdigamma(const Packet& a) { using numext::digamma; return digamma(a); } + +/** \internal \returns the zeta function of two arguments (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pzeta(const Packet& x, const Packet& q) { using numext::zeta; return zeta(x, q); } + +/** \internal \returns the polygamma function (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet ppolygamma(const Packet& n, const Packet& x) { using numext::polygamma; return polygamma(n, x); } + +/** \internal \returns the erf(\a a) (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet perf(const Packet& a) { using numext::erf; return erf(a); } + +/** \internal \returns the erfc(\a a) (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet perfc(const Packet& a) { using numext::erfc; return erfc(a); } + +/** \internal \returns the ndtri(\a a) (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pndtri(const Packet& a) { + typedef typename unpacket_traits::type ScalarType; + using internal::generic_ndtri; return generic_ndtri(a); +} + +/** \internal \returns the incomplete gamma function igamma(\a a, \a x) */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +Packet pigamma(const Packet& a, const Packet& x) { using numext::igamma; return igamma(a, x); } + +/** \internal \returns the derivative of the incomplete gamma function + * igamma_der_a(\a a, \a x) */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pigamma_der_a(const Packet& a, const Packet& x) { + using numext::igamma_der_a; return igamma_der_a(a, x); +} + +/** \internal \returns compute the derivative of the sample + * of Gamma(alpha, 1) random variable with respect to the parameter a + * gamma_sample_der_alpha(\a alpha, \a sample) */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pgamma_sample_der_alpha(const Packet& alpha, const Packet& sample) { + using numext::gamma_sample_der_alpha; return gamma_sample_der_alpha(alpha, sample); +} + +/** \internal \returns the complementary incomplete gamma function igammac(\a a, \a x) */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +Packet pigammac(const Packet& a, const Packet& x) { using numext::igammac; return igammac(a, x); } + +/** \internal \returns the complementary incomplete gamma function betainc(\a a, \a b, \a x) */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +Packet pbetainc(const Packet& a, const Packet& b,const Packet& x) { using numext::betainc; return betainc(a, b, x); } + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_SPECIALFUNCTIONS_PACKETMATH_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/BesselFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/BesselFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..2d76692097f50386c97b9e33b7ebe925aa327bed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/BesselFunctions.h @@ -0,0 +1,46 @@ +#ifndef EIGEN_AVX_BESSELFUNCTIONS_H +#define EIGEN_AVX_BESSELFUNCTIONS_H + +namespace Eigen { +namespace internal { + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i0) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i0) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i0e) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i0e) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i1) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i1) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i1e) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i1e) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_j0) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_j0) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_j1) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_j1) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k0) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k0) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k0e) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k0e) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k1) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k1) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k1e) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k1e) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_y0) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_y0) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_y1) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_y1) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_AVX_BESSELFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/SpecialFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/SpecialFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..35e62a8acb25e0d56334183f70bad9a3909de64a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX/SpecialFunctions.h @@ -0,0 +1,16 @@ +#ifndef EIGEN_AVX_SPECIALFUNCTIONS_H +#define EIGEN_AVX_SPECIALFUNCTIONS_H + +namespace Eigen { +namespace internal { + +F16_PACKET_FUNCTION(Packet8f, Packet8h, perf) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, perf) + +F16_PACKET_FUNCTION(Packet8f, Packet8h, pndtri) +BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pndtri) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_AVX_SPECIAL_FUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/BesselFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/BesselFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..7dd3c3e5be6de84176da2459a860fec6c344c770 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/BesselFunctions.h @@ -0,0 +1,46 @@ +#ifndef EIGEN_AVX512_BESSELFUNCTIONS_H +#define EIGEN_AVX512_BESSELFUNCTIONS_H + +namespace Eigen { +namespace internal { + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i0) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i0) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i0e) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i0e) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i1) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i1) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i1e) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i1e) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_j0) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_j0) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_j1) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_j1) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k0) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k0) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k0e) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k0e) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k1) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k1) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k1e) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k1e) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_y0) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_y0) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_y1) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_y1) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_AVX512_BESSELFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/SpecialFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/SpecialFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..79878f2b6967ed3125d1726df48df95e9b63721d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/SpecialFunctions.h @@ -0,0 +1,16 @@ +#ifndef EIGEN_AVX512_SPECIALFUNCTIONS_H +#define EIGEN_AVX512_SPECIALFUNCTIONS_H + +namespace Eigen { +namespace internal { + +F16_PACKET_FUNCTION(Packet16f, Packet16h, perf) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, perf) + +F16_PACKET_FUNCTION(Packet16f, Packet16h, pndtri) +BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pndtri) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_AVX512_SPECIAL_FUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/GPU/SpecialFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/GPU/SpecialFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..dd3bf4dd13bdf923db53be7f661f04367e1171a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/GPU/SpecialFunctions.h @@ -0,0 +1,369 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GPU_SPECIALFUNCTIONS_H +#define EIGEN_GPU_SPECIALFUNCTIONS_H + +namespace Eigen { + +namespace internal { + +// Make sure this is only available when targeting a GPU: we don't want to +// introduce conflicts between these packet_traits definitions and the ones +// we'll use on the host side (SSE, AVX, ...) +#if defined(EIGEN_GPUCC) && defined(EIGEN_USE_GPU) + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 plgamma(const float4& a) +{ + return make_float4(lgammaf(a.x), lgammaf(a.y), lgammaf(a.z), lgammaf(a.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 plgamma(const double2& a) +{ + using numext::lgamma; + return make_double2(lgamma(a.x), lgamma(a.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pdigamma(const float4& a) +{ + using numext::digamma; + return make_float4(digamma(a.x), digamma(a.y), digamma(a.z), digamma(a.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pdigamma(const double2& a) +{ + using numext::digamma; + return make_double2(digamma(a.x), digamma(a.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pzeta(const float4& x, const float4& q) +{ + using numext::zeta; + return make_float4(zeta(x.x, q.x), zeta(x.y, q.y), zeta(x.z, q.z), zeta(x.w, q.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pzeta(const double2& x, const double2& q) +{ + using numext::zeta; + return make_double2(zeta(x.x, q.x), zeta(x.y, q.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 ppolygamma(const float4& n, const float4& x) +{ + using numext::polygamma; + return make_float4(polygamma(n.x, x.x), polygamma(n.y, x.y), polygamma(n.z, x.z), polygamma(n.w, x.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 ppolygamma(const double2& n, const double2& x) +{ + using numext::polygamma; + return make_double2(polygamma(n.x, x.x), polygamma(n.y, x.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 perf(const float4& a) +{ + return make_float4(erff(a.x), erff(a.y), erff(a.z), erff(a.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 perf(const double2& a) +{ + using numext::erf; + return make_double2(erf(a.x), erf(a.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 perfc(const float4& a) +{ + using numext::erfc; + return make_float4(erfc(a.x), erfc(a.y), erfc(a.z), erfc(a.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 perfc(const double2& a) +{ + using numext::erfc; + return make_double2(erfc(a.x), erfc(a.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pndtri(const float4& a) +{ + using numext::ndtri; + return make_float4(ndtri(a.x), ndtri(a.y), ndtri(a.z), ndtri(a.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pndtri(const double2& a) +{ + using numext::ndtri; + return make_double2(ndtri(a.x), ndtri(a.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pigamma(const float4& a, const float4& x) +{ + using numext::igamma; + return make_float4( + igamma(a.x, x.x), + igamma(a.y, x.y), + igamma(a.z, x.z), + igamma(a.w, x.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pigamma(const double2& a, const double2& x) +{ + using numext::igamma; + return make_double2(igamma(a.x, x.x), igamma(a.y, x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pigamma_der_a( + const float4& a, const float4& x) { + using numext::igamma_der_a; + return make_float4(igamma_der_a(a.x, x.x), igamma_der_a(a.y, x.y), + igamma_der_a(a.z, x.z), igamma_der_a(a.w, x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pigamma_der_a(const double2& a, const double2& x) { + using numext::igamma_der_a; + return make_double2(igamma_der_a(a.x, x.x), igamma_der_a(a.y, x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pgamma_sample_der_alpha( + const float4& alpha, const float4& sample) { + using numext::gamma_sample_der_alpha; + return make_float4( + gamma_sample_der_alpha(alpha.x, sample.x), + gamma_sample_der_alpha(alpha.y, sample.y), + gamma_sample_der_alpha(alpha.z, sample.z), + gamma_sample_der_alpha(alpha.w, sample.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pgamma_sample_der_alpha(const double2& alpha, const double2& sample) { + using numext::gamma_sample_der_alpha; + return make_double2( + gamma_sample_der_alpha(alpha.x, sample.x), + gamma_sample_der_alpha(alpha.y, sample.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pigammac(const float4& a, const float4& x) +{ + using numext::igammac; + return make_float4( + igammac(a.x, x.x), + igammac(a.y, x.y), + igammac(a.z, x.z), + igammac(a.w, x.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pigammac(const double2& a, const double2& x) +{ + using numext::igammac; + return make_double2(igammac(a.x, x.x), igammac(a.y, x.y)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +float4 pbetainc(const float4& a, const float4& b, const float4& x) +{ + using numext::betainc; + return make_float4( + betainc(a.x, b.x, x.x), + betainc(a.y, b.y, x.y), + betainc(a.z, b.z, x.z), + betainc(a.w, b.w, x.w)); +} + +template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +double2 pbetainc(const double2& a, const double2& b, const double2& x) +{ + using numext::betainc; + return make_double2(betainc(a.x, b.x, x.x), betainc(a.y, b.y, x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i0e(const float4& x) { + using numext::bessel_i0e; + return make_float4(bessel_i0e(x.x), bessel_i0e(x.y), bessel_i0e(x.z), bessel_i0e(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_i0e(const double2& x) { + using numext::bessel_i0e; + return make_double2(bessel_i0e(x.x), bessel_i0e(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i0(const float4& x) { + using numext::bessel_i0; + return make_float4(bessel_i0(x.x), bessel_i0(x.y), bessel_i0(x.z), bessel_i0(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_i0(const double2& x) { + using numext::bessel_i0; + return make_double2(bessel_i0(x.x), bessel_i0(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i1e(const float4& x) { + using numext::bessel_i1e; + return make_float4(bessel_i1e(x.x), bessel_i1e(x.y), bessel_i1e(x.z), bessel_i1e(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_i1e(const double2& x) { + using numext::bessel_i1e; + return make_double2(bessel_i1e(x.x), bessel_i1e(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i1(const float4& x) { + using numext::bessel_i1; + return make_float4(bessel_i1(x.x), bessel_i1(x.y), bessel_i1(x.z), bessel_i1(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_i1(const double2& x) { + using numext::bessel_i1; + return make_double2(bessel_i1(x.x), bessel_i1(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k0e(const float4& x) { + using numext::bessel_k0e; + return make_float4(bessel_k0e(x.x), bessel_k0e(x.y), bessel_k0e(x.z), bessel_k0e(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_k0e(const double2& x) { + using numext::bessel_k0e; + return make_double2(bessel_k0e(x.x), bessel_k0e(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k0(const float4& x) { + using numext::bessel_k0; + return make_float4(bessel_k0(x.x), bessel_k0(x.y), bessel_k0(x.z), bessel_k0(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_k0(const double2& x) { + using numext::bessel_k0; + return make_double2(bessel_k0(x.x), bessel_k0(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k1e(const float4& x) { + using numext::bessel_k1e; + return make_float4(bessel_k1e(x.x), bessel_k1e(x.y), bessel_k1e(x.z), bessel_k1e(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_k1e(const double2& x) { + using numext::bessel_k1e; + return make_double2(bessel_k1e(x.x), bessel_k1e(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k1(const float4& x) { + using numext::bessel_k1; + return make_float4(bessel_k1(x.x), bessel_k1(x.y), bessel_k1(x.z), bessel_k1(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_k1(const double2& x) { + using numext::bessel_k1; + return make_double2(bessel_k1(x.x), bessel_k1(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_j0(const float4& x) { + using numext::bessel_j0; + return make_float4(bessel_j0(x.x), bessel_j0(x.y), bessel_j0(x.z), bessel_j0(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_j0(const double2& x) { + using numext::bessel_j0; + return make_double2(bessel_j0(x.x), bessel_j0(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_j1(const float4& x) { + using numext::bessel_j1; + return make_float4(bessel_j1(x.x), bessel_j1(x.y), bessel_j1(x.z), bessel_j1(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_j1(const double2& x) { + using numext::bessel_j1; + return make_double2(bessel_j1(x.x), bessel_j1(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_y0(const float4& x) { + using numext::bessel_y0; + return make_float4(bessel_y0(x.x), bessel_y0(x.y), bessel_y0(x.z), bessel_y0(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_y0(const double2& x) { + using numext::bessel_y0; + return make_double2(bessel_y0(x.x), bessel_y0(x.y)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_y1(const float4& x) { + using numext::bessel_y1; + return make_float4(bessel_y1(x.x), bessel_y1(x.y), bessel_y1(x.z), bessel_y1(x.w)); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 +pbessel_y1(const double2& x) { + using numext::bessel_y1; + return make_double2(bessel_y1(x.x), bessel_y1(x.y)); +} + +#endif + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_GPU_SPECIALFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/BesselFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/BesselFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..67433b057cf384084243b65cbd9e56982b9e671b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/BesselFunctions.h @@ -0,0 +1,54 @@ +#ifndef EIGEN_NEON_BESSELFUNCTIONS_H +#define EIGEN_NEON_BESSELFUNCTIONS_H + +namespace Eigen { +namespace internal { + +#if EIGEN_HAS_ARM64_FP16_VECTOR_ARITHMETIC + +#define NEON_HALF_TO_FLOAT_FUNCTIONS(METHOD) \ +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \ +Packet8hf METHOD(const Packet8hf& x) { \ + const Packet4f lo = METHOD(vcvt_f32_f16(vget_low_f16(x))); \ + const Packet4f hi = METHOD(vcvt_f32_f16(vget_high_f16(x))); \ + return vcombine_f16(vcvt_f16_f32(lo), vcvt_f16_f32(hi)); \ +} \ + \ +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \ +Packet4hf METHOD(const Packet4hf& x) { \ + return vcvt_f16_f32(METHOD(vcvt_f32_f16(x))); \ +} + +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i0) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i0e) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i1) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i1e) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_j0) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_j1) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k0) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k0e) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k1) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k1e) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_y0) +NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_y1) + +#undef NEON_HALF_TO_FLOAT_FUNCTIONS +#endif + +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i0) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i0e) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i1) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i1e) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_j0) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_j1) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k0) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k0e) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k1) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k1e) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_y0) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_y1) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_NEON_BESSELFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/SpecialFunctions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/SpecialFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..ec9295197c5ee4e50eec7e64da7a353b0478f247 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/SpecialFunctions/arch/NEON/SpecialFunctions.h @@ -0,0 +1,34 @@ +#ifndef EIGEN_NEON_SPECIALFUNCTIONS_H +#define EIGEN_NEON_SPECIALFUNCTIONS_H + +namespace Eigen { +namespace internal { + +#if EIGEN_HAS_ARM64_FP16_VECTOR_ARITHMETIC + +#define NEON_HALF_TO_FLOAT_FUNCTIONS(METHOD) \ +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \ +Packet8hf METHOD(const Packet8hf& x) { \ + const Packet4f lo = METHOD(vcvt_f32_f16(vget_low_f16(x))); \ + const Packet4f hi = METHOD(vcvt_f32_f16(vget_high_f16(x))); \ + return vcombine_f16(vcvt_f16_f32(lo), vcvt_f16_f32(hi)); \ +} \ + \ +template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \ +Packet4hf METHOD(const Packet4hf& x) { \ + return vcvt_f16_f32(METHOD(vcvt_f32_f16(x))); \ +} + +NEON_HALF_TO_FLOAT_FUNCTIONS(perf) +NEON_HALF_TO_FLOAT_FUNCTIONS(pndtri) + +#undef NEON_HALF_TO_FLOAT_FUNCTIONS +#endif + +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, perf) +BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pndtri) + +} // namespace internal +} // namespace Eigen + +#endif // EIGEN_NEON_SPECIALFUNCTIONS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/InternalHeaderCheck.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/InternalHeaderCheck.h new file mode 100644 index 0000000000000000000000000000000000000000..4a6087e79598982ece7180485f51fc627f49d163 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/InternalHeaderCheck.h @@ -0,0 +1,3 @@ +#ifndef EIGEN_SPLINES_MODULE_H +#error "Please include unsupported/Eigen/Splines instead of including headers inside the src directory directly." +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/Spline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/Spline.h new file mode 100644 index 0000000000000000000000000000000000000000..ce786ee9a22c6c4b9ff09d3a8d4127816d03f8a2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/Spline.h @@ -0,0 +1,509 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 20010-2011 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPLINE_H +#define EIGEN_SPLINE_H + +#include "./InternalHeaderCheck.h" + +#include "SplineFwd.h" + +namespace Eigen +{ + /** + * \ingroup Splines_Module + * \class Spline + * \brief A class representing multi-dimensional spline curves. + * + * The class represents B-splines with non-uniform knot vectors. Each control + * point of the B-spline is associated with a basis function + * \f{align*} + * C(u) & = \sum_{i=0}^{n}N_{i,p}(u)P_i + * \f} + * + * \tparam Scalar_ The underlying data type (typically float or double) + * \tparam Dim_ The curve dimension (e.g. 2 or 3) + * \tparam Degree_ Per default set to Dynamic; could be set to the actual desired + * degree for optimization purposes (would result in stack allocation + * of several temporary variables). + **/ + template + class Spline + { + public: + typedef Scalar_ Scalar; /*!< The spline curve's scalar type. */ + enum { Dimension = Dim_ /*!< The spline curve's dimension. */ }; + enum { Degree = Degree_ /*!< The spline curve's degree. */ }; + + /** \brief The point type the spline is representing. */ + typedef typename SplineTraits::PointType PointType; + + /** \brief The data type used to store knot vectors. */ + typedef typename SplineTraits::KnotVectorType KnotVectorType; + + /** \brief The data type used to store parameter vectors. */ + typedef typename SplineTraits::ParameterVectorType ParameterVectorType; + + /** \brief The data type used to store non-zero basis functions. */ + typedef typename SplineTraits::BasisVectorType BasisVectorType; + + /** \brief The data type used to store the values of the basis function derivatives. */ + typedef typename SplineTraits::BasisDerivativeType BasisDerivativeType; + + /** \brief The data type representing the spline's control points. */ + typedef typename SplineTraits::ControlPointVectorType ControlPointVectorType; + + /** + * \brief Creates a (constant) zero spline. + * For Splines with dynamic degree, the resulting degree will be 0. + **/ + Spline() + : m_knots(1, (Degree==Dynamic ? 2 : 2*Degree+2)) + , m_ctrls(ControlPointVectorType::Zero(Dimension,(Degree==Dynamic ? 1 : Degree+1))) + { + // in theory this code can go to the initializer list but it will get pretty + // much unreadable ... + enum { MinDegree = (Degree==Dynamic ? 0 : Degree) }; + m_knots.template segment(0) = Array::Zero(); + m_knots.template segment(MinDegree+1) = Array::Ones(); + } + + /** + * \brief Creates a spline from a knot vector and control points. + * \param knots The spline's knot vector. + * \param ctrls The spline's control point vector. + **/ + template + Spline(const OtherVectorType& knots, const OtherArrayType& ctrls) : m_knots(knots), m_ctrls(ctrls) {} + + /** + * \brief Copy constructor for splines. + * \param spline The input spline. + **/ + template + Spline(const Spline& spline) : + m_knots(spline.knots()), m_ctrls(spline.ctrls()) {} + + /** + * \brief Returns the knots of the underlying spline. + **/ + const KnotVectorType& knots() const { return m_knots; } + + /** + * \brief Returns the ctrls of the underlying spline. + **/ + const ControlPointVectorType& ctrls() const { return m_ctrls; } + + /** + * \brief Returns the spline value at a given site \f$u\f$. + * + * The function returns + * \f{align*} + * C(u) & = \sum_{i=0}^{n}N_{i,p}P_i + * \f} + * + * \param u Parameter \f$u \in [0;1]\f$ at which the spline is evaluated. + * \return The spline value at the given location \f$u\f$. + **/ + PointType operator()(Scalar u) const; + + /** + * \brief Evaluation of spline derivatives of up-to given order. + * + * The function returns + * \f{align*} + * \frac{d^i}{du^i}C(u) & = \sum_{i=0}^{n} \frac{d^i}{du^i} N_{i,p}(u)P_i + * \f} + * for i ranging between 0 and order. + * + * \param u Parameter \f$u \in [0;1]\f$ at which the spline derivative is evaluated. + * \param order The order up to which the derivatives are computed. + **/ + typename SplineTraits::DerivativeType + derivatives(Scalar u, DenseIndex order) const; + + /** + * \copydoc Spline::derivatives + * Using the template version of this function is more efficieent since + * temporary objects are allocated on the stack whenever this is possible. + **/ + template + typename SplineTraits::DerivativeType + derivatives(Scalar u, DenseIndex order = DerivativeOrder) const; + + /** + * \brief Computes the non-zero basis functions at the given site. + * + * Splines have local support and a point from their image is defined + * by exactly \f$p+1\f$ control points \f$P_i\f$ where \f$p\f$ is the + * spline degree. + * + * This function computes the \f$p+1\f$ non-zero basis function values + * for a given parameter value \f$u\f$. It returns + * \f{align*}{ + * N_{i,p}(u), \hdots, N_{i+p+1,p}(u) + * \f} + * + * \param u Parameter \f$u \in [0;1]\f$ at which the non-zero basis functions + * are computed. + **/ + typename SplineTraits::BasisVectorType + basisFunctions(Scalar u) const; + + /** + * \brief Computes the non-zero spline basis function derivatives up to given order. + * + * The function computes + * \f{align*}{ + * \frac{d^i}{du^i} N_{i,p}(u), \hdots, \frac{d^i}{du^i} N_{i+p+1,p}(u) + * \f} + * with i ranging from 0 up to the specified order. + * + * \param u Parameter \f$u \in [0;1]\f$ at which the non-zero basis function + * derivatives are computed. + * \param order The order up to which the basis function derivatives are computes. + **/ + typename SplineTraits::BasisDerivativeType + basisFunctionDerivatives(Scalar u, DenseIndex order) const; + + /** + * \copydoc Spline::basisFunctionDerivatives + * Using the template version of this function is more efficieent since + * temporary objects are allocated on the stack whenever this is possible. + **/ + template + typename SplineTraits::BasisDerivativeType + basisFunctionDerivatives(Scalar u, DenseIndex order = DerivativeOrder) const; + + /** + * \brief Returns the spline degree. + **/ + DenseIndex degree() const; + + /** + * \brief Returns the span within the knot vector in which u is falling. + * \param u The site for which the span is determined. + **/ + DenseIndex span(Scalar u) const; + + /** + * \brief Computes the span within the provided knot vector in which u is falling. + **/ + static DenseIndex Span(typename SplineTraits::Scalar u, DenseIndex degree, const typename SplineTraits::KnotVectorType& knots); + + /** + * \brief Returns the spline's non-zero basis functions. + * + * The function computes and returns + * \f{align*}{ + * N_{i,p}(u), \hdots, N_{i+p+1,p}(u) + * \f} + * + * \param u The site at which the basis functions are computed. + * \param degree The degree of the underlying spline. + * \param knots The underlying spline's knot vector. + **/ + static BasisVectorType BasisFunctions(Scalar u, DenseIndex degree, const KnotVectorType& knots); + + /** + * \copydoc Spline::basisFunctionDerivatives + * \param degree The degree of the underlying spline + * \param knots The underlying spline's knot vector. + **/ + static BasisDerivativeType BasisFunctionDerivatives( + const Scalar u, const DenseIndex order, const DenseIndex degree, const KnotVectorType& knots); + + private: + KnotVectorType m_knots; /*!< Knot vector. */ + ControlPointVectorType m_ctrls; /*!< Control points. */ + + template + static void BasisFunctionDerivativesImpl( + const typename Spline::Scalar u, + const DenseIndex order, + const DenseIndex p, + const typename Spline::KnotVectorType& U, + DerivativeType& N_); + }; + + template + DenseIndex Spline::Span( + typename SplineTraits< Spline >::Scalar u, + DenseIndex degree, + const typename SplineTraits< Spline >::KnotVectorType& knots) + { + // Piegl & Tiller, "The NURBS Book", A2.1 (p. 68) + if (u <= knots(0)) return degree; + const Scalar* pos = std::upper_bound(knots.data()+degree-1, knots.data()+knots.size()-degree-1, u); + return static_cast( std::distance(knots.data(), pos) - 1 ); + } + + template + typename Spline::BasisVectorType + Spline::BasisFunctions( + typename Spline::Scalar u, + DenseIndex degree, + const typename Spline::KnotVectorType& knots) + { + const DenseIndex p = degree; + const DenseIndex i = Spline::Span(u, degree, knots); + + const KnotVectorType& U = knots; + + BasisVectorType left(p+1); left(0) = Scalar(0); + BasisVectorType right(p+1); right(0) = Scalar(0); + + VectorBlock(left,1,p) = u - VectorBlock(U,i+1-p,p).reverse(); + VectorBlock(right,1,p) = VectorBlock(U,i+1,p) - u; + + BasisVectorType N(1,p+1); + N(0) = Scalar(1); + for (DenseIndex j=1; j<=p; ++j) + { + Scalar saved = Scalar(0); + for (DenseIndex r=0; r + DenseIndex Spline::degree() const + { + if (Degree_ == Dynamic) + return m_knots.size() - m_ctrls.cols() - 1; + else + return Degree_; + } + + template + DenseIndex Spline::span(Scalar u) const + { + return Spline::Span(u, degree(), knots()); + } + + template + typename Spline::PointType Spline::operator()(Scalar u) const + { + enum { Order = SplineTraits::OrderAtCompileTime }; + + const DenseIndex span = this->span(u); + const DenseIndex p = degree(); + const BasisVectorType basis_funcs = basisFunctions(u); + + const Replicate ctrl_weights(basis_funcs); + const Block ctrl_pts(ctrls(),0,span-p,Dimension,p+1); + return (ctrl_weights * ctrl_pts).rowwise().sum(); + } + + /* --------------------------------------------------------------------------------------------- */ + + template + void derivativesImpl(const SplineType& spline, typename SplineType::Scalar u, DenseIndex order, DerivativeType& der) + { + enum { Dimension = SplineTraits::Dimension }; + enum { Order = SplineTraits::OrderAtCompileTime }; + enum { DerivativeOrder = DerivativeType::ColsAtCompileTime }; + + typedef typename SplineTraits::ControlPointVectorType ControlPointVectorType; + typedef typename SplineTraits::BasisDerivativeType BasisDerivativeType; + typedef typename BasisDerivativeType::ConstRowXpr BasisDerivativeRowXpr; + + const DenseIndex p = spline.degree(); + const DenseIndex span = spline.span(u); + + const DenseIndex n = (std::min)(p, order); + + der.resize(Dimension,n+1); + + // Retrieve the basis function derivatives up to the desired order... + const BasisDerivativeType basis_func_ders = spline.template basisFunctionDerivatives(u, n+1); + + // ... and perform the linear combinations of the control points. + for (DenseIndex der_order=0; der_order ctrl_weights( basis_func_ders.row(der_order) ); + const Block ctrl_pts(spline.ctrls(),0,span-p,Dimension,p+1); + der.col(der_order) = (ctrl_weights * ctrl_pts).rowwise().sum(); + } + } + + template + typename SplineTraits< Spline >::DerivativeType + Spline::derivatives(Scalar u, DenseIndex order) const + { + typename SplineTraits< Spline >::DerivativeType res; + derivativesImpl(*this, u, order, res); + return res; + } + + template + template + typename SplineTraits< Spline, DerivativeOrder >::DerivativeType + Spline::derivatives(Scalar u, DenseIndex order) const + { + typename SplineTraits< Spline, DerivativeOrder >::DerivativeType res; + derivativesImpl(*this, u, order, res); + return res; + } + + template + typename SplineTraits< Spline >::BasisVectorType + Spline::basisFunctions(Scalar u) const + { + return Spline::BasisFunctions(u, degree(), knots()); + } + + /* --------------------------------------------------------------------------------------------- */ + + + template + template + void Spline::BasisFunctionDerivativesImpl( + const typename Spline::Scalar u, + const DenseIndex order, + const DenseIndex p, + const typename Spline::KnotVectorType& U, + DerivativeType& N_) + { + typedef Spline SplineType; + enum { Order = SplineTraits::OrderAtCompileTime }; + + const DenseIndex span = SplineType::Span(u, p, U); + + const DenseIndex n = (std::min)(p, order); + + N_.resize(n+1, p+1); + + BasisVectorType left = BasisVectorType::Zero(p+1); + BasisVectorType right = BasisVectorType::Zero(p+1); + + Matrix ndu(p+1,p+1); + + Scalar saved, temp; // FIXME These were double instead of Scalar. Was there a reason for that? + + ndu(0,0) = 1.0; + + DenseIndex j; + for (j=1; j<=p; ++j) + { + left[j] = u-U[span+1-j]; + right[j] = U[span+j]-u; + saved = 0.0; + + for (DenseIndex r=0; r(saved+right[r+1] * temp); + saved = left[j-r] * temp; + } + + ndu(j,j) = static_cast(saved); + } + + for (j = p; j>=0; --j) + N_(0,j) = ndu(j,p); + + // Compute the derivatives + DerivativeType a(n+1,p+1); + DenseIndex r=0; + for (; r<=p; ++r) + { + DenseIndex s1,s2; + s1 = 0; s2 = 1; // alternate rows in array a + a(0,0) = 1.0; + + // Compute the k-th derivative + for (DenseIndex k=1; k<=static_cast(n); ++k) + { + Scalar d = 0.0; + DenseIndex rk,pk,j1,j2; + rk = r-k; pk = p-k; + + if (r>=k) + { + a(s2,0) = a(s1,0)/ndu(pk+1,rk); + d = a(s2,0)*ndu(rk,pk); + } + + if (rk>=-1) j1 = 1; + else j1 = -rk; + + if (r-1 <= pk) j2 = k-1; + else j2 = p-r; + + for (j=j1; j<=j2; ++j) + { + a(s2,j) = (a(s1,j)-a(s1,j-1))/ndu(pk+1,rk+j); + d += a(s2,j)*ndu(rk+j,pk); + } + + if (r<=pk) + { + a(s2,k) = -a(s1,k-1)/ndu(pk+1,r); + d += a(s2,k)*ndu(r,pk); + } + + N_(k,r) = static_cast(d); + j = s1; s1 = s2; s2 = j; // Switch rows + } + } + + /* Multiply through by the correct factors */ + /* (Eq. [2.9]) */ + r = p; + for (DenseIndex k=1; k<=static_cast(n); ++k) + { + for (j=p; j>=0; --j) N_(k,j) *= r; + r *= p-k; + } + } + + template + typename SplineTraits< Spline >::BasisDerivativeType + Spline::basisFunctionDerivatives(Scalar u, DenseIndex order) const + { + typename SplineTraits >::BasisDerivativeType der; + BasisFunctionDerivativesImpl(u, order, degree(), knots(), der); + return der; + } + + template + template + typename SplineTraits< Spline, DerivativeOrder >::BasisDerivativeType + Spline::basisFunctionDerivatives(Scalar u, DenseIndex order) const + { + typename SplineTraits< Spline, DerivativeOrder >::BasisDerivativeType der; + BasisFunctionDerivativesImpl(u, order, degree(), knots(), der); + return der; + } + + template + typename SplineTraits >::BasisDerivativeType + Spline::BasisFunctionDerivatives( + const typename Spline::Scalar u, + const DenseIndex order, + const DenseIndex degree, + const typename Spline::KnotVectorType& knots) + { + typename SplineTraits::BasisDerivativeType der; + BasisFunctionDerivativesImpl(u, order, degree, knots, der); + return der; + } +} + +#endif // EIGEN_SPLINE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFitting.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFitting.h new file mode 100644 index 0000000000000000000000000000000000000000..fe70658a6742b2d54944f717a2c2af30c589c3bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFitting.h @@ -0,0 +1,434 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 20010-2011 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPLINE_FITTING_H +#define EIGEN_SPLINE_FITTING_H + +#include +#include +#include +#include + +#include "./InternalHeaderCheck.h" + +#include "SplineFwd.h" + +#include "../../../../Eigen/LU" +#include "../../../../Eigen/QR" + + +namespace Eigen +{ + /** + * \brief Computes knot averages. + * \ingroup Splines_Module + * + * The knots are computed as + * \f{align*} + * u_0 & = \hdots = u_p = 0 \\ + * u_{m-p} & = \hdots = u_{m} = 1 \\ + * u_{j+p} & = \frac{1}{p}\sum_{i=j}^{j+p-1}\bar{u}_i \quad\quad j=1,\hdots,n-p + * \f} + * where \f$p\f$ is the degree and \f$m+1\f$ the number knots + * of the desired interpolating spline. + * + * \param[in] parameters The input parameters. During interpolation one for each data point. + * \param[in] degree The spline degree which is used during the interpolation. + * \param[out] knots The output knot vector. + * + * \sa Les Piegl and Wayne Tiller, The NURBS book (2nd ed.), 1997, 9.2.1 Global Curve Interpolation to Point Data + **/ + template + void KnotAveraging(const KnotVectorType& parameters, DenseIndex degree, KnotVectorType& knots) + { + knots.resize(parameters.size()+degree+1); + + for (DenseIndex j=1; j + void KnotAveragingWithDerivatives(const ParameterVectorType& parameters, + const unsigned int degree, + const IndexArray& derivativeIndices, + KnotVectorType& knots) + { + typedef typename ParameterVectorType::Scalar Scalar; + + DenseIndex numParameters = parameters.size(); + DenseIndex numDerivatives = derivativeIndices.size(); + + if (numDerivatives < 1) + { + KnotAveraging(parameters, degree, knots); + return; + } + + DenseIndex startIndex; + DenseIndex endIndex; + + DenseIndex numInternalDerivatives = numDerivatives; + + if (derivativeIndices[0] == 0) + { + startIndex = 0; + --numInternalDerivatives; + } + else + { + startIndex = 1; + } + if (derivativeIndices[numDerivatives - 1] == numParameters - 1) + { + endIndex = numParameters - degree; + --numInternalDerivatives; + } + else + { + endIndex = numParameters - degree - 1; + } + + // There are (endIndex - startIndex + 1) knots obtained from the averaging + // and 2 for the first and last parameters. + DenseIndex numAverageKnots = endIndex - startIndex + 3; + KnotVectorType averageKnots(numAverageKnots); + averageKnots[0] = parameters[0]; + + int newKnotIndex = 0; + for (DenseIndex i = startIndex; i <= endIndex; ++i) + averageKnots[++newKnotIndex] = parameters.segment(i, degree).mean(); + averageKnots[++newKnotIndex] = parameters[numParameters - 1]; + + newKnotIndex = -1; + + ParameterVectorType temporaryParameters(numParameters + 1); + KnotVectorType derivativeKnots(numInternalDerivatives); + for (DenseIndex i = 0; i < numAverageKnots - 1; ++i) + { + temporaryParameters[0] = averageKnots[i]; + ParameterVectorType parameterIndices(numParameters); + int temporaryParameterIndex = 1; + for (DenseIndex j = 0; j < numParameters; ++j) + { + Scalar parameter = parameters[j]; + if (parameter >= averageKnots[i] && parameter < averageKnots[i + 1]) + { + parameterIndices[temporaryParameterIndex] = j; + temporaryParameters[temporaryParameterIndex++] = parameter; + } + } + temporaryParameters[temporaryParameterIndex] = averageKnots[i + 1]; + + for (int j = 0; j <= temporaryParameterIndex - 2; ++j) + { + for (DenseIndex k = 0; k < derivativeIndices.size(); ++k) + { + if (parameterIndices[j + 1] == derivativeIndices[k] + && parameterIndices[j + 1] != 0 + && parameterIndices[j + 1] != numParameters - 1) + { + derivativeKnots[++newKnotIndex] = temporaryParameters.segment(j, 3).mean(); + break; + } + } + } + } + + KnotVectorType temporaryKnots(averageKnots.size() + derivativeKnots.size()); + + std::merge(averageKnots.data(), averageKnots.data() + averageKnots.size(), + derivativeKnots.data(), derivativeKnots.data() + derivativeKnots.size(), + temporaryKnots.data()); + + // Number of knots (one for each point and derivative) plus spline order. + DenseIndex numKnots = numParameters + numDerivatives + degree + 1; + knots.resize(numKnots); + + knots.head(degree).fill(temporaryKnots[0]); + knots.tail(degree).fill(temporaryKnots.template tail<1>()[0]); + knots.segment(degree, temporaryKnots.size()) = temporaryKnots; + } + + /** + * \brief Computes chord length parameters which are required for spline interpolation. + * \ingroup Splines_Module + * + * \param[in] pts The data points to which a spline should be fit. + * \param[out] chord_lengths The resulting chord length vector. + * + * \sa Les Piegl and Wayne Tiller, The NURBS book (2nd ed.), 1997, 9.2.1 Global Curve Interpolation to Point Data + **/ + template + void ChordLengths(const PointArrayType& pts, KnotVectorType& chord_lengths) + { + typedef typename KnotVectorType::Scalar Scalar; + + const DenseIndex n = pts.cols(); + + // 1. compute the column-wise norms + chord_lengths.resize(pts.cols()); + chord_lengths[0] = 0; + chord_lengths.rightCols(n-1) = (pts.array().leftCols(n-1) - pts.array().rightCols(n-1)).matrix().colwise().norm(); + + // 2. compute the partial sums + std::partial_sum(chord_lengths.data(), chord_lengths.data()+n, chord_lengths.data()); + + // 3. normalize the data + chord_lengths /= chord_lengths(n-1); + chord_lengths(n-1) = Scalar(1); + } + + /** + * \brief Spline fitting methods. + * \ingroup Splines_Module + **/ + template + struct SplineFitting + { + typedef typename SplineType::KnotVectorType KnotVectorType; + typedef typename SplineType::ParameterVectorType ParameterVectorType; + + /** + * \brief Fits an interpolating Spline to the given data points. + * + * \param pts The points for which an interpolating spline will be computed. + * \param degree The degree of the interpolating spline. + * + * \returns A spline interpolating the initially provided points. + **/ + template + static SplineType Interpolate(const PointArrayType& pts, DenseIndex degree); + + /** + * \brief Fits an interpolating Spline to the given data points. + * + * \param pts The points for which an interpolating spline will be computed. + * \param degree The degree of the interpolating spline. + * \param knot_parameters The knot parameters for the interpolation. + * + * \returns A spline interpolating the initially provided points. + **/ + template + static SplineType Interpolate(const PointArrayType& pts, DenseIndex degree, const KnotVectorType& knot_parameters); + + /** + * \brief Fits an interpolating spline to the given data points and + * derivatives. + * + * \param points The points for which an interpolating spline will be computed. + * \param derivatives The desired derivatives of the interpolating spline at interpolation + * points. + * \param derivativeIndices An array indicating which point each derivative belongs to. This + * must be the same size as @a derivatives. + * \param degree The degree of the interpolating spline. + * + * \returns A spline interpolating @a points with @a derivatives at those points. + * + * \sa Les A. Piegl, Khairan Rajab, Volha Smarodzinana. 2008. + * Curve interpolation with directional constraints for engineering design. + * Engineering with Computers + **/ + template + static SplineType InterpolateWithDerivatives(const PointArrayType& points, + const PointArrayType& derivatives, + const IndexArray& derivativeIndices, + const unsigned int degree); + + /** + * \brief Fits an interpolating spline to the given data points and derivatives. + * + * \param points The points for which an interpolating spline will be computed. + * \param derivatives The desired derivatives of the interpolating spline at interpolation points. + * \param derivativeIndices An array indicating which point each derivative belongs to. This + * must be the same size as @a derivatives. + * \param degree The degree of the interpolating spline. + * \param parameters The parameters corresponding to the interpolation points. + * + * \returns A spline interpolating @a points with @a derivatives at those points. + * + * \sa Les A. Piegl, Khairan Rajab, Volha Smarodzinana. 2008. + * Curve interpolation with directional constraints for engineering design. + * Engineering with Computers + */ + template + static SplineType InterpolateWithDerivatives(const PointArrayType& points, + const PointArrayType& derivatives, + const IndexArray& derivativeIndices, + const unsigned int degree, + const ParameterVectorType& parameters); + }; + + template + template + SplineType SplineFitting::Interpolate(const PointArrayType& pts, DenseIndex degree, const KnotVectorType& knot_parameters) + { + typedef typename SplineType::KnotVectorType::Scalar Scalar; + typedef typename SplineType::ControlPointVectorType ControlPointVectorType; + + typedef Matrix MatrixType; + + KnotVectorType knots; + KnotAveraging(knot_parameters, degree, knots); + + DenseIndex n = pts.cols(); + MatrixType A = MatrixType::Zero(n,n); + for (DenseIndex i=1; i qr(A); + + // Here, we are creating a temporary due to an Eigen issue. + ControlPointVectorType ctrls = qr.solve(MatrixType(pts.transpose())).transpose(); + + return SplineType(knots, ctrls); + } + + template + template + SplineType SplineFitting::Interpolate(const PointArrayType& pts, DenseIndex degree) + { + KnotVectorType chord_lengths; // knot parameters + ChordLengths(pts, chord_lengths); + return Interpolate(pts, degree, chord_lengths); + } + + template + template + SplineType + SplineFitting::InterpolateWithDerivatives(const PointArrayType& points, + const PointArrayType& derivatives, + const IndexArray& derivativeIndices, + const unsigned int degree, + const ParameterVectorType& parameters) + { + typedef typename SplineType::KnotVectorType::Scalar Scalar; + typedef typename SplineType::ControlPointVectorType ControlPointVectorType; + + typedef Matrix MatrixType; + + const DenseIndex n = points.cols() + derivatives.cols(); + + KnotVectorType knots; + + KnotAveragingWithDerivatives(parameters, degree, derivativeIndices, knots); + + // fill matrix + MatrixType A = MatrixType::Zero(n, n); + + // Use these dimensions for quicker populating, then transpose for solving. + MatrixType b(points.rows(), n); + + DenseIndex startRow; + DenseIndex derivativeStart; + + // End derivatives. + if (derivativeIndices[0] == 0) + { + A.template block<1, 2>(1, 0) << -1, 1; + + Scalar y = (knots(degree + 1) - knots(0)) / degree; + b.col(1) = y*derivatives.col(0); + + startRow = 2; + derivativeStart = 1; + } + else + { + startRow = 1; + derivativeStart = 0; + } + if (derivativeIndices[derivatives.cols() - 1] == points.cols() - 1) + { + A.template block<1, 2>(n - 2, n - 2) << -1, 1; + + Scalar y = (knots(knots.size() - 1) - knots(knots.size() - (degree + 2))) / degree; + b.col(b.cols() - 2) = y*derivatives.col(derivatives.cols() - 1); + } + + DenseIndex row = startRow; + DenseIndex derivativeIndex = derivativeStart; + for (DenseIndex i = 1; i < parameters.size() - 1; ++i) + { + const DenseIndex span = SplineType::Span(parameters[i], degree, knots); + + if (derivativeIndex < derivativeIndices.size() && derivativeIndices[derivativeIndex] == i) + { + A.block(row, span - degree, 2, degree + 1) + = SplineType::BasisFunctionDerivatives(parameters[i], 1, degree, knots); + + b.col(row++) = points.col(i); + b.col(row++) = derivatives.col(derivativeIndex++); + } + else + { + A.row(row).segment(span - degree, degree + 1) + = SplineType::BasisFunctions(parameters[i], degree, knots); + b.col(row++) = points.col(i); + } + } + b.col(0) = points.col(0); + b.col(b.cols() - 1) = points.col(points.cols() - 1); + A(0,0) = 1; + A(n - 1, n - 1) = 1; + + // Solve + FullPivLU lu(A); + ControlPointVectorType controlPoints = lu.solve(MatrixType(b.transpose())).transpose(); + + SplineType spline(knots, controlPoints); + + return spline; + } + + template + template + SplineType + SplineFitting::InterpolateWithDerivatives(const PointArrayType& points, + const PointArrayType& derivatives, + const IndexArray& derivativeIndices, + const unsigned int degree) + { + ParameterVectorType parameters; + ChordLengths(points, parameters); + return InterpolateWithDerivatives(points, derivatives, derivativeIndices, degree, parameters); + } +} + +#endif // EIGEN_SPLINE_FITTING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFwd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFwd.h new file mode 100644 index 0000000000000000000000000000000000000000..2cc0977983d2dee737963e8833a9b246d178e791 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/unsupported/Eigen/src/Splines/SplineFwd.h @@ -0,0 +1,94 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 20010-2011 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPLINES_FWD_H +#define EIGEN_SPLINES_FWD_H + +#include "./InternalHeaderCheck.h" +#include "../../../../Eigen/Core" + +namespace Eigen +{ + template class Spline; + + template < typename SplineType, int DerivativeOrder = Dynamic > struct SplineTraits {}; + + /** + * \ingroup Splines_Module + * \brief Compile-time attributes of the Spline class for Dynamic degree. + **/ + template + struct SplineTraits< Spline, Dynamic > + { + typedef Scalar_ Scalar; /*!< The spline curve's scalar type. */ + enum { Dimension = Dim_ /*!< The spline curve's dimension. */ }; + enum { Degree = Degree_ /*!< The spline curve's degree. */ }; + + enum { OrderAtCompileTime = Degree_==Dynamic ? Dynamic : Degree_+1 /*!< The spline curve's order at compile-time. */ }; + enum { NumOfDerivativesAtCompileTime = OrderAtCompileTime /*!< The number of derivatives defined for the current spline. */ }; + + enum { DerivativeMemoryLayout = Dimension==1 ? RowMajor : ColMajor /*!< The derivative type's memory layout. */ }; + + /** \brief The data type used to store non-zero basis functions. */ + typedef Array BasisVectorType; + + /** \brief The data type used to store the values of the basis function derivatives. */ + typedef Array BasisDerivativeType; + + /** \brief The data type used to store the spline's derivative values. */ + typedef Array DerivativeType; + + /** \brief The point type the spline is representing. */ + typedef Array PointType; + + /** \brief The data type used to store knot vectors. */ + typedef Array KnotVectorType; + + /** \brief The data type used to store parameter vectors. */ + typedef Array ParameterVectorType; + + /** \brief The data type representing the spline's control points. */ + typedef Array ControlPointVectorType; + }; + + /** + * \ingroup Splines_Module + * \brief Compile-time attributes of the Spline class for fixed degree. + * + * The traits class inherits all attributes from the SplineTraits of Dynamic degree. + **/ + template < typename Scalar_, int Dim_, int Degree_, int _DerivativeOrder > + struct SplineTraits< Spline, _DerivativeOrder > : public SplineTraits< Spline > + { + enum { OrderAtCompileTime = Degree_==Dynamic ? Dynamic : Degree_+1 /*!< The spline curve's order at compile-time. */ }; + enum { NumOfDerivativesAtCompileTime = _DerivativeOrder==Dynamic ? Dynamic : _DerivativeOrder+1 /*!< The number of derivatives defined for the current spline. */ }; + + enum { DerivativeMemoryLayout = Dim_==1 ? RowMajor : ColMajor /*!< The derivative type's memory layout. */ }; + + /** \brief The data type used to store the values of the basis function derivatives. */ + typedef Array BasisDerivativeType; + + /** \brief The data type used to store the spline's derivative values. */ + typedef Array DerivativeType; + }; + + /** \brief 2D float B-spline with dynamic degree. */ + typedef Spline Spline2f; + + /** \brief 3D float B-spline with dynamic degree. */ + typedef Spline Spline3f; + + /** \brief 2D double B-spline with dynamic degree. */ + typedef Spline Spline2d; + + /** \brief 3D double B-spline with dynamic degree. */ + typedef Spline Spline3d; +} + +#endif // EIGEN_SPLINES_FWD_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array.h new file mode 100644 index 0000000000000000000000000000000000000000..93c956beaeff8a6f5c484f4322289713fff53be7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array.h @@ -0,0 +1,702 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ARRAY_H_ +#define XLA_ARRAY_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "xla/status.h" +#include "xla/types.h" + +namespace xla { + +namespace array_impl { + +template +using overload_for_float = std::enable_if_t< + is_specialized_floating_point_v && std::is_same::value, bool>; + +// A type trait that is valid when all elements in a parameter pack are of +// integral type. Not using an alias template to work around MSVC 14.00 bug. +template +struct pack_is_integral : std::conjunction...> {}; + +// Compares three same-sized vectors elementwise. For each item in `values`, +// returns false if any of values[i] is outside the half-open range [starts[i], +// ends[i]). +template +bool all_inside_range(const C1& values, const C2& range_starts, + const C3& range_ends) { + for (size_t i = 0, e = values.size(); i < e; ++i) { + if (values[i] < range_starts[i] || values[i] >= range_ends[i]) { + return false; + } + } + return true; +} + +} // namespace array_impl + +// General N dimensional array class with arbitrary value type. +template +class Array { + public: + // Type inference can have a hard time parsing very deep initializer list + // nests, especially if one or more dimensions is one as the compiler just + // sees a single-element integer initializer. These typedefs allow casting + // explicitly with less typing. + template + using InitializerList1D = std::initializer_list; + template + using InitializerList2D = std::initializer_list>; + template + using InitializerList3D = std::initializer_list>; + template + using InitializerList4D = std::initializer_list>; + + using value_type = T; + + // Creates a new array with the specified dimensions and initialized elements. + explicit Array(absl::Span sizes) + : sizes_(sizes.size()), + values_(calculate_elements(sizes), default_init_t{}) { + std::memcpy(sizes_.data.get(), sizes.data(), + sizeof(int64_t) * sizes.size()); + } + + // Creates a new array with the specified dimensions and specified value for + // every cell. + Array(absl::Span sizes, T value) + : Array(sizes, no_default_init_t{}) { + Fill(value); + } + + // Creates a 2D array from the given nested initializer list. The outer + // initializer list is the first dimension, the inner is the second dimension. + // For example, {{1, 2, 3}, {4, 5, 6}} results in an array with n1=2 and n2=3. + Array(InitializerList2D values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + values_[idx] = it2; + ++idx; + } + } + CHECK(idx == num_elements()); + } + + // Creates a 1D array of a floating-point type (half, bfloat16, float, + // or double) from an initializer list of float values. + template = true> + Array(std::initializer_list values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + values_[idx] = static_cast(it1); + ++idx; + } + CHECK(idx == num_elements()); + } + + // Creates a 2D array of a floating-point type (float8, half, bfloat16, float, + // or double) from an initializer list of float values. + template = true> + Array(std::initializer_list> values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + values_[idx] = static_cast(it2); + ++idx; + } + } + CHECK(idx == num_elements()); + } + + // Creates a 3D array from the given nested initializer list. The outer + // initializer list is the first dimension, and so on. + Array(InitializerList3D values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + for (const auto& it3 : it2) { + values_[idx] = it3; + ++idx; + } + } + } + CHECK(idx == num_elements()); + } + + // Creates a 3D array of a floating-point type (half, bfloat16, float, + // or double) from an initializer list of float values. + template = true> + Array(std::initializer_list>> + values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + for (const auto& it3 : it2) { + values_[idx] = static_cast(it3); + ++idx; + } + } + } + CHECK(idx == num_elements()); + } + + // Creates a 4D array from the given nested initializer list. The outer + // initializer list is the first dimension, and so on. + Array(InitializerList4D values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + for (const auto& it3 : it2) { + for (const auto& it4 : it3) { + values_[idx] = it4; + ++idx; + } + } + } + } + CHECK(idx == num_elements()); + } + + // Creates a 4D array of a floating-point type (half, bfloat16, float, + // or double) from an initializer list of float values. + template = true> + Array(std::initializer_list< + std::initializer_list>>> + values) + : Array(ToInt64Array(values), no_default_init_t{}) { + int64_t idx = 0; + for (const auto& it1 : values) { + for (const auto& it2 : it1) { + for (const auto& it3 : it2) { + for (const auto& it4 : it3) { + values_[idx] = static_cast(it4); + ++idx; + } + } + } + } + CHECK(idx == num_elements()); + } + + Array(const Array& other) + : sizes_(other.sizes_.Clone()), values_(other.values_.Clone()) {} + + Array(Array&& other) = default; + + Array& operator=(const Array& other) { + sizes_ = other.sizes_.Clone(); + values_ = other.values_.Clone(); + return *this; + } + + Array& operator=(Array&& other) = default; + + // Fills the array with the specified value. + void Fill(const T& value) { std::fill(begin(), end(), value); } + + // Fills the array with sequentially increasing values. + void FillIota(const T& value) { std::iota(begin(), end(), value); } + + // Fills the array with a repeating sequence: + // [value, value + 1, ..., value + length - 1, value, ... ] + void FillRepeatedIota(const T& value, int64_t length) { + for (int64_t i = 0; i < num_elements(); i += length) { + std::iota(begin() + i, begin() + std::min(i + length, num_elements()), + value); + } + } + + // Fills the array with the sequence i*multiplier for i=0,1,... + void FillWithMultiples(const T& multiplier) { + for (int64_t i = 0; i < num_elements(); ++i) { + values_[i] = static_cast(i) * multiplier; + } + } + + // Fills the array with random normal variables with the specified mean. + void FillRandom(const T& stddev, double mean = 0.0, int seed = 12345) { + FillRandomDouble(static_cast(stddev), mean, seed); + } + + void FillRandomDouble(double stddev, double mean = 0.0, int seed = 12345) { + std::mt19937 g(seed); + std::normal_distribution distribution(mean, stddev); + for (int64_t i = 0; i < num_elements(); ++i) { + if (std::is_same()) { + values_[i] = static_cast(distribution(g) > 0.0); + } else { + values_[i] = static_cast(distribution(g)); + } + } + } + + // Fills the array with random uniform variables in the [min_value, max_value] + // range. Defined for integral types. + template ::value>> + void FillRandomUniform(const T& min_value, const T& max_value, + int seed = 12345) { + std::mt19937 g(seed); + std::uniform_int_distribution distribution(min_value, max_value); + for (int64_t i = 0; i < num_elements(); ++i) { + values_[i] = static_cast(distribution(g)); + } + } + + // Fills the array with random uniform variables that's either True or False. + // Defined for boolean type. + void FillRandomBool(int seed = 12345) { + std::mt19937 g(seed); + std::uniform_int_distribution distribution(0, 1); + for (int64_t i = 0; i < num_elements(); ++i) { + values_[i] = static_cast(distribution(g)); + } + } + + // Sets all the values in the array to values specified in the container. + template > + void SetValues(const Container& container) { + CHECK_EQ(std::distance(std::begin(container), std::end(container)), + num_elements()); + std::copy(std::begin(container), std::end(container), begin()); + } + + // Invokes a callback with the (indices, value_ptr) for each cell in the + // array. + void Each(absl::FunctionRef, T*)> f) { + OwnedBuffer index(sizes_.size, default_init_t{}); + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + f(index.span(), &values_[i]); + } + } + + // Invokes a callback with the (indices, value) for each cell in the array. + void Each(absl::FunctionRef, T)> f) const { + OwnedBuffer index(sizes_.size, default_init_t{}); + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + f(index.span(), values_[i]); + } + } + + // Invokes a callback with the (indices, value_ptr) for each cell in the + // array. If a callback returns a non-OK status, returns that else returns + // OkStatus(). + Status EachStatus( + absl::FunctionRef, T*)> f) { + OwnedBuffer index(sizes_.size, default_init_t{}); + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + Status s = f(index.span(), &values_[i]); + if (!s.ok()) { + return s; + } + } + return OkStatus(); + } + + // Invokes a callback with the (indices, value) for each cell in the array. + // If a callback returns a non-OK status, returns that else returns + // OkStatus(). + Status EachStatus( + absl::FunctionRef, T)> f) const { + OwnedBuffer index(sizes_.size, default_init_t{}); + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + Status s = f(index.span(), values_[i]); + if (!s.ok()) { + return s; + } + } + return OkStatus(); + } + + // Returns the value at the cell specified by the indexes. The number of + // arguments have to match with the number of dimensions for the array. + // + // The type trait is required to avoid this overload participating too + // eagerly; a parameter pack can take zero or more elements, so we must + // restrict this to only parameter packs that are all of integral type. + template + typename std::enable_if::value, + const T&>::type + operator()(Dims... dims) const { + CHECK_EQ(sizeof...(dims), num_dimensions()); + // We are using a std::array to avoid having to allocate memory in this + // function for performance reasons. + std::array indexes{ + {static_cast(dims)...}}; + return values_[calculate_index(indexes)]; + } + + // Returns the value at the cell specified by the indexes. The number of + // arguments have to match with the number of dimensions for the array. + template + typename std::enable_if::value, + T&>::type + operator()(Dims... dims) { + return const_cast(const_cast(this)->operator()( + std::forward(dims)...)); + } + + // Returns the value at the cell specified by the indexes. The number of + // arguments have to match with the number of dimensions for the array. + const T& operator()(absl::Span indexes) const { + CHECK_EQ(indexes.size(), num_dimensions()); + return values_[calculate_index(indexes)]; + } + + // Returns the value at the cell specified by the indexes. The number of + // arguments have to match with the number of dimensions for the array. + T& operator()(absl::Span indexes) { + return const_cast(const_cast(this)->operator()(indexes)); + } + + // Low-level accessor for stuff like memcmp, handle with care. Returns pointer + // to the underlying storage of the array (similarly to std::vector::data()). + T* data() const { + // TODO(tberghammer): Get rid of the const_cast. Currently it is needed + // because the Eigen backend needs a non-const pointers even for reading + // from the array. + return const_cast(this)->values_.data.get(); + } + + // Returns the size of the dimension at the given index. + int64_t dim(int64_t n) const { + DCHECK_LT(n, sizes_.size); + return sizes_[n]; + } + + // Returns a vector containing the dimensions of the array. + absl::Span dimensions() const { return sizes_.span(); } + + int64_t num_dimensions() const { return sizes_.size; } + + // Returns the total number of elements in the array. + int64_t num_elements() const { return values_.size; } + + const T* begin() const { return values_.data.get(); } + T* begin() { return values_.data.get(); } + const T* end() const { return values_.data.get() + num_elements(); } + T* end() { return values_.data.get() + num_elements(); } + + bool operator==(const Array& other) const { + if (sizes_.size != other.sizes_.size) { + return false; + } + for (int64_t i = 0, end = sizes_.size; i < end; ++i) { + if (sizes_[i] != other.sizes_[i]) { + return false; + } + } + for (int64_t i = 0; i < num_elements(); ++i) { + if (values_[i] != other.values_[i]) { + return false; + } + } + return true; + } + + bool operator!=(const Array& other) const { return !(*this == other); } + + // Performs the equivalent of a slice operation on this array. + Array Slice(absl::Span starts, + absl::Span limits) const { + CHECK_EQ(starts.size(), num_dimensions()); + CHECK_EQ(limits.size(), num_dimensions()); + + OwnedBuffer sizes(starts.size()); + for (int64_t i = 0; i < starts.size(); ++i) { + sizes[i] = limits[i] - starts[i]; + } + Array result(sizes.span()); + + OwnedBuffer index(sizes_.size, default_init_t{}); + int64_t slice_i = 0; + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + if (array_impl::all_inside_range(index.span(), starts, limits)) { + // Even though the bounds of result are different to our bounds, we're + // iterating in the same order. So we can simply write successive linear + // indices instead of recalculating a multi-dimensional index. + result.values_[slice_i++] = values_[i]; + } + } + return result; + } + + // Performs the equivalent of a DynamicUpdateSlice in-place on this array. + void UpdateSlice(const Array& from, + absl::Span start_indices) { + CHECK_EQ(from.num_dimensions(), num_dimensions()); + OwnedBuffer limit_indices(start_indices.size()); + for (int64_t i = 0; i < start_indices.size(); ++i) { + limit_indices[i] = from.sizes_[i] + start_indices[i]; + } + OwnedBuffer index(sizes_.size, default_init_t{}); + int64_t from_i = 0; + for (int64_t i = 0; i < num_elements(); ++i, next_index(&index)) { + if (array_impl::all_inside_range(index.span(), start_indices, + limit_indices)) { + // Even though the bounds of from are different to our bounds, we're + // iterating in the same order. So we can simply write successive linear + // indices instead of recalculating a multi-dimensional index. + values_[i] = from.values_[from_i++]; + } + } + } + + // Performs an in-place reshape, modifying the dimensions but not the + // underlying data. + void Reshape(absl::Span new_dimensions) { + const int64_t new_num_elements = + std::accumulate(new_dimensions.begin(), new_dimensions.end(), 1LL, + std::multiplies()); + CHECK_EQ(new_num_elements, num_elements()); + if (sizes_.size != new_dimensions.size()) { + sizes_ = OwnedBuffer(new_dimensions.size()); + } + std::memcpy(sizes_.data.get(), new_dimensions.data(), + new_dimensions.size() * sizeof(int64_t)); + } + + // Performs a permutation of dimensions. + void TransposeDimensions(absl::Span permutation) { + return TransposeDimensionsImpl(permutation); + } + void TransposeDimensions(absl::Span permutation) { + return TransposeDimensionsImpl(permutation); + } + void TransposeDimensions(std::initializer_list permutation) { + return TransposeDimensionsImpl(permutation); + } + template >* = nullptr> + void TransposeDimensionsImpl(absl::Span permutation) { + CHECK_EQ(sizes_.size, permutation.size()); + OwnedBuffer permuted_dims(permutation.size()); + for (int64_t i = 0; i < permutation.size(); ++i) { + permuted_dims[i] = this->dim(permutation[i]); + } + Array permuted(permuted_dims.span()); + OwnedBuffer src_indices(sizes_.size, -1); + permuted.Each([&](absl::Span indices, T* value) { + for (int64_t i = 0; i < sizes_.size; ++i) { + src_indices[permutation[i]] = indices[i]; + } + *value = (*this)(src_indices.span()); + }); + *this = std::move(permuted); + } + + template + friend H AbslHashValue(H h, const Array& array) { + return H::combine(std::move(h), array.values_.span(), array.dimensions()); + } + + // Returns a string representation of the array suitable for debugging. + std::string ToString() const { + if (sizes_.size == 0) { + return ""; + } + std::string result; + OwnedBuffer index(sizes_.size, default_init_t{}); + do { + // Emit leading spaces and opening square brackets + if (index[index.size - 1] == 0) { + for (int64_t i = sizes_.size - 1; i >= 0; --i) { + if (i == 0 || index[i - 1] != 0) { + for (int64_t j = 0; j < sizes_.size; ++j) { + absl::StrAppend(&result, j < i ? " " : "["); + } + break; + } + } + } + int value_index = calculate_index(index.span()); + if (value_index < num_elements()) { + absl::StrAppend(&result, values_[value_index]); + } + + // Emit comma if it isn't the last element + if (index[index.size - 1] < sizes_[sizes_.size - 1] - 1) { + absl::StrAppend(&result, ", "); + } + + // Emit closing square brackets + for (int64_t i = sizes_.size - 1; i >= 0; --i) { + if (index[i] < sizes_[i] - 1) { + break; + } + absl::StrAppend(&result, "]"); + if (i != 0 && index[i - 1] < sizes_[i - 1] - 1) { + absl::StrAppend(&result, ",\n"); + } + } + } while (next_index(&index)); + return result; + } + + private: + struct default_init_t {}; + struct no_default_init_t {}; + // A fixed sized dynamically allocated buffer to replace std::vector usage. It + // saves one word for storing capacity which is always the same as size and it + // provides the ability to leave its elements uninitialized if the element + // type is trivially destructible. + template + struct OwnedBuffer { + explicit OwnedBuffer(size_t size) + : data(std::is_trivially_destructible_v ? new D[size] + : new D[size]()), + size(size) {} + explicit OwnedBuffer(size_t size, default_init_t) + : data(new D[size]()), size(size) {} + + explicit OwnedBuffer(size_t size, D init) : OwnedBuffer(size) { + std::fill(data.get(), data.get() + size, init); + } + + OwnedBuffer(OwnedBuffer&& other) + : data(std::move(other.data)), size(other.size) { + other.size = 0; + } + + OwnedBuffer& operator=(OwnedBuffer&& other) { + data = std::move(other.data); + size = other.size; + other.size = 0; + return *this; + } + + OwnedBuffer Clone() const { + OwnedBuffer clone(size); + std::memcpy(clone.data.get(), data.get(), size * sizeof(D)); + return clone; + } + + D& operator[](int64_t index) { return data[index]; } + const D& operator[](int64_t index) const { return data[index]; } + + absl::Span span() const { + return absl::MakeConstSpan(data.get(), size); + } + + std::unique_ptr data; + size_t size; + }; + + explicit Array(absl::Span sizes, no_default_init_t) + : sizes_(sizes.size()), values_(calculate_elements(sizes)) { + std::memcpy(sizes_.data.get(), sizes.data(), + sizeof(int64_t) * sizes.size()); + } + + // Extracts the dimensions of an initializer_list to an array type int64_t. + // Used by the initializer list based constructors to convert the size type + // into int64_t to be passed to the size based constructor. + template + static std::array ToInt64Array(const InitializerList1D& data) { + return std::array{static_cast(data.size())}; + } + + template + static std::array ToInt64Array(const InitializerList2D& data) { + return std::array{static_cast(data.size()), + static_cast(data.begin()->size())}; + } + + template + static std::array ToInt64Array(const InitializerList3D& data) { + return std::array{ + static_cast(data.size()), + static_cast(data.begin()->size()), + static_cast(data.begin()->begin()->size())}; + } + + template + static std::array ToInt64Array(const InitializerList4D& data) { + return std::array{ + static_cast(data.size()), + static_cast(data.begin()->size()), + static_cast(data.begin()->begin()->size()), + static_cast(data.begin()->begin()->begin()->size())}; + } + + // Returns the linear index from the list of per-dimension indexes. Function + // is templated so can be used with an std::array from operator() to avoid + // memory allocation. + // The returned value may be larger than or equal to the number of elements if + // the indexes exceed the array's corresponding dimension size. + int64_t calculate_index(absl::Span indexes) const { + DCHECK_EQ(sizes_.size, indexes.size()); + int64_t index = 0; + for (int64_t i = 0; i < sizes_.size; ++i) { + index *= sizes_[i]; + index += indexes[i]; + } + return index; + } + + // Advances the specified set of indexes and returns true if we haven't + // wrapped around (i.e. result isn't {0, 0, ...}). + bool next_index(OwnedBuffer* index) const { + DCHECK_EQ(index->size, sizes_.size); + for (int64_t i = sizes_.size - 1; i >= 0; --i) { + (*index)[i]++; + if ((*index)[i] < sizes_[i]) { + return true; + } + (*index)[i] = 0; + } + return false; + } + + static size_t calculate_elements(absl::Span sizes) { + return std::accumulate(sizes.begin(), sizes.end(), 1LL, + std::multiplies()); + } + + OwnedBuffer sizes_; + OwnedBuffer values_; +}; + +// Specialization of FillRandom() method for complex64 type. Uses real part of +// the stddev parameter as the standard deviation value. +template <> +void Array::FillRandom(const complex64& stddev, double mean, + int seed); + +} // namespace xla + +#endif // XLA_ARRAY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array2d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array2d.h new file mode 100644 index 0000000000000000000000000000000000000000..8f86c09d4fc37dd0f73b0a80c446889a72ff0def --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array2d.h @@ -0,0 +1,112 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ARRAY2D_H_ +#define XLA_ARRAY2D_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "absl/strings/str_cat.h" +#include "xla/array.h" +#include "xla/types.h" +#include "xla/util.h" + +namespace xla { + +template +class Array2D : public Array { + public: + Array2D() : Array(std::vector{0, 0}) {} + + Array2D(const int64_t n1, const int64_t n2) + : Array(std::vector{n1, n2}) {} + + Array2D(const int64_t n1, const int64_t n2, const T value) + : Array({n1, n2}, value) {} + + // Creates an array from the given nested initializer list. The outer + // initializer list is the first dimension; the inner is the second dimension. + // For example, {{1, 2, 3}, {4, 5, 6}} results in an array with n1=2 and n2=3. + Array2D(std::initializer_list> values) + : Array(values) {} + + // Creates an array of a floating-point type (float8, half, bfloat16, float, + // or double) from the given nested initializer list of float values. + template = true> + Array2D(std::initializer_list> values) + : Array(values) {} + + Array2D(const Array2D& other) : Array(other) {} + + int64_t n1() const { return this->dim(0); } + int64_t n2() const { return this->dim(1); } + + int64_t height() const { return this->dim(0); } + int64_t width() const { return this->dim(1); } + + // Fills the array with a pattern of values of the form: + // + // (rowno << log2ceil(width) | colno) + start_value + // + // This makes it easy to see distinct row/column values in the array. + void FillUnique(T start_value = 0) { + int shift = Log2Ceiling(n2()); + for (int64_t i0 = 0; i0 < n1(); ++i0) { + for (int64_t i1 = 0; i1 < n2(); ++i1) { + (*this)(i0, i1) = ((i0 << shift) | i1) + start_value; + } + } + } + + // Applies f to all cells in this array, in row-major order. + void Each(absl::FunctionRef f) { + for (int64_t i0 = 0; i0 < n1(); ++i0) { + for (int64_t i1 = 0; i1 < n2(); ++i1) { + f(i0, i1, &(*this)(i0, i1)); + } + } + } +}; + +// Returns a linspace-populated Array2D in the range [from, to] (inclusive) +// with dimensions n1 x n2. +template +std::unique_ptr> MakeLinspaceArray2D(double from, double to, + int64_t n1, int64_t n2) { + auto array = std::make_unique>(n1, n2); + int64_t count = n1 * n2; + NativeT step = + static_cast((count > 1) ? (to - from) / (count - 1) : 0); + auto set = [&array, n2](int64_t index, NativeT value) { + (*array)(index / n2, index % n2) = value; + }; + for (int64_t i = 0; i < count - 1; ++i) { + set(i, (static_cast(from) + + static_cast(i) * static_cast(step))); + } + set(count - 1, static_cast(to)); + return array; +} +} // namespace xla + +#endif // XLA_ARRAY2D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array3d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array3d.h new file mode 100644 index 0000000000000000000000000000000000000000..6c8b81d165ec10292badd180be1dd54cbb10a66c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array3d.h @@ -0,0 +1,73 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ARRAY3D_H_ +#define XLA_ARRAY3D_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "xla/array.h" +#include "xla/types.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Simple 3D array structure. +template +class Array3D : public Array { + public: + Array3D() : Array(std::vector{0, 0, 0}) {} + + // Creates an array of dimensions n1 x n2 x n3, uninitialized values. + Array3D(const int64_t n1, const int64_t n2, const int64_t n3) + : Array(std::vector{n1, n2, n3}) {} + + // Creates an array of dimensions n1 x n2 x n3, initialized to value. + Array3D(const int64_t n1, const int64_t n2, const int64_t n3, const T value) + : Array(std::vector{n1, n2, n3}, value) {} + + // Creates an array from the given nested initializer list. The outer + // initializer list is the first dimension, and so on. + // + // For example {{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, + // {{9, 10}, {11, 12}, {13, 14}, {15, 16}}, + // {{17, 18}, {19, 20}, {21, 22}, {23, 24}}} + // results in an array with n1=3, n2=4, n3=2. + Array3D(std::initializer_list>> + values) + : Array(values) {} + + // Creates an array of a floating-point type (half, bfloat16, float, + // or double) from the given nested initializer list of float values. + template = true> + Array3D( + std::initializer_list>> + values) + : Array(values) {} + + int64_t n1() const { return this->dim(0); } + int64_t n2() const { return this->dim(1); } + int64_t n3() const { return this->dim(2); } +}; + +} // namespace xla + +#endif // XLA_ARRAY3D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array4d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array4d.h new file mode 100644 index 0000000000000000000000000000000000000000..0b4549dd0a85909f5fa86e89fc50e0baffadb1a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/array4d.h @@ -0,0 +1,170 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ARRAY4D_H_ +#define XLA_ARRAY4D_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "xla/array.h" +#include "xla/array2d.h" +#include "xla/types.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Simple 4D array structure, similar in form to Array2D, for use primarily in +// testing and describing to XLA APIs values in the 4D array structures used +// in convolutions. +// +// The data layout is, in order from major to minor: +// +// First dimension: plane, batch, n1 +// Second dimension: depth, feature, z, n2 +// Third dimension: height, y, n3 +// Fourth dimension: width, x, n4 +// +// These dimensions are referred to by various names, so that is why +// more than one name is given above. See operator() for the exact +// calculation of 1d indices from 4d indices. +template +class Array4D : public Array { + public: + Array4D() : Array(std::vector{0, 0, 0, 0}) {} + + // Creates a 4D array, uninitialized values. + Array4D(int64_t planes, int64_t depth, int64_t height, int64_t width) + : Array(std::vector{planes, depth, height, width}) {} + + // Creates a 4D array, initialized to value. + Array4D(int64_t planes, int64_t depth, int64_t height, int64_t width, T value) + : Array(std::vector{planes, depth, height, width}, value) {} + + // Creates a 4D array, filled with values. + // + // We need to set a default type for Container so that code like + // Array4D(1, 1, 1, 1, {1}) will work. The template cannot infer the + // initializer_list type in that case without this default. + template > + Array4D(int64_t planes, int64_t depth, int64_t height, int64_t width, + const Container& values) + : Array4D(planes, depth, height, width) { + this->SetValues(values); + } + + // Construct an Array4D with the given nested initializer list. + Array4D(std::initializer_list>>> + values) + : Array(values) {} + + // Creates an array of a floating-point type (half, bfloat16, float, + // or double) from the given nested initializer list of float values. + template = true> + Array4D(std::initializer_list>>> + values) + : Array(values) {} + + // Numerically-named aliases for the various dimensions. This matches the + // dimension names used in array3d. + int64_t n4() const { return this->dim(3); } + int64_t n3() const { return this->dim(2); } + int64_t n2() const { return this->dim(1); } + int64_t n1() const { return this->dim(0); } + + int64_t width() const { return this->dim(3); } + int64_t height() const { return this->dim(2); } + int64_t depth() const { return this->dim(1); } + int64_t planes() const { return this->dim(0); } + + // Fills all of the {p,z} with the array provided, which specifies {y,x}. + void FillWithYX(const Array2D& value) { + CHECK_EQ(value.height(), height()); + CHECK_EQ(value.width(), width()); + for (int64_t plane = 0; plane < planes(); ++plane) { + for (int64_t depth = 0; depth < this->depth(); ++depth) { + for (int64_t height = 0; height < this->height(); ++height) { + for (int64_t width = 0; width < this->width(); ++width) { + (*this)(plane, depth, height, width) = value(height, width); + } + } + } + } + } + + // Fills all of the {p,x} with the array provided, which specifies {z,y}. + void FillWithZY(const Array2D& value) { + CHECK_EQ(value.height(), depth()); + CHECK_EQ(value.width(), height()); + for (int64_t plane = 0; plane < planes(); ++plane) { + for (int64_t depth = 0; depth < this->depth(); ++depth) { + for (int64_t height = 0; height < this->height(); ++height) { + for (int64_t width = 0; width < this->width(); ++width) { + (*this)(plane, depth, height, width) = value(depth, height); + } + } + } + } + } + + // Fills all of the {x,y} with the array provided, which specifies {p,z}. + void FillWithPZ(const Array2D& value) { + CHECK_EQ(value.height(), planes()); + CHECK_EQ(value.width(), depth()); + for (int64_t height = 0; height < this->height(); ++height) { + for (int64_t width = 0; width < this->width(); ++width) { + for (int64_t plane = 0; plane < planes(); ++plane) { + for (int64_t depth = 0; depth < this->depth(); ++depth) { + (*this)(plane, depth, height, width) = value(plane, depth); + } + } + } + } + } + + // Fills each of the minor-dim matrices with a number designating which minor + // dim matrix is enclosed by the shape. + void FillWithMinorDimNum() { + LOG(INFO) << "width: " << this->width(); + LOG(INFO) << "height: " << this->height(); + LOG(INFO) << "depth: " << this->depth(); + LOG(INFO) << "planes: " << this->planes(); + for (int64_t height = 0; height < this->height(); ++height) { + for (int64_t width = 0; width < this->width(); ++width) { + for (int64_t plane = 0; plane < planes(); ++plane) { + for (int64_t depth = 0; depth < this->depth(); ++depth) { + float this_val = plane * this->depth() + depth; + (*this)(plane, depth, height, width) = this_val; + } + } + } + } + } +}; + +} // namespace xla + +#endif // XLA_ARRAY4D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotune_results.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotune_results.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..9795b63d93bb86ea80a2a15a4ab3194c03878d6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotune_results.pb.h @@ -0,0 +1,694 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/autotune_results.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fautotune_5fresults_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fautotune_5fresults_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include "xla/autotuning.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fautotune_5fresults_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fautotune_5fresults_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fautotune_5fresults_2eproto; +namespace xla { +class AutotuneResults; +struct AutotuneResultsDefaultTypeInternal; +extern AutotuneResultsDefaultTypeInternal _AutotuneResults_default_instance_; +class AutotuneResults_Entry; +struct AutotuneResults_EntryDefaultTypeInternal; +extern AutotuneResults_EntryDefaultTypeInternal _AutotuneResults_Entry_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::AutotuneResults* Arena::CreateMaybeMessage<::xla::AutotuneResults>(Arena*); +template<> ::xla::AutotuneResults_Entry* Arena::CreateMaybeMessage<::xla::AutotuneResults_Entry>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +// =================================================================== + +class AutotuneResults_Entry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResults.Entry) */ { + public: + inline AutotuneResults_Entry() : AutotuneResults_Entry(nullptr) {} + ~AutotuneResults_Entry() override; + explicit PROTOBUF_CONSTEXPR AutotuneResults_Entry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResults_Entry(const AutotuneResults_Entry& from); + AutotuneResults_Entry(AutotuneResults_Entry&& from) noexcept + : AutotuneResults_Entry() { + *this = ::std::move(from); + } + + inline AutotuneResults_Entry& operator=(const AutotuneResults_Entry& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResults_Entry& operator=(AutotuneResults_Entry&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResults_Entry& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResults_Entry* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResults_Entry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(AutotuneResults_Entry& a, AutotuneResults_Entry& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResults_Entry* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResults_Entry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResults_Entry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResults_Entry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResults_Entry& from) { + AutotuneResults_Entry::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResults_Entry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResults.Entry"; + } + protected: + explicit AutotuneResults_Entry(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kDeviceFieldNumber = 1, + kHloFieldNumber = 2, + kResultFieldNumber = 3, + }; + // string device = 1; + void clear_device(); + const std::string& device() const; + template + void set_device(ArgT0&& arg0, ArgT... args); + std::string* mutable_device(); + PROTOBUF_NODISCARD std::string* release_device(); + void set_allocated_device(std::string* device); + private: + const std::string& _internal_device() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device(const std::string& value); + std::string* _internal_mutable_device(); + public: + + // string hlo = 2; + void clear_hlo(); + const std::string& hlo() const; + template + void set_hlo(ArgT0&& arg0, ArgT... args); + std::string* mutable_hlo(); + PROTOBUF_NODISCARD std::string* release_hlo(); + void set_allocated_hlo(std::string* hlo); + private: + const std::string& _internal_hlo() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_hlo(const std::string& value); + std::string* _internal_mutable_hlo(); + public: + + // .xla.AutotuneResult result = 3; + bool has_result() const; + private: + bool _internal_has_result() const; + public: + void clear_result(); + const ::xla::AutotuneResult& result() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult* release_result(); + ::xla::AutotuneResult* mutable_result(); + void set_allocated_result(::xla::AutotuneResult* result); + private: + const ::xla::AutotuneResult& _internal_result() const; + ::xla::AutotuneResult* _internal_mutable_result(); + public: + void unsafe_arena_set_allocated_result( + ::xla::AutotuneResult* result); + ::xla::AutotuneResult* unsafe_arena_release_result(); + + // @@protoc_insertion_point(class_scope:xla.AutotuneResults.Entry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hlo_; + ::xla::AutotuneResult* result_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotune_5fresults_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResults final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResults) */ { + public: + inline AutotuneResults() : AutotuneResults(nullptr) {} + ~AutotuneResults() override; + explicit PROTOBUF_CONSTEXPR AutotuneResults(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResults(const AutotuneResults& from); + AutotuneResults(AutotuneResults&& from) noexcept + : AutotuneResults() { + *this = ::std::move(from); + } + + inline AutotuneResults& operator=(const AutotuneResults& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResults& operator=(AutotuneResults&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResults& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResults* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResults_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(AutotuneResults& a, AutotuneResults& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResults* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResults* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResults* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResults& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResults& from) { + AutotuneResults::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResults* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResults"; + } + protected: + explicit AutotuneResults(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + typedef AutotuneResults_Entry Entry; + + // accessors ------------------------------------------------------- + + enum : int { + kResultsFieldNumber = 4, + kVersionFieldNumber = 1, + }; + // repeated .xla.AutotuneResults.Entry results = 4; + int results_size() const; + private: + int _internal_results_size() const; + public: + void clear_results(); + ::xla::AutotuneResults_Entry* mutable_results(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResults_Entry >* + mutable_results(); + private: + const ::xla::AutotuneResults_Entry& _internal_results(int index) const; + ::xla::AutotuneResults_Entry* _internal_add_results(); + public: + const ::xla::AutotuneResults_Entry& results(int index) const; + ::xla::AutotuneResults_Entry* add_results(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResults_Entry >& + results() const; + + // int32 version = 1; + void clear_version(); + int32_t version() const; + void set_version(int32_t value); + private: + int32_t _internal_version() const; + void _internal_set_version(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.AutotuneResults) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResults_Entry > results_; + int32_t version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotune_5fresults_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// AutotuneResults_Entry + +// string device = 1; +inline void AutotuneResults_Entry::clear_device() { + _impl_.device_.ClearToEmpty(); +} +inline const std::string& AutotuneResults_Entry::device() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResults.Entry.device) + return _internal_device(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuneResults_Entry::set_device(ArgT0&& arg0, ArgT... args) { + + _impl_.device_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuneResults.Entry.device) +} +inline std::string* AutotuneResults_Entry::mutable_device() { + std::string* _s = _internal_mutable_device(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResults.Entry.device) + return _s; +} +inline const std::string& AutotuneResults_Entry::_internal_device() const { + return _impl_.device_.Get(); +} +inline void AutotuneResults_Entry::_internal_set_device(const std::string& value) { + + _impl_.device_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuneResults_Entry::_internal_mutable_device() { + + return _impl_.device_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuneResults_Entry::release_device() { + // @@protoc_insertion_point(field_release:xla.AutotuneResults.Entry.device) + return _impl_.device_.Release(); +} +inline void AutotuneResults_Entry::set_allocated_device(std::string* device) { + if (device != nullptr) { + + } else { + + } + _impl_.device_.SetAllocated(device, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_.IsDefault()) { + _impl_.device_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResults.Entry.device) +} + +// string hlo = 2; +inline void AutotuneResults_Entry::clear_hlo() { + _impl_.hlo_.ClearToEmpty(); +} +inline const std::string& AutotuneResults_Entry::hlo() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResults.Entry.hlo) + return _internal_hlo(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuneResults_Entry::set_hlo(ArgT0&& arg0, ArgT... args) { + + _impl_.hlo_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuneResults.Entry.hlo) +} +inline std::string* AutotuneResults_Entry::mutable_hlo() { + std::string* _s = _internal_mutable_hlo(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResults.Entry.hlo) + return _s; +} +inline const std::string& AutotuneResults_Entry::_internal_hlo() const { + return _impl_.hlo_.Get(); +} +inline void AutotuneResults_Entry::_internal_set_hlo(const std::string& value) { + + _impl_.hlo_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuneResults_Entry::_internal_mutable_hlo() { + + return _impl_.hlo_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuneResults_Entry::release_hlo() { + // @@protoc_insertion_point(field_release:xla.AutotuneResults.Entry.hlo) + return _impl_.hlo_.Release(); +} +inline void AutotuneResults_Entry::set_allocated_hlo(std::string* hlo) { + if (hlo != nullptr) { + + } else { + + } + _impl_.hlo_.SetAllocated(hlo, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.hlo_.IsDefault()) { + _impl_.hlo_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResults.Entry.hlo) +} + +// .xla.AutotuneResult result = 3; +inline bool AutotuneResults_Entry::_internal_has_result() const { + return this != internal_default_instance() && _impl_.result_ != nullptr; +} +inline bool AutotuneResults_Entry::has_result() const { + return _internal_has_result(); +} +inline const ::xla::AutotuneResult& AutotuneResults_Entry::_internal_result() const { + const ::xla::AutotuneResult* p = _impl_.result_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_AutotuneResult_default_instance_); +} +inline const ::xla::AutotuneResult& AutotuneResults_Entry::result() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResults.Entry.result) + return _internal_result(); +} +inline void AutotuneResults_Entry::unsafe_arena_set_allocated_result( + ::xla::AutotuneResult* result) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.result_); + } + _impl_.result_ = result; + if (result) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResults.Entry.result) +} +inline ::xla::AutotuneResult* AutotuneResults_Entry::release_result() { + + ::xla::AutotuneResult* temp = _impl_.result_; + _impl_.result_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::AutotuneResult* AutotuneResults_Entry::unsafe_arena_release_result() { + // @@protoc_insertion_point(field_release:xla.AutotuneResults.Entry.result) + + ::xla::AutotuneResult* temp = _impl_.result_; + _impl_.result_ = nullptr; + return temp; +} +inline ::xla::AutotuneResult* AutotuneResults_Entry::_internal_mutable_result() { + + if (_impl_.result_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::AutotuneResult>(GetArenaForAllocation()); + _impl_.result_ = p; + } + return _impl_.result_; +} +inline ::xla::AutotuneResult* AutotuneResults_Entry::mutable_result() { + ::xla::AutotuneResult* _msg = _internal_mutable_result(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResults.Entry.result) + return _msg; +} +inline void AutotuneResults_Entry::set_allocated_result(::xla::AutotuneResult* result) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.result_); + } + if (result) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(result)); + if (message_arena != submessage_arena) { + result = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, result, submessage_arena); + } + + } else { + + } + _impl_.result_ = result; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResults.Entry.result) +} + +// ------------------------------------------------------------------- + +// AutotuneResults + +// int32 version = 1; +inline void AutotuneResults::clear_version() { + _impl_.version_ = 0; +} +inline int32_t AutotuneResults::_internal_version() const { + return _impl_.version_; +} +inline int32_t AutotuneResults::version() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResults.version) + return _internal_version(); +} +inline void AutotuneResults::_internal_set_version(int32_t value) { + + _impl_.version_ = value; +} +inline void AutotuneResults::set_version(int32_t value) { + _internal_set_version(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResults.version) +} + +// repeated .xla.AutotuneResults.Entry results = 4; +inline int AutotuneResults::_internal_results_size() const { + return _impl_.results_.size(); +} +inline int AutotuneResults::results_size() const { + return _internal_results_size(); +} +inline void AutotuneResults::clear_results() { + _impl_.results_.Clear(); +} +inline ::xla::AutotuneResults_Entry* AutotuneResults::mutable_results(int index) { + // @@protoc_insertion_point(field_mutable:xla.AutotuneResults.results) + return _impl_.results_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResults_Entry >* +AutotuneResults::mutable_results() { + // @@protoc_insertion_point(field_mutable_list:xla.AutotuneResults.results) + return &_impl_.results_; +} +inline const ::xla::AutotuneResults_Entry& AutotuneResults::_internal_results(int index) const { + return _impl_.results_.Get(index); +} +inline const ::xla::AutotuneResults_Entry& AutotuneResults::results(int index) const { + // @@protoc_insertion_point(field_get:xla.AutotuneResults.results) + return _internal_results(index); +} +inline ::xla::AutotuneResults_Entry* AutotuneResults::_internal_add_results() { + return _impl_.results_.Add(); +} +inline ::xla::AutotuneResults_Entry* AutotuneResults::add_results() { + ::xla::AutotuneResults_Entry* _add = _internal_add_results(); + // @@protoc_insertion_point(field_add:xla.AutotuneResults.results) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResults_Entry >& +AutotuneResults::results() const { + // @@protoc_insertion_point(field_list:xla.AutotuneResults.results) + return _impl_.results_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fautotune_5fresults_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotuning.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotuning.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..9256f38d7bb87839909e757a69e9cfe98c4305c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/autotuning.pb.h @@ -0,0 +1,3760 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/autotuning.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fautotuning_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fautotuning_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include +#include "tsl/protobuf/dnn.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fautotuning_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fautotuning_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fautotuning_2eproto; +namespace xla { +class AutotuneResult; +struct AutotuneResultDefaultTypeInternal; +extern AutotuneResultDefaultTypeInternal _AutotuneResult_default_instance_; +class AutotuneResult_ConvKey; +struct AutotuneResult_ConvKeyDefaultTypeInternal; +extern AutotuneResult_ConvKeyDefaultTypeInternal _AutotuneResult_ConvKey_default_instance_; +class AutotuneResult_CudaConvPlanKey; +struct AutotuneResult_CudaConvPlanKeyDefaultTypeInternal; +extern AutotuneResult_CudaConvPlanKeyDefaultTypeInternal _AutotuneResult_CudaConvPlanKey_default_instance_; +class AutotuneResult_FailureResult; +struct AutotuneResult_FailureResultDefaultTypeInternal; +extern AutotuneResult_FailureResultDefaultTypeInternal _AutotuneResult_FailureResult_default_instance_; +class AutotuneResult_GemmKey; +struct AutotuneResult_GemmKeyDefaultTypeInternal; +extern AutotuneResult_GemmKeyDefaultTypeInternal _AutotuneResult_GemmKey_default_instance_; +class AutotuneResult_TritonGemmKey; +struct AutotuneResult_TritonGemmKeyDefaultTypeInternal; +extern AutotuneResult_TritonGemmKeyDefaultTypeInternal _AutotuneResult_TritonGemmKey_default_instance_; +class AutotuningLog; +struct AutotuningLogDefaultTypeInternal; +extern AutotuningLogDefaultTypeInternal _AutotuningLog_default_instance_; +class ComputeCapability; +struct ComputeCapabilityDefaultTypeInternal; +extern ComputeCapabilityDefaultTypeInternal _ComputeCapability_default_instance_; +class CudnnVersion; +struct CudnnVersionDefaultTypeInternal; +extern CudnnVersionDefaultTypeInternal _CudnnVersion_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::AutotuneResult* Arena::CreateMaybeMessage<::xla::AutotuneResult>(Arena*); +template<> ::xla::AutotuneResult_ConvKey* Arena::CreateMaybeMessage<::xla::AutotuneResult_ConvKey>(Arena*); +template<> ::xla::AutotuneResult_CudaConvPlanKey* Arena::CreateMaybeMessage<::xla::AutotuneResult_CudaConvPlanKey>(Arena*); +template<> ::xla::AutotuneResult_FailureResult* Arena::CreateMaybeMessage<::xla::AutotuneResult_FailureResult>(Arena*); +template<> ::xla::AutotuneResult_GemmKey* Arena::CreateMaybeMessage<::xla::AutotuneResult_GemmKey>(Arena*); +template<> ::xla::AutotuneResult_TritonGemmKey* Arena::CreateMaybeMessage<::xla::AutotuneResult_TritonGemmKey>(Arena*); +template<> ::xla::AutotuningLog* Arena::CreateMaybeMessage<::xla::AutotuningLog>(Arena*); +template<> ::xla::ComputeCapability* Arena::CreateMaybeMessage<::xla::ComputeCapability>(Arena*); +template<> ::xla::CudnnVersion* Arena::CreateMaybeMessage<::xla::CudnnVersion>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +enum AutotuneResult_FailureKind : int { + AutotuneResult_FailureKind_UNKNOWN = 0, + AutotuneResult_FailureKind_REDZONE_MODIFIED = 1, + AutotuneResult_FailureKind_WRONG_RESULT = 2, + AutotuneResult_FailureKind_DISQUALIFIED = 3, + AutotuneResult_FailureKind_AutotuneResult_FailureKind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + AutotuneResult_FailureKind_AutotuneResult_FailureKind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool AutotuneResult_FailureKind_IsValid(int value); +constexpr AutotuneResult_FailureKind AutotuneResult_FailureKind_FailureKind_MIN = AutotuneResult_FailureKind_UNKNOWN; +constexpr AutotuneResult_FailureKind AutotuneResult_FailureKind_FailureKind_MAX = AutotuneResult_FailureKind_DISQUALIFIED; +constexpr int AutotuneResult_FailureKind_FailureKind_ARRAYSIZE = AutotuneResult_FailureKind_FailureKind_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* AutotuneResult_FailureKind_descriptor(); +template +inline const std::string& AutotuneResult_FailureKind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function AutotuneResult_FailureKind_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + AutotuneResult_FailureKind_descriptor(), enum_t_value); +} +inline bool AutotuneResult_FailureKind_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, AutotuneResult_FailureKind* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + AutotuneResult_FailureKind_descriptor(), name, value); +} +// =================================================================== + +class CudnnVersion final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.CudnnVersion) */ { + public: + inline CudnnVersion() : CudnnVersion(nullptr) {} + ~CudnnVersion() override; + explicit PROTOBUF_CONSTEXPR CudnnVersion(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CudnnVersion(const CudnnVersion& from); + CudnnVersion(CudnnVersion&& from) noexcept + : CudnnVersion() { + *this = ::std::move(from); + } + + inline CudnnVersion& operator=(const CudnnVersion& from) { + CopyFrom(from); + return *this; + } + inline CudnnVersion& operator=(CudnnVersion&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CudnnVersion& default_instance() { + return *internal_default_instance(); + } + static inline const CudnnVersion* internal_default_instance() { + return reinterpret_cast( + &_CudnnVersion_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CudnnVersion& a, CudnnVersion& b) { + a.Swap(&b); + } + inline void Swap(CudnnVersion* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CudnnVersion* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CudnnVersion* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CudnnVersion& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CudnnVersion& from) { + CudnnVersion::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(CudnnVersion* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.CudnnVersion"; + } + protected: + explicit CudnnVersion(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMajorFieldNumber = 1, + kMinorFieldNumber = 2, + kPatchFieldNumber = 3, + }; + // int32 major = 1; + void clear_major(); + int32_t major() const; + void set_major(int32_t value); + private: + int32_t _internal_major() const; + void _internal_set_major(int32_t value); + public: + + // int32 minor = 2; + void clear_minor(); + int32_t minor() const; + void set_minor(int32_t value); + private: + int32_t _internal_minor() const; + void _internal_set_minor(int32_t value); + public: + + // int32 patch = 3; + void clear_patch(); + int32_t patch() const; + void set_patch(int32_t value); + private: + int32_t _internal_patch() const; + void _internal_set_patch(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.CudnnVersion) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t major_; + int32_t minor_; + int32_t patch_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class ComputeCapability final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.ComputeCapability) */ { + public: + inline ComputeCapability() : ComputeCapability(nullptr) {} + ~ComputeCapability() override; + explicit PROTOBUF_CONSTEXPR ComputeCapability(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ComputeCapability(const ComputeCapability& from); + ComputeCapability(ComputeCapability&& from) noexcept + : ComputeCapability() { + *this = ::std::move(from); + } + + inline ComputeCapability& operator=(const ComputeCapability& from) { + CopyFrom(from); + return *this; + } + inline ComputeCapability& operator=(ComputeCapability&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const ComputeCapability& default_instance() { + return *internal_default_instance(); + } + static inline const ComputeCapability* internal_default_instance() { + return reinterpret_cast( + &_ComputeCapability_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(ComputeCapability& a, ComputeCapability& b) { + a.Swap(&b); + } + inline void Swap(ComputeCapability* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(ComputeCapability* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ComputeCapability* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ComputeCapability& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ComputeCapability& from) { + ComputeCapability::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(ComputeCapability* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.ComputeCapability"; + } + protected: + explicit ComputeCapability(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMajorFieldNumber = 1, + kMinorFieldNumber = 2, + }; + // int32 major = 1; + void clear_major(); + int32_t major() const; + void set_major(int32_t value); + private: + int32_t _internal_major() const; + void _internal_set_major(int32_t value); + public: + + // int32 minor = 2; + void clear_minor(); + int32_t minor() const; + void set_minor(int32_t value); + private: + int32_t _internal_minor() const; + void _internal_set_minor(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.ComputeCapability) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t major_; + int32_t minor_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult_FailureResult final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult.FailureResult) */ { + public: + inline AutotuneResult_FailureResult() : AutotuneResult_FailureResult(nullptr) {} + ~AutotuneResult_FailureResult() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult_FailureResult(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult_FailureResult(const AutotuneResult_FailureResult& from); + AutotuneResult_FailureResult(AutotuneResult_FailureResult&& from) noexcept + : AutotuneResult_FailureResult() { + *this = ::std::move(from); + } + + inline AutotuneResult_FailureResult& operator=(const AutotuneResult_FailureResult& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult_FailureResult& operator=(AutotuneResult_FailureResult&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult_FailureResult& default_instance() { + return *internal_default_instance(); + } + enum KeyCase { + kReferenceConv = 11, + kReferenceGemm = 12, + kReferenceCudaConvPlan = 14, + kReferenceAlgorithm = 15, + KEY_NOT_SET = 0, + }; + + static inline const AutotuneResult_FailureResult* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_FailureResult_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(AutotuneResult_FailureResult& a, AutotuneResult_FailureResult& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult_FailureResult* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult_FailureResult* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult_FailureResult* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult_FailureResult& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult_FailureResult& from) { + AutotuneResult_FailureResult::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult_FailureResult* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult.FailureResult"; + } + protected: + explicit AutotuneResult_FailureResult(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMsgFieldNumber = 2, + kBufferAddressFieldNumber = 13, + kKindFieldNumber = 1, + kReferenceConvFieldNumber = 11, + kReferenceGemmFieldNumber = 12, + kReferenceCudaConvPlanFieldNumber = 14, + kReferenceAlgorithmFieldNumber = 15, + }; + // string msg = 2; + void clear_msg(); + const std::string& msg() const; + template + void set_msg(ArgT0&& arg0, ArgT... args); + std::string* mutable_msg(); + PROTOBUF_NODISCARD std::string* release_msg(); + void set_allocated_msg(std::string* msg); + private: + const std::string& _internal_msg() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_msg(const std::string& value); + std::string* _internal_mutable_msg(); + public: + + // int64 buffer_address = 13; + void clear_buffer_address(); + int64_t buffer_address() const; + void set_buffer_address(int64_t value); + private: + int64_t _internal_buffer_address() const; + void _internal_set_buffer_address(int64_t value); + public: + + // .xla.AutotuneResult.FailureKind kind = 1; + void clear_kind(); + ::xla::AutotuneResult_FailureKind kind() const; + void set_kind(::xla::AutotuneResult_FailureKind value); + private: + ::xla::AutotuneResult_FailureKind _internal_kind() const; + void _internal_set_kind(::xla::AutotuneResult_FailureKind value); + public: + + // .xla.AutotuneResult.ConvKey reference_conv = 11; + bool has_reference_conv() const; + private: + bool _internal_has_reference_conv() const; + public: + void clear_reference_conv(); + const ::xla::AutotuneResult_ConvKey& reference_conv() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_ConvKey* release_reference_conv(); + ::xla::AutotuneResult_ConvKey* mutable_reference_conv(); + void set_allocated_reference_conv(::xla::AutotuneResult_ConvKey* reference_conv); + private: + const ::xla::AutotuneResult_ConvKey& _internal_reference_conv() const; + ::xla::AutotuneResult_ConvKey* _internal_mutable_reference_conv(); + public: + void unsafe_arena_set_allocated_reference_conv( + ::xla::AutotuneResult_ConvKey* reference_conv); + ::xla::AutotuneResult_ConvKey* unsafe_arena_release_reference_conv(); + + // .xla.AutotuneResult.GemmKey reference_gemm = 12; + bool has_reference_gemm() const; + private: + bool _internal_has_reference_gemm() const; + public: + void clear_reference_gemm(); + const ::xla::AutotuneResult_GemmKey& reference_gemm() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_GemmKey* release_reference_gemm(); + ::xla::AutotuneResult_GemmKey* mutable_reference_gemm(); + void set_allocated_reference_gemm(::xla::AutotuneResult_GemmKey* reference_gemm); + private: + const ::xla::AutotuneResult_GemmKey& _internal_reference_gemm() const; + ::xla::AutotuneResult_GemmKey* _internal_mutable_reference_gemm(); + public: + void unsafe_arena_set_allocated_reference_gemm( + ::xla::AutotuneResult_GemmKey* reference_gemm); + ::xla::AutotuneResult_GemmKey* unsafe_arena_release_reference_gemm(); + + // .xla.AutotuneResult.CudaConvPlanKey reference_cuda_conv_plan = 14; + bool has_reference_cuda_conv_plan() const; + private: + bool _internal_has_reference_cuda_conv_plan() const; + public: + void clear_reference_cuda_conv_plan(); + const ::xla::AutotuneResult_CudaConvPlanKey& reference_cuda_conv_plan() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_CudaConvPlanKey* release_reference_cuda_conv_plan(); + ::xla::AutotuneResult_CudaConvPlanKey* mutable_reference_cuda_conv_plan(); + void set_allocated_reference_cuda_conv_plan(::xla::AutotuneResult_CudaConvPlanKey* reference_cuda_conv_plan); + private: + const ::xla::AutotuneResult_CudaConvPlanKey& _internal_reference_cuda_conv_plan() const; + ::xla::AutotuneResult_CudaConvPlanKey* _internal_mutable_reference_cuda_conv_plan(); + public: + void unsafe_arena_set_allocated_reference_cuda_conv_plan( + ::xla::AutotuneResult_CudaConvPlanKey* reference_cuda_conv_plan); + ::xla::AutotuneResult_CudaConvPlanKey* unsafe_arena_release_reference_cuda_conv_plan(); + + // .stream_executor.dnn.AlgorithmProto reference_algorithm = 15; + bool has_reference_algorithm() const; + private: + bool _internal_has_reference_algorithm() const; + public: + void clear_reference_algorithm(); + const ::stream_executor::dnn::AlgorithmProto& reference_algorithm() const; + PROTOBUF_NODISCARD ::stream_executor::dnn::AlgorithmProto* release_reference_algorithm(); + ::stream_executor::dnn::AlgorithmProto* mutable_reference_algorithm(); + void set_allocated_reference_algorithm(::stream_executor::dnn::AlgorithmProto* reference_algorithm); + private: + const ::stream_executor::dnn::AlgorithmProto& _internal_reference_algorithm() const; + ::stream_executor::dnn::AlgorithmProto* _internal_mutable_reference_algorithm(); + public: + void unsafe_arena_set_allocated_reference_algorithm( + ::stream_executor::dnn::AlgorithmProto* reference_algorithm); + ::stream_executor::dnn::AlgorithmProto* unsafe_arena_release_reference_algorithm(); + + void clear_key(); + KeyCase key_case() const; + // @@protoc_insertion_point(class_scope:xla.AutotuneResult.FailureResult) + private: + class _Internal; + void set_has_reference_conv(); + void set_has_reference_gemm(); + void set_has_reference_cuda_conv_plan(); + void set_has_reference_algorithm(); + + inline bool has_key() const; + inline void clear_has_key(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr msg_; + int64_t buffer_address_; + int kind_; + union KeyUnion { + constexpr KeyUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::xla::AutotuneResult_ConvKey* reference_conv_; + ::xla::AutotuneResult_GemmKey* reference_gemm_; + ::xla::AutotuneResult_CudaConvPlanKey* reference_cuda_conv_plan_; + ::stream_executor::dnn::AlgorithmProto* reference_algorithm_; + } key_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult_ConvKey final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult.ConvKey) */ { + public: + inline AutotuneResult_ConvKey() : AutotuneResult_ConvKey(nullptr) {} + ~AutotuneResult_ConvKey() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult_ConvKey(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult_ConvKey(const AutotuneResult_ConvKey& from); + AutotuneResult_ConvKey(AutotuneResult_ConvKey&& from) noexcept + : AutotuneResult_ConvKey() { + *this = ::std::move(from); + } + + inline AutotuneResult_ConvKey& operator=(const AutotuneResult_ConvKey& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult_ConvKey& operator=(AutotuneResult_ConvKey&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult_ConvKey& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResult_ConvKey* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_ConvKey_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(AutotuneResult_ConvKey& a, AutotuneResult_ConvKey& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult_ConvKey* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult_ConvKey* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult_ConvKey* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult_ConvKey& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult_ConvKey& from) { + AutotuneResult_ConvKey::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult_ConvKey* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult.ConvKey"; + } + protected: + explicit AutotuneResult_ConvKey(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kAlgorithmFieldNumber = 1, + kTensorOpsEnabledFieldNumber = 2, + }; + // int64 algorithm = 1; + void clear_algorithm(); + int64_t algorithm() const; + void set_algorithm(int64_t value); + private: + int64_t _internal_algorithm() const; + void _internal_set_algorithm(int64_t value); + public: + + // bool tensor_ops_enabled = 2; + void clear_tensor_ops_enabled(); + bool tensor_ops_enabled() const; + void set_tensor_ops_enabled(bool value); + private: + bool _internal_tensor_ops_enabled() const; + void _internal_set_tensor_ops_enabled(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.AutotuneResult.ConvKey) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t algorithm_; + bool tensor_ops_enabled_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult_GemmKey final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult.GemmKey) */ { + public: + inline AutotuneResult_GemmKey() : AutotuneResult_GemmKey(nullptr) {} + ~AutotuneResult_GemmKey() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult_GemmKey(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult_GemmKey(const AutotuneResult_GemmKey& from); + AutotuneResult_GemmKey(AutotuneResult_GemmKey&& from) noexcept + : AutotuneResult_GemmKey() { + *this = ::std::move(from); + } + + inline AutotuneResult_GemmKey& operator=(const AutotuneResult_GemmKey& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult_GemmKey& operator=(AutotuneResult_GemmKey&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult_GemmKey& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResult_GemmKey* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_GemmKey_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(AutotuneResult_GemmKey& a, AutotuneResult_GemmKey& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult_GemmKey* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult_GemmKey* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult_GemmKey* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult_GemmKey& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult_GemmKey& from) { + AutotuneResult_GemmKey::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult_GemmKey* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult.GemmKey"; + } + protected: + explicit AutotuneResult_GemmKey(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kAlgorithmFieldNumber = 1, + }; + // int64 algorithm = 1; + void clear_algorithm(); + int64_t algorithm() const; + void set_algorithm(int64_t value); + private: + int64_t _internal_algorithm() const; + void _internal_set_algorithm(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.AutotuneResult.GemmKey) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t algorithm_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult_CudaConvPlanKey final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult.CudaConvPlanKey) */ { + public: + inline AutotuneResult_CudaConvPlanKey() : AutotuneResult_CudaConvPlanKey(nullptr) {} + ~AutotuneResult_CudaConvPlanKey() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult_CudaConvPlanKey(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult_CudaConvPlanKey(const AutotuneResult_CudaConvPlanKey& from); + AutotuneResult_CudaConvPlanKey(AutotuneResult_CudaConvPlanKey&& from) noexcept + : AutotuneResult_CudaConvPlanKey() { + *this = ::std::move(from); + } + + inline AutotuneResult_CudaConvPlanKey& operator=(const AutotuneResult_CudaConvPlanKey& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult_CudaConvPlanKey& operator=(AutotuneResult_CudaConvPlanKey&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult_CudaConvPlanKey& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResult_CudaConvPlanKey* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_CudaConvPlanKey_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(AutotuneResult_CudaConvPlanKey& a, AutotuneResult_CudaConvPlanKey& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult_CudaConvPlanKey* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult_CudaConvPlanKey* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult_CudaConvPlanKey* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult_CudaConvPlanKey& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult_CudaConvPlanKey& from) { + AutotuneResult_CudaConvPlanKey::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult_CudaConvPlanKey* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult.CudaConvPlanKey"; + } + protected: + explicit AutotuneResult_CudaConvPlanKey(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kExecPlanIdFieldNumber = 1, + }; + // string exec_plan_id = 1; + void clear_exec_plan_id(); + const std::string& exec_plan_id() const; + template + void set_exec_plan_id(ArgT0&& arg0, ArgT... args); + std::string* mutable_exec_plan_id(); + PROTOBUF_NODISCARD std::string* release_exec_plan_id(); + void set_allocated_exec_plan_id(std::string* exec_plan_id); + private: + const std::string& _internal_exec_plan_id() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_exec_plan_id(const std::string& value); + std::string* _internal_mutable_exec_plan_id(); + public: + + // @@protoc_insertion_point(class_scope:xla.AutotuneResult.CudaConvPlanKey) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr exec_plan_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult_TritonGemmKey final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult.TritonGemmKey) */ { + public: + inline AutotuneResult_TritonGemmKey() : AutotuneResult_TritonGemmKey(nullptr) {} + ~AutotuneResult_TritonGemmKey() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult_TritonGemmKey(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult_TritonGemmKey(const AutotuneResult_TritonGemmKey& from); + AutotuneResult_TritonGemmKey(AutotuneResult_TritonGemmKey&& from) noexcept + : AutotuneResult_TritonGemmKey() { + *this = ::std::move(from); + } + + inline AutotuneResult_TritonGemmKey& operator=(const AutotuneResult_TritonGemmKey& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult_TritonGemmKey& operator=(AutotuneResult_TritonGemmKey&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult_TritonGemmKey& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuneResult_TritonGemmKey* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_TritonGemmKey_default_instance_); + } + static constexpr int kIndexInFileMessages = + 6; + + friend void swap(AutotuneResult_TritonGemmKey& a, AutotuneResult_TritonGemmKey& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult_TritonGemmKey* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult_TritonGemmKey* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult_TritonGemmKey* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult_TritonGemmKey& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult_TritonGemmKey& from) { + AutotuneResult_TritonGemmKey::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult_TritonGemmKey* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult.TritonGemmKey"; + } + protected: + explicit AutotuneResult_TritonGemmKey(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kBlockMFieldNumber = 1, + kBlockNFieldNumber = 2, + kBlockKFieldNumber = 3, + kSplitKFieldNumber = 4, + kNumStagesFieldNumber = 5, + kNumWarpsFieldNumber = 6, + }; + // int64 block_m = 1; + void clear_block_m(); + int64_t block_m() const; + void set_block_m(int64_t value); + private: + int64_t _internal_block_m() const; + void _internal_set_block_m(int64_t value); + public: + + // int64 block_n = 2; + void clear_block_n(); + int64_t block_n() const; + void set_block_n(int64_t value); + private: + int64_t _internal_block_n() const; + void _internal_set_block_n(int64_t value); + public: + + // int64 block_k = 3; + void clear_block_k(); + int64_t block_k() const; + void set_block_k(int64_t value); + private: + int64_t _internal_block_k() const; + void _internal_set_block_k(int64_t value); + public: + + // int64 split_k = 4; + void clear_split_k(); + int64_t split_k() const; + void set_split_k(int64_t value); + private: + int64_t _internal_split_k() const; + void _internal_set_split_k(int64_t value); + public: + + // int64 num_stages = 5; + void clear_num_stages(); + int64_t num_stages() const; + void set_num_stages(int64_t value); + private: + int64_t _internal_num_stages() const; + void _internal_set_num_stages(int64_t value); + public: + + // int64 num_warps = 6; + void clear_num_warps(); + int64_t num_warps() const; + void set_num_warps(int64_t value); + private: + int64_t _internal_num_warps() const; + void _internal_set_num_warps(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.AutotuneResult.TritonGemmKey) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t block_m_; + int64_t block_n_; + int64_t block_k_; + int64_t split_k_; + int64_t num_stages_; + int64_t num_warps_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuneResult final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuneResult) */ { + public: + inline AutotuneResult() : AutotuneResult(nullptr) {} + ~AutotuneResult() override; + explicit PROTOBUF_CONSTEXPR AutotuneResult(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneResult(const AutotuneResult& from); + AutotuneResult(AutotuneResult&& from) noexcept + : AutotuneResult() { + *this = ::std::move(from); + } + + inline AutotuneResult& operator=(const AutotuneResult& from) { + CopyFrom(from); + return *this; + } + inline AutotuneResult& operator=(AutotuneResult&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuneResult& default_instance() { + return *internal_default_instance(); + } + enum KeyCase { + kConv = 5, + kGemm = 6, + kTriton = 17, + kCudaConvPlan = 15, + kAlgorithm = 16, + KEY_NOT_SET = 0, + }; + + static inline const AutotuneResult* internal_default_instance() { + return reinterpret_cast( + &_AutotuneResult_default_instance_); + } + static constexpr int kIndexInFileMessages = + 7; + + friend void swap(AutotuneResult& a, AutotuneResult& b) { + a.Swap(&b); + } + inline void Swap(AutotuneResult* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuneResult* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneResult* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneResult& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneResult& from) { + AutotuneResult::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuneResult* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuneResult"; + } + protected: + explicit AutotuneResult(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + typedef AutotuneResult_FailureResult FailureResult; + typedef AutotuneResult_ConvKey ConvKey; + typedef AutotuneResult_GemmKey GemmKey; + typedef AutotuneResult_CudaConvPlanKey CudaConvPlanKey; + typedef AutotuneResult_TritonGemmKey TritonGemmKey; + + typedef AutotuneResult_FailureKind FailureKind; + static constexpr FailureKind UNKNOWN = + AutotuneResult_FailureKind_UNKNOWN; + static constexpr FailureKind REDZONE_MODIFIED = + AutotuneResult_FailureKind_REDZONE_MODIFIED; + static constexpr FailureKind WRONG_RESULT = + AutotuneResult_FailureKind_WRONG_RESULT; + static constexpr FailureKind DISQUALIFIED = + AutotuneResult_FailureKind_DISQUALIFIED; + static inline bool FailureKind_IsValid(int value) { + return AutotuneResult_FailureKind_IsValid(value); + } + static constexpr FailureKind FailureKind_MIN = + AutotuneResult_FailureKind_FailureKind_MIN; + static constexpr FailureKind FailureKind_MAX = + AutotuneResult_FailureKind_FailureKind_MAX; + static constexpr int FailureKind_ARRAYSIZE = + AutotuneResult_FailureKind_FailureKind_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + FailureKind_descriptor() { + return AutotuneResult_FailureKind_descriptor(); + } + template + static inline const std::string& FailureKind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FailureKind_Name."); + return AutotuneResult_FailureKind_Name(enum_t_value); + } + static inline bool FailureKind_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + FailureKind* value) { + return AutotuneResult_FailureKind_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kFailureFieldNumber = 7, + kRunTimeFieldNumber = 9, + kScratchBytesFieldNumber = 8, + kConvFieldNumber = 5, + kGemmFieldNumber = 6, + kTritonFieldNumber = 17, + kCudaConvPlanFieldNumber = 15, + kAlgorithmFieldNumber = 16, + }; + // .xla.AutotuneResult.FailureResult failure = 7; + bool has_failure() const; + private: + bool _internal_has_failure() const; + public: + void clear_failure(); + const ::xla::AutotuneResult_FailureResult& failure() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_FailureResult* release_failure(); + ::xla::AutotuneResult_FailureResult* mutable_failure(); + void set_allocated_failure(::xla::AutotuneResult_FailureResult* failure); + private: + const ::xla::AutotuneResult_FailureResult& _internal_failure() const; + ::xla::AutotuneResult_FailureResult* _internal_mutable_failure(); + public: + void unsafe_arena_set_allocated_failure( + ::xla::AutotuneResult_FailureResult* failure); + ::xla::AutotuneResult_FailureResult* unsafe_arena_release_failure(); + + // .google.protobuf.Duration run_time = 9; + bool has_run_time() const; + private: + bool _internal_has_run_time() const; + public: + void clear_run_time(); + const ::PROTOBUF_NAMESPACE_ID::Duration& run_time() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Duration* release_run_time(); + ::PROTOBUF_NAMESPACE_ID::Duration* mutable_run_time(); + void set_allocated_run_time(::PROTOBUF_NAMESPACE_ID::Duration* run_time); + private: + const ::PROTOBUF_NAMESPACE_ID::Duration& _internal_run_time() const; + ::PROTOBUF_NAMESPACE_ID::Duration* _internal_mutable_run_time(); + public: + void unsafe_arena_set_allocated_run_time( + ::PROTOBUF_NAMESPACE_ID::Duration* run_time); + ::PROTOBUF_NAMESPACE_ID::Duration* unsafe_arena_release_run_time(); + + // int64 scratch_bytes = 8; + void clear_scratch_bytes(); + int64_t scratch_bytes() const; + void set_scratch_bytes(int64_t value); + private: + int64_t _internal_scratch_bytes() const; + void _internal_set_scratch_bytes(int64_t value); + public: + + // .xla.AutotuneResult.ConvKey conv = 5; + bool has_conv() const; + private: + bool _internal_has_conv() const; + public: + void clear_conv(); + const ::xla::AutotuneResult_ConvKey& conv() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_ConvKey* release_conv(); + ::xla::AutotuneResult_ConvKey* mutable_conv(); + void set_allocated_conv(::xla::AutotuneResult_ConvKey* conv); + private: + const ::xla::AutotuneResult_ConvKey& _internal_conv() const; + ::xla::AutotuneResult_ConvKey* _internal_mutable_conv(); + public: + void unsafe_arena_set_allocated_conv( + ::xla::AutotuneResult_ConvKey* conv); + ::xla::AutotuneResult_ConvKey* unsafe_arena_release_conv(); + + // .xla.AutotuneResult.GemmKey gemm = 6; + bool has_gemm() const; + private: + bool _internal_has_gemm() const; + public: + void clear_gemm(); + const ::xla::AutotuneResult_GemmKey& gemm() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_GemmKey* release_gemm(); + ::xla::AutotuneResult_GemmKey* mutable_gemm(); + void set_allocated_gemm(::xla::AutotuneResult_GemmKey* gemm); + private: + const ::xla::AutotuneResult_GemmKey& _internal_gemm() const; + ::xla::AutotuneResult_GemmKey* _internal_mutable_gemm(); + public: + void unsafe_arena_set_allocated_gemm( + ::xla::AutotuneResult_GemmKey* gemm); + ::xla::AutotuneResult_GemmKey* unsafe_arena_release_gemm(); + + // .xla.AutotuneResult.TritonGemmKey triton = 17; + bool has_triton() const; + private: + bool _internal_has_triton() const; + public: + void clear_triton(); + const ::xla::AutotuneResult_TritonGemmKey& triton() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_TritonGemmKey* release_triton(); + ::xla::AutotuneResult_TritonGemmKey* mutable_triton(); + void set_allocated_triton(::xla::AutotuneResult_TritonGemmKey* triton); + private: + const ::xla::AutotuneResult_TritonGemmKey& _internal_triton() const; + ::xla::AutotuneResult_TritonGemmKey* _internal_mutable_triton(); + public: + void unsafe_arena_set_allocated_triton( + ::xla::AutotuneResult_TritonGemmKey* triton); + ::xla::AutotuneResult_TritonGemmKey* unsafe_arena_release_triton(); + + // .xla.AutotuneResult.CudaConvPlanKey cuda_conv_plan = 15; + bool has_cuda_conv_plan() const; + private: + bool _internal_has_cuda_conv_plan() const; + public: + void clear_cuda_conv_plan(); + const ::xla::AutotuneResult_CudaConvPlanKey& cuda_conv_plan() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_CudaConvPlanKey* release_cuda_conv_plan(); + ::xla::AutotuneResult_CudaConvPlanKey* mutable_cuda_conv_plan(); + void set_allocated_cuda_conv_plan(::xla::AutotuneResult_CudaConvPlanKey* cuda_conv_plan); + private: + const ::xla::AutotuneResult_CudaConvPlanKey& _internal_cuda_conv_plan() const; + ::xla::AutotuneResult_CudaConvPlanKey* _internal_mutable_cuda_conv_plan(); + public: + void unsafe_arena_set_allocated_cuda_conv_plan( + ::xla::AutotuneResult_CudaConvPlanKey* cuda_conv_plan); + ::xla::AutotuneResult_CudaConvPlanKey* unsafe_arena_release_cuda_conv_plan(); + + // .stream_executor.dnn.AlgorithmProto algorithm = 16; + bool has_algorithm() const; + private: + bool _internal_has_algorithm() const; + public: + void clear_algorithm(); + const ::stream_executor::dnn::AlgorithmProto& algorithm() const; + PROTOBUF_NODISCARD ::stream_executor::dnn::AlgorithmProto* release_algorithm(); + ::stream_executor::dnn::AlgorithmProto* mutable_algorithm(); + void set_allocated_algorithm(::stream_executor::dnn::AlgorithmProto* algorithm); + private: + const ::stream_executor::dnn::AlgorithmProto& _internal_algorithm() const; + ::stream_executor::dnn::AlgorithmProto* _internal_mutable_algorithm(); + public: + void unsafe_arena_set_allocated_algorithm( + ::stream_executor::dnn::AlgorithmProto* algorithm); + ::stream_executor::dnn::AlgorithmProto* unsafe_arena_release_algorithm(); + + void clear_key(); + KeyCase key_case() const; + // @@protoc_insertion_point(class_scope:xla.AutotuneResult) + private: + class _Internal; + void set_has_conv(); + void set_has_gemm(); + void set_has_triton(); + void set_has_cuda_conv_plan(); + void set_has_algorithm(); + + inline bool has_key() const; + inline void clear_has_key(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::AutotuneResult_FailureResult* failure_; + ::PROTOBUF_NAMESPACE_ID::Duration* run_time_; + int64_t scratch_bytes_; + union KeyUnion { + constexpr KeyUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::xla::AutotuneResult_ConvKey* conv_; + ::xla::AutotuneResult_GemmKey* gemm_; + ::xla::AutotuneResult_TritonGemmKey* triton_; + ::xla::AutotuneResult_CudaConvPlanKey* cuda_conv_plan_; + ::stream_executor::dnn::AlgorithmProto* algorithm_; + } key_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AutotuningLog final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.AutotuningLog) */ { + public: + inline AutotuningLog() : AutotuningLog(nullptr) {} + ~AutotuningLog() override; + explicit PROTOBUF_CONSTEXPR AutotuningLog(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuningLog(const AutotuningLog& from); + AutotuningLog(AutotuningLog&& from) noexcept + : AutotuningLog() { + *this = ::std::move(from); + } + + inline AutotuningLog& operator=(const AutotuningLog& from) { + CopyFrom(from); + return *this; + } + inline AutotuningLog& operator=(AutotuningLog&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AutotuningLog& default_instance() { + return *internal_default_instance(); + } + static inline const AutotuningLog* internal_default_instance() { + return reinterpret_cast( + &_AutotuningLog_default_instance_); + } + static constexpr int kIndexInFileMessages = + 8; + + friend void swap(AutotuningLog& a, AutotuningLog& b) { + a.Swap(&b); + } + inline void Swap(AutotuningLog* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AutotuningLog* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuningLog* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuningLog& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuningLog& from) { + AutotuningLog::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AutotuningLog* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.AutotuningLog"; + } + protected: + explicit AutotuningLog(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kResultsFieldNumber = 2, + kDevicePciBusIdFieldNumber = 5, + kBlasVersionFieldNumber = 6, + kInstrFieldNumber = 1, + kCudnnVersionFieldNumber = 3, + kComputeCapabilityFieldNumber = 4, + }; + // repeated .xla.AutotuneResult results = 2; + int results_size() const; + private: + int _internal_results_size() const; + public: + void clear_results(); + ::xla::AutotuneResult* mutable_results(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResult >* + mutable_results(); + private: + const ::xla::AutotuneResult& _internal_results(int index) const; + ::xla::AutotuneResult* _internal_add_results(); + public: + const ::xla::AutotuneResult& results(int index) const; + ::xla::AutotuneResult* add_results(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResult >& + results() const; + + // string device_pci_bus_id = 5; + void clear_device_pci_bus_id(); + const std::string& device_pci_bus_id() const; + template + void set_device_pci_bus_id(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_pci_bus_id(); + PROTOBUF_NODISCARD std::string* release_device_pci_bus_id(); + void set_allocated_device_pci_bus_id(std::string* device_pci_bus_id); + private: + const std::string& _internal_device_pci_bus_id() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_pci_bus_id(const std::string& value); + std::string* _internal_mutable_device_pci_bus_id(); + public: + + // string blas_version = 6; + void clear_blas_version(); + const std::string& blas_version() const; + template + void set_blas_version(ArgT0&& arg0, ArgT... args); + std::string* mutable_blas_version(); + PROTOBUF_NODISCARD std::string* release_blas_version(); + void set_allocated_blas_version(std::string* blas_version); + private: + const std::string& _internal_blas_version() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_blas_version(const std::string& value); + std::string* _internal_mutable_blas_version(); + public: + + // .google.protobuf.Any instr = 1; + bool has_instr() const; + private: + bool _internal_has_instr() const; + public: + void clear_instr(); + const ::PROTOBUF_NAMESPACE_ID::Any& instr() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Any* release_instr(); + ::PROTOBUF_NAMESPACE_ID::Any* mutable_instr(); + void set_allocated_instr(::PROTOBUF_NAMESPACE_ID::Any* instr); + private: + const ::PROTOBUF_NAMESPACE_ID::Any& _internal_instr() const; + ::PROTOBUF_NAMESPACE_ID::Any* _internal_mutable_instr(); + public: + void unsafe_arena_set_allocated_instr( + ::PROTOBUF_NAMESPACE_ID::Any* instr); + ::PROTOBUF_NAMESPACE_ID::Any* unsafe_arena_release_instr(); + + // .xla.CudnnVersion cudnn_version = 3; + bool has_cudnn_version() const; + private: + bool _internal_has_cudnn_version() const; + public: + void clear_cudnn_version(); + const ::xla::CudnnVersion& cudnn_version() const; + PROTOBUF_NODISCARD ::xla::CudnnVersion* release_cudnn_version(); + ::xla::CudnnVersion* mutable_cudnn_version(); + void set_allocated_cudnn_version(::xla::CudnnVersion* cudnn_version); + private: + const ::xla::CudnnVersion& _internal_cudnn_version() const; + ::xla::CudnnVersion* _internal_mutable_cudnn_version(); + public: + void unsafe_arena_set_allocated_cudnn_version( + ::xla::CudnnVersion* cudnn_version); + ::xla::CudnnVersion* unsafe_arena_release_cudnn_version(); + + // .xla.ComputeCapability compute_capability = 4; + bool has_compute_capability() const; + private: + bool _internal_has_compute_capability() const; + public: + void clear_compute_capability(); + const ::xla::ComputeCapability& compute_capability() const; + PROTOBUF_NODISCARD ::xla::ComputeCapability* release_compute_capability(); + ::xla::ComputeCapability* mutable_compute_capability(); + void set_allocated_compute_capability(::xla::ComputeCapability* compute_capability); + private: + const ::xla::ComputeCapability& _internal_compute_capability() const; + ::xla::ComputeCapability* _internal_mutable_compute_capability(); + public: + void unsafe_arena_set_allocated_compute_capability( + ::xla::ComputeCapability* compute_capability); + ::xla::ComputeCapability* unsafe_arena_release_compute_capability(); + + // @@protoc_insertion_point(class_scope:xla.AutotuningLog) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResult > results_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_pci_bus_id_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr blas_version_; + ::PROTOBUF_NAMESPACE_ID::Any* instr_; + ::xla::CudnnVersion* cudnn_version_; + ::xla::ComputeCapability* compute_capability_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fautotuning_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CudnnVersion + +// int32 major = 1; +inline void CudnnVersion::clear_major() { + _impl_.major_ = 0; +} +inline int32_t CudnnVersion::_internal_major() const { + return _impl_.major_; +} +inline int32_t CudnnVersion::major() const { + // @@protoc_insertion_point(field_get:xla.CudnnVersion.major) + return _internal_major(); +} +inline void CudnnVersion::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void CudnnVersion::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:xla.CudnnVersion.major) +} + +// int32 minor = 2; +inline void CudnnVersion::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t CudnnVersion::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t CudnnVersion::minor() const { + // @@protoc_insertion_point(field_get:xla.CudnnVersion.minor) + return _internal_minor(); +} +inline void CudnnVersion::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void CudnnVersion::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:xla.CudnnVersion.minor) +} + +// int32 patch = 3; +inline void CudnnVersion::clear_patch() { + _impl_.patch_ = 0; +} +inline int32_t CudnnVersion::_internal_patch() const { + return _impl_.patch_; +} +inline int32_t CudnnVersion::patch() const { + // @@protoc_insertion_point(field_get:xla.CudnnVersion.patch) + return _internal_patch(); +} +inline void CudnnVersion::_internal_set_patch(int32_t value) { + + _impl_.patch_ = value; +} +inline void CudnnVersion::set_patch(int32_t value) { + _internal_set_patch(value); + // @@protoc_insertion_point(field_set:xla.CudnnVersion.patch) +} + +// ------------------------------------------------------------------- + +// ComputeCapability + +// int32 major = 1; +inline void ComputeCapability::clear_major() { + _impl_.major_ = 0; +} +inline int32_t ComputeCapability::_internal_major() const { + return _impl_.major_; +} +inline int32_t ComputeCapability::major() const { + // @@protoc_insertion_point(field_get:xla.ComputeCapability.major) + return _internal_major(); +} +inline void ComputeCapability::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void ComputeCapability::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:xla.ComputeCapability.major) +} + +// int32 minor = 2; +inline void ComputeCapability::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t ComputeCapability::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t ComputeCapability::minor() const { + // @@protoc_insertion_point(field_get:xla.ComputeCapability.minor) + return _internal_minor(); +} +inline void ComputeCapability::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void ComputeCapability::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:xla.ComputeCapability.minor) +} + +// ------------------------------------------------------------------- + +// AutotuneResult_FailureResult + +// .xla.AutotuneResult.FailureKind kind = 1; +inline void AutotuneResult_FailureResult::clear_kind() { + _impl_.kind_ = 0; +} +inline ::xla::AutotuneResult_FailureKind AutotuneResult_FailureResult::_internal_kind() const { + return static_cast< ::xla::AutotuneResult_FailureKind >(_impl_.kind_); +} +inline ::xla::AutotuneResult_FailureKind AutotuneResult_FailureResult::kind() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.kind) + return _internal_kind(); +} +inline void AutotuneResult_FailureResult::_internal_set_kind(::xla::AutotuneResult_FailureKind value) { + + _impl_.kind_ = value; +} +inline void AutotuneResult_FailureResult::set_kind(::xla::AutotuneResult_FailureKind value) { + _internal_set_kind(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.FailureResult.kind) +} + +// string msg = 2; +inline void AutotuneResult_FailureResult::clear_msg() { + _impl_.msg_.ClearToEmpty(); +} +inline const std::string& AutotuneResult_FailureResult::msg() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.msg) + return _internal_msg(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuneResult_FailureResult::set_msg(ArgT0&& arg0, ArgT... args) { + + _impl_.msg_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.FailureResult.msg) +} +inline std::string* AutotuneResult_FailureResult::mutable_msg() { + std::string* _s = _internal_mutable_msg(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.FailureResult.msg) + return _s; +} +inline const std::string& AutotuneResult_FailureResult::_internal_msg() const { + return _impl_.msg_.Get(); +} +inline void AutotuneResult_FailureResult::_internal_set_msg(const std::string& value) { + + _impl_.msg_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuneResult_FailureResult::_internal_mutable_msg() { + + return _impl_.msg_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuneResult_FailureResult::release_msg() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.FailureResult.msg) + return _impl_.msg_.Release(); +} +inline void AutotuneResult_FailureResult::set_allocated_msg(std::string* msg) { + if (msg != nullptr) { + + } else { + + } + _impl_.msg_.SetAllocated(msg, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.msg_.IsDefault()) { + _impl_.msg_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResult.FailureResult.msg) +} + +// .xla.AutotuneResult.ConvKey reference_conv = 11; +inline bool AutotuneResult_FailureResult::_internal_has_reference_conv() const { + return key_case() == kReferenceConv; +} +inline bool AutotuneResult_FailureResult::has_reference_conv() const { + return _internal_has_reference_conv(); +} +inline void AutotuneResult_FailureResult::set_has_reference_conv() { + _impl_._oneof_case_[0] = kReferenceConv; +} +inline void AutotuneResult_FailureResult::clear_reference_conv() { + if (_internal_has_reference_conv()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.reference_conv_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult_FailureResult::release_reference_conv() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.FailureResult.reference_conv) + if (_internal_has_reference_conv()) { + clear_has_key(); + ::xla::AutotuneResult_ConvKey* temp = _impl_.key_.reference_conv_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.reference_conv_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_ConvKey& AutotuneResult_FailureResult::_internal_reference_conv() const { + return _internal_has_reference_conv() + ? *_impl_.key_.reference_conv_ + : reinterpret_cast< ::xla::AutotuneResult_ConvKey&>(::xla::_AutotuneResult_ConvKey_default_instance_); +} +inline const ::xla::AutotuneResult_ConvKey& AutotuneResult_FailureResult::reference_conv() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.reference_conv) + return _internal_reference_conv(); +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult_FailureResult::unsafe_arena_release_reference_conv() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.FailureResult.reference_conv) + if (_internal_has_reference_conv()) { + clear_has_key(); + ::xla::AutotuneResult_ConvKey* temp = _impl_.key_.reference_conv_; + _impl_.key_.reference_conv_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult_FailureResult::unsafe_arena_set_allocated_reference_conv(::xla::AutotuneResult_ConvKey* reference_conv) { + clear_key(); + if (reference_conv) { + set_has_reference_conv(); + _impl_.key_.reference_conv_ = reference_conv; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.FailureResult.reference_conv) +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult_FailureResult::_internal_mutable_reference_conv() { + if (!_internal_has_reference_conv()) { + clear_key(); + set_has_reference_conv(); + _impl_.key_.reference_conv_ = CreateMaybeMessage< ::xla::AutotuneResult_ConvKey >(GetArenaForAllocation()); + } + return _impl_.key_.reference_conv_; +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult_FailureResult::mutable_reference_conv() { + ::xla::AutotuneResult_ConvKey* _msg = _internal_mutable_reference_conv(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.FailureResult.reference_conv) + return _msg; +} + +// .xla.AutotuneResult.GemmKey reference_gemm = 12; +inline bool AutotuneResult_FailureResult::_internal_has_reference_gemm() const { + return key_case() == kReferenceGemm; +} +inline bool AutotuneResult_FailureResult::has_reference_gemm() const { + return _internal_has_reference_gemm(); +} +inline void AutotuneResult_FailureResult::set_has_reference_gemm() { + _impl_._oneof_case_[0] = kReferenceGemm; +} +inline void AutotuneResult_FailureResult::clear_reference_gemm() { + if (_internal_has_reference_gemm()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.reference_gemm_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult_FailureResult::release_reference_gemm() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.FailureResult.reference_gemm) + if (_internal_has_reference_gemm()) { + clear_has_key(); + ::xla::AutotuneResult_GemmKey* temp = _impl_.key_.reference_gemm_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.reference_gemm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_GemmKey& AutotuneResult_FailureResult::_internal_reference_gemm() const { + return _internal_has_reference_gemm() + ? *_impl_.key_.reference_gemm_ + : reinterpret_cast< ::xla::AutotuneResult_GemmKey&>(::xla::_AutotuneResult_GemmKey_default_instance_); +} +inline const ::xla::AutotuneResult_GemmKey& AutotuneResult_FailureResult::reference_gemm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.reference_gemm) + return _internal_reference_gemm(); +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult_FailureResult::unsafe_arena_release_reference_gemm() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.FailureResult.reference_gemm) + if (_internal_has_reference_gemm()) { + clear_has_key(); + ::xla::AutotuneResult_GemmKey* temp = _impl_.key_.reference_gemm_; + _impl_.key_.reference_gemm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult_FailureResult::unsafe_arena_set_allocated_reference_gemm(::xla::AutotuneResult_GemmKey* reference_gemm) { + clear_key(); + if (reference_gemm) { + set_has_reference_gemm(); + _impl_.key_.reference_gemm_ = reference_gemm; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.FailureResult.reference_gemm) +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult_FailureResult::_internal_mutable_reference_gemm() { + if (!_internal_has_reference_gemm()) { + clear_key(); + set_has_reference_gemm(); + _impl_.key_.reference_gemm_ = CreateMaybeMessage< ::xla::AutotuneResult_GemmKey >(GetArenaForAllocation()); + } + return _impl_.key_.reference_gemm_; +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult_FailureResult::mutable_reference_gemm() { + ::xla::AutotuneResult_GemmKey* _msg = _internal_mutable_reference_gemm(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.FailureResult.reference_gemm) + return _msg; +} + +// .xla.AutotuneResult.CudaConvPlanKey reference_cuda_conv_plan = 14; +inline bool AutotuneResult_FailureResult::_internal_has_reference_cuda_conv_plan() const { + return key_case() == kReferenceCudaConvPlan; +} +inline bool AutotuneResult_FailureResult::has_reference_cuda_conv_plan() const { + return _internal_has_reference_cuda_conv_plan(); +} +inline void AutotuneResult_FailureResult::set_has_reference_cuda_conv_plan() { + _impl_._oneof_case_[0] = kReferenceCudaConvPlan; +} +inline void AutotuneResult_FailureResult::clear_reference_cuda_conv_plan() { + if (_internal_has_reference_cuda_conv_plan()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.reference_cuda_conv_plan_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult_FailureResult::release_reference_cuda_conv_plan() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.FailureResult.reference_cuda_conv_plan) + if (_internal_has_reference_cuda_conv_plan()) { + clear_has_key(); + ::xla::AutotuneResult_CudaConvPlanKey* temp = _impl_.key_.reference_cuda_conv_plan_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.reference_cuda_conv_plan_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_CudaConvPlanKey& AutotuneResult_FailureResult::_internal_reference_cuda_conv_plan() const { + return _internal_has_reference_cuda_conv_plan() + ? *_impl_.key_.reference_cuda_conv_plan_ + : reinterpret_cast< ::xla::AutotuneResult_CudaConvPlanKey&>(::xla::_AutotuneResult_CudaConvPlanKey_default_instance_); +} +inline const ::xla::AutotuneResult_CudaConvPlanKey& AutotuneResult_FailureResult::reference_cuda_conv_plan() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.reference_cuda_conv_plan) + return _internal_reference_cuda_conv_plan(); +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult_FailureResult::unsafe_arena_release_reference_cuda_conv_plan() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.FailureResult.reference_cuda_conv_plan) + if (_internal_has_reference_cuda_conv_plan()) { + clear_has_key(); + ::xla::AutotuneResult_CudaConvPlanKey* temp = _impl_.key_.reference_cuda_conv_plan_; + _impl_.key_.reference_cuda_conv_plan_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult_FailureResult::unsafe_arena_set_allocated_reference_cuda_conv_plan(::xla::AutotuneResult_CudaConvPlanKey* reference_cuda_conv_plan) { + clear_key(); + if (reference_cuda_conv_plan) { + set_has_reference_cuda_conv_plan(); + _impl_.key_.reference_cuda_conv_plan_ = reference_cuda_conv_plan; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.FailureResult.reference_cuda_conv_plan) +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult_FailureResult::_internal_mutable_reference_cuda_conv_plan() { + if (!_internal_has_reference_cuda_conv_plan()) { + clear_key(); + set_has_reference_cuda_conv_plan(); + _impl_.key_.reference_cuda_conv_plan_ = CreateMaybeMessage< ::xla::AutotuneResult_CudaConvPlanKey >(GetArenaForAllocation()); + } + return _impl_.key_.reference_cuda_conv_plan_; +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult_FailureResult::mutable_reference_cuda_conv_plan() { + ::xla::AutotuneResult_CudaConvPlanKey* _msg = _internal_mutable_reference_cuda_conv_plan(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.FailureResult.reference_cuda_conv_plan) + return _msg; +} + +// .stream_executor.dnn.AlgorithmProto reference_algorithm = 15; +inline bool AutotuneResult_FailureResult::_internal_has_reference_algorithm() const { + return key_case() == kReferenceAlgorithm; +} +inline bool AutotuneResult_FailureResult::has_reference_algorithm() const { + return _internal_has_reference_algorithm(); +} +inline void AutotuneResult_FailureResult::set_has_reference_algorithm() { + _impl_._oneof_case_[0] = kReferenceAlgorithm; +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult_FailureResult::release_reference_algorithm() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.FailureResult.reference_algorithm) + if (_internal_has_reference_algorithm()) { + clear_has_key(); + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.key_.reference_algorithm_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.reference_algorithm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::dnn::AlgorithmProto& AutotuneResult_FailureResult::_internal_reference_algorithm() const { + return _internal_has_reference_algorithm() + ? *_impl_.key_.reference_algorithm_ + : reinterpret_cast< ::stream_executor::dnn::AlgorithmProto&>(::stream_executor::dnn::_AlgorithmProto_default_instance_); +} +inline const ::stream_executor::dnn::AlgorithmProto& AutotuneResult_FailureResult::reference_algorithm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.reference_algorithm) + return _internal_reference_algorithm(); +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult_FailureResult::unsafe_arena_release_reference_algorithm() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.FailureResult.reference_algorithm) + if (_internal_has_reference_algorithm()) { + clear_has_key(); + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.key_.reference_algorithm_; + _impl_.key_.reference_algorithm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult_FailureResult::unsafe_arena_set_allocated_reference_algorithm(::stream_executor::dnn::AlgorithmProto* reference_algorithm) { + clear_key(); + if (reference_algorithm) { + set_has_reference_algorithm(); + _impl_.key_.reference_algorithm_ = reference_algorithm; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.FailureResult.reference_algorithm) +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult_FailureResult::_internal_mutable_reference_algorithm() { + if (!_internal_has_reference_algorithm()) { + clear_key(); + set_has_reference_algorithm(); + _impl_.key_.reference_algorithm_ = CreateMaybeMessage< ::stream_executor::dnn::AlgorithmProto >(GetArenaForAllocation()); + } + return _impl_.key_.reference_algorithm_; +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult_FailureResult::mutable_reference_algorithm() { + ::stream_executor::dnn::AlgorithmProto* _msg = _internal_mutable_reference_algorithm(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.FailureResult.reference_algorithm) + return _msg; +} + +// int64 buffer_address = 13; +inline void AutotuneResult_FailureResult::clear_buffer_address() { + _impl_.buffer_address_ = int64_t{0}; +} +inline int64_t AutotuneResult_FailureResult::_internal_buffer_address() const { + return _impl_.buffer_address_; +} +inline int64_t AutotuneResult_FailureResult::buffer_address() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.FailureResult.buffer_address) + return _internal_buffer_address(); +} +inline void AutotuneResult_FailureResult::_internal_set_buffer_address(int64_t value) { + + _impl_.buffer_address_ = value; +} +inline void AutotuneResult_FailureResult::set_buffer_address(int64_t value) { + _internal_set_buffer_address(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.FailureResult.buffer_address) +} + +inline bool AutotuneResult_FailureResult::has_key() const { + return key_case() != KEY_NOT_SET; +} +inline void AutotuneResult_FailureResult::clear_has_key() { + _impl_._oneof_case_[0] = KEY_NOT_SET; +} +inline AutotuneResult_FailureResult::KeyCase AutotuneResult_FailureResult::key_case() const { + return AutotuneResult_FailureResult::KeyCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// AutotuneResult_ConvKey + +// int64 algorithm = 1; +inline void AutotuneResult_ConvKey::clear_algorithm() { + _impl_.algorithm_ = int64_t{0}; +} +inline int64_t AutotuneResult_ConvKey::_internal_algorithm() const { + return _impl_.algorithm_; +} +inline int64_t AutotuneResult_ConvKey::algorithm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.ConvKey.algorithm) + return _internal_algorithm(); +} +inline void AutotuneResult_ConvKey::_internal_set_algorithm(int64_t value) { + + _impl_.algorithm_ = value; +} +inline void AutotuneResult_ConvKey::set_algorithm(int64_t value) { + _internal_set_algorithm(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.ConvKey.algorithm) +} + +// bool tensor_ops_enabled = 2; +inline void AutotuneResult_ConvKey::clear_tensor_ops_enabled() { + _impl_.tensor_ops_enabled_ = false; +} +inline bool AutotuneResult_ConvKey::_internal_tensor_ops_enabled() const { + return _impl_.tensor_ops_enabled_; +} +inline bool AutotuneResult_ConvKey::tensor_ops_enabled() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.ConvKey.tensor_ops_enabled) + return _internal_tensor_ops_enabled(); +} +inline void AutotuneResult_ConvKey::_internal_set_tensor_ops_enabled(bool value) { + + _impl_.tensor_ops_enabled_ = value; +} +inline void AutotuneResult_ConvKey::set_tensor_ops_enabled(bool value) { + _internal_set_tensor_ops_enabled(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.ConvKey.tensor_ops_enabled) +} + +// ------------------------------------------------------------------- + +// AutotuneResult_GemmKey + +// int64 algorithm = 1; +inline void AutotuneResult_GemmKey::clear_algorithm() { + _impl_.algorithm_ = int64_t{0}; +} +inline int64_t AutotuneResult_GemmKey::_internal_algorithm() const { + return _impl_.algorithm_; +} +inline int64_t AutotuneResult_GemmKey::algorithm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.GemmKey.algorithm) + return _internal_algorithm(); +} +inline void AutotuneResult_GemmKey::_internal_set_algorithm(int64_t value) { + + _impl_.algorithm_ = value; +} +inline void AutotuneResult_GemmKey::set_algorithm(int64_t value) { + _internal_set_algorithm(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.GemmKey.algorithm) +} + +// ------------------------------------------------------------------- + +// AutotuneResult_CudaConvPlanKey + +// string exec_plan_id = 1; +inline void AutotuneResult_CudaConvPlanKey::clear_exec_plan_id() { + _impl_.exec_plan_id_.ClearToEmpty(); +} +inline const std::string& AutotuneResult_CudaConvPlanKey::exec_plan_id() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.CudaConvPlanKey.exec_plan_id) + return _internal_exec_plan_id(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuneResult_CudaConvPlanKey::set_exec_plan_id(ArgT0&& arg0, ArgT... args) { + + _impl_.exec_plan_id_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.CudaConvPlanKey.exec_plan_id) +} +inline std::string* AutotuneResult_CudaConvPlanKey::mutable_exec_plan_id() { + std::string* _s = _internal_mutable_exec_plan_id(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.CudaConvPlanKey.exec_plan_id) + return _s; +} +inline const std::string& AutotuneResult_CudaConvPlanKey::_internal_exec_plan_id() const { + return _impl_.exec_plan_id_.Get(); +} +inline void AutotuneResult_CudaConvPlanKey::_internal_set_exec_plan_id(const std::string& value) { + + _impl_.exec_plan_id_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuneResult_CudaConvPlanKey::_internal_mutable_exec_plan_id() { + + return _impl_.exec_plan_id_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuneResult_CudaConvPlanKey::release_exec_plan_id() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.CudaConvPlanKey.exec_plan_id) + return _impl_.exec_plan_id_.Release(); +} +inline void AutotuneResult_CudaConvPlanKey::set_allocated_exec_plan_id(std::string* exec_plan_id) { + if (exec_plan_id != nullptr) { + + } else { + + } + _impl_.exec_plan_id_.SetAllocated(exec_plan_id, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.exec_plan_id_.IsDefault()) { + _impl_.exec_plan_id_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResult.CudaConvPlanKey.exec_plan_id) +} + +// ------------------------------------------------------------------- + +// AutotuneResult_TritonGemmKey + +// int64 block_m = 1; +inline void AutotuneResult_TritonGemmKey::clear_block_m() { + _impl_.block_m_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_block_m() const { + return _impl_.block_m_; +} +inline int64_t AutotuneResult_TritonGemmKey::block_m() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.block_m) + return _internal_block_m(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_block_m(int64_t value) { + + _impl_.block_m_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_block_m(int64_t value) { + _internal_set_block_m(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.block_m) +} + +// int64 block_n = 2; +inline void AutotuneResult_TritonGemmKey::clear_block_n() { + _impl_.block_n_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_block_n() const { + return _impl_.block_n_; +} +inline int64_t AutotuneResult_TritonGemmKey::block_n() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.block_n) + return _internal_block_n(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_block_n(int64_t value) { + + _impl_.block_n_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_block_n(int64_t value) { + _internal_set_block_n(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.block_n) +} + +// int64 block_k = 3; +inline void AutotuneResult_TritonGemmKey::clear_block_k() { + _impl_.block_k_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_block_k() const { + return _impl_.block_k_; +} +inline int64_t AutotuneResult_TritonGemmKey::block_k() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.block_k) + return _internal_block_k(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_block_k(int64_t value) { + + _impl_.block_k_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_block_k(int64_t value) { + _internal_set_block_k(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.block_k) +} + +// int64 split_k = 4; +inline void AutotuneResult_TritonGemmKey::clear_split_k() { + _impl_.split_k_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_split_k() const { + return _impl_.split_k_; +} +inline int64_t AutotuneResult_TritonGemmKey::split_k() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.split_k) + return _internal_split_k(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_split_k(int64_t value) { + + _impl_.split_k_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_split_k(int64_t value) { + _internal_set_split_k(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.split_k) +} + +// int64 num_stages = 5; +inline void AutotuneResult_TritonGemmKey::clear_num_stages() { + _impl_.num_stages_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_num_stages() const { + return _impl_.num_stages_; +} +inline int64_t AutotuneResult_TritonGemmKey::num_stages() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.num_stages) + return _internal_num_stages(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_num_stages(int64_t value) { + + _impl_.num_stages_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_num_stages(int64_t value) { + _internal_set_num_stages(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.num_stages) +} + +// int64 num_warps = 6; +inline void AutotuneResult_TritonGemmKey::clear_num_warps() { + _impl_.num_warps_ = int64_t{0}; +} +inline int64_t AutotuneResult_TritonGemmKey::_internal_num_warps() const { + return _impl_.num_warps_; +} +inline int64_t AutotuneResult_TritonGemmKey::num_warps() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.TritonGemmKey.num_warps) + return _internal_num_warps(); +} +inline void AutotuneResult_TritonGemmKey::_internal_set_num_warps(int64_t value) { + + _impl_.num_warps_ = value; +} +inline void AutotuneResult_TritonGemmKey::set_num_warps(int64_t value) { + _internal_set_num_warps(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.TritonGemmKey.num_warps) +} + +// ------------------------------------------------------------------- + +// AutotuneResult + +// int64 scratch_bytes = 8; +inline void AutotuneResult::clear_scratch_bytes() { + _impl_.scratch_bytes_ = int64_t{0}; +} +inline int64_t AutotuneResult::_internal_scratch_bytes() const { + return _impl_.scratch_bytes_; +} +inline int64_t AutotuneResult::scratch_bytes() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.scratch_bytes) + return _internal_scratch_bytes(); +} +inline void AutotuneResult::_internal_set_scratch_bytes(int64_t value) { + + _impl_.scratch_bytes_ = value; +} +inline void AutotuneResult::set_scratch_bytes(int64_t value) { + _internal_set_scratch_bytes(value); + // @@protoc_insertion_point(field_set:xla.AutotuneResult.scratch_bytes) +} + +// .google.protobuf.Duration run_time = 9; +inline bool AutotuneResult::_internal_has_run_time() const { + return this != internal_default_instance() && _impl_.run_time_ != nullptr; +} +inline bool AutotuneResult::has_run_time() const { + return _internal_has_run_time(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& AutotuneResult::_internal_run_time() const { + const ::PROTOBUF_NAMESPACE_ID::Duration* p = _impl_.run_time_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_Duration_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& AutotuneResult::run_time() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.run_time) + return _internal_run_time(); +} +inline void AutotuneResult::unsafe_arena_set_allocated_run_time( + ::PROTOBUF_NAMESPACE_ID::Duration* run_time) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.run_time_); + } + _impl_.run_time_ = run_time; + if (run_time) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.run_time) +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* AutotuneResult::release_run_time() { + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.run_time_; + _impl_.run_time_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* AutotuneResult::unsafe_arena_release_run_time() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.run_time) + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.run_time_; + _impl_.run_time_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* AutotuneResult::_internal_mutable_run_time() { + + if (_impl_.run_time_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Duration>(GetArenaForAllocation()); + _impl_.run_time_ = p; + } + return _impl_.run_time_; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* AutotuneResult::mutable_run_time() { + ::PROTOBUF_NAMESPACE_ID::Duration* _msg = _internal_mutable_run_time(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.run_time) + return _msg; +} +inline void AutotuneResult::set_allocated_run_time(::PROTOBUF_NAMESPACE_ID::Duration* run_time) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.run_time_); + } + if (run_time) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(run_time)); + if (message_arena != submessage_arena) { + run_time = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, run_time, submessage_arena); + } + + } else { + + } + _impl_.run_time_ = run_time; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResult.run_time) +} + +// .xla.AutotuneResult.FailureResult failure = 7; +inline bool AutotuneResult::_internal_has_failure() const { + return this != internal_default_instance() && _impl_.failure_ != nullptr; +} +inline bool AutotuneResult::has_failure() const { + return _internal_has_failure(); +} +inline void AutotuneResult::clear_failure() { + if (GetArenaForAllocation() == nullptr && _impl_.failure_ != nullptr) { + delete _impl_.failure_; + } + _impl_.failure_ = nullptr; +} +inline const ::xla::AutotuneResult_FailureResult& AutotuneResult::_internal_failure() const { + const ::xla::AutotuneResult_FailureResult* p = _impl_.failure_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_AutotuneResult_FailureResult_default_instance_); +} +inline const ::xla::AutotuneResult_FailureResult& AutotuneResult::failure() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.failure) + return _internal_failure(); +} +inline void AutotuneResult::unsafe_arena_set_allocated_failure( + ::xla::AutotuneResult_FailureResult* failure) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.failure_); + } + _impl_.failure_ = failure; + if (failure) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.failure) +} +inline ::xla::AutotuneResult_FailureResult* AutotuneResult::release_failure() { + + ::xla::AutotuneResult_FailureResult* temp = _impl_.failure_; + _impl_.failure_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::AutotuneResult_FailureResult* AutotuneResult::unsafe_arena_release_failure() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.failure) + + ::xla::AutotuneResult_FailureResult* temp = _impl_.failure_; + _impl_.failure_ = nullptr; + return temp; +} +inline ::xla::AutotuneResult_FailureResult* AutotuneResult::_internal_mutable_failure() { + + if (_impl_.failure_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::AutotuneResult_FailureResult>(GetArenaForAllocation()); + _impl_.failure_ = p; + } + return _impl_.failure_; +} +inline ::xla::AutotuneResult_FailureResult* AutotuneResult::mutable_failure() { + ::xla::AutotuneResult_FailureResult* _msg = _internal_mutable_failure(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.failure) + return _msg; +} +inline void AutotuneResult::set_allocated_failure(::xla::AutotuneResult_FailureResult* failure) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.failure_; + } + if (failure) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(failure); + if (message_arena != submessage_arena) { + failure = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, failure, submessage_arena); + } + + } else { + + } + _impl_.failure_ = failure; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuneResult.failure) +} + +// .xla.AutotuneResult.ConvKey conv = 5; +inline bool AutotuneResult::_internal_has_conv() const { + return key_case() == kConv; +} +inline bool AutotuneResult::has_conv() const { + return _internal_has_conv(); +} +inline void AutotuneResult::set_has_conv() { + _impl_._oneof_case_[0] = kConv; +} +inline void AutotuneResult::clear_conv() { + if (_internal_has_conv()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.conv_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult::release_conv() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.conv) + if (_internal_has_conv()) { + clear_has_key(); + ::xla::AutotuneResult_ConvKey* temp = _impl_.key_.conv_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.conv_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_ConvKey& AutotuneResult::_internal_conv() const { + return _internal_has_conv() + ? *_impl_.key_.conv_ + : reinterpret_cast< ::xla::AutotuneResult_ConvKey&>(::xla::_AutotuneResult_ConvKey_default_instance_); +} +inline const ::xla::AutotuneResult_ConvKey& AutotuneResult::conv() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.conv) + return _internal_conv(); +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult::unsafe_arena_release_conv() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.conv) + if (_internal_has_conv()) { + clear_has_key(); + ::xla::AutotuneResult_ConvKey* temp = _impl_.key_.conv_; + _impl_.key_.conv_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult::unsafe_arena_set_allocated_conv(::xla::AutotuneResult_ConvKey* conv) { + clear_key(); + if (conv) { + set_has_conv(); + _impl_.key_.conv_ = conv; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.conv) +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult::_internal_mutable_conv() { + if (!_internal_has_conv()) { + clear_key(); + set_has_conv(); + _impl_.key_.conv_ = CreateMaybeMessage< ::xla::AutotuneResult_ConvKey >(GetArenaForAllocation()); + } + return _impl_.key_.conv_; +} +inline ::xla::AutotuneResult_ConvKey* AutotuneResult::mutable_conv() { + ::xla::AutotuneResult_ConvKey* _msg = _internal_mutable_conv(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.conv) + return _msg; +} + +// .xla.AutotuneResult.GemmKey gemm = 6; +inline bool AutotuneResult::_internal_has_gemm() const { + return key_case() == kGemm; +} +inline bool AutotuneResult::has_gemm() const { + return _internal_has_gemm(); +} +inline void AutotuneResult::set_has_gemm() { + _impl_._oneof_case_[0] = kGemm; +} +inline void AutotuneResult::clear_gemm() { + if (_internal_has_gemm()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.gemm_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult::release_gemm() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.gemm) + if (_internal_has_gemm()) { + clear_has_key(); + ::xla::AutotuneResult_GemmKey* temp = _impl_.key_.gemm_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.gemm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_GemmKey& AutotuneResult::_internal_gemm() const { + return _internal_has_gemm() + ? *_impl_.key_.gemm_ + : reinterpret_cast< ::xla::AutotuneResult_GemmKey&>(::xla::_AutotuneResult_GemmKey_default_instance_); +} +inline const ::xla::AutotuneResult_GemmKey& AutotuneResult::gemm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.gemm) + return _internal_gemm(); +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult::unsafe_arena_release_gemm() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.gemm) + if (_internal_has_gemm()) { + clear_has_key(); + ::xla::AutotuneResult_GemmKey* temp = _impl_.key_.gemm_; + _impl_.key_.gemm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult::unsafe_arena_set_allocated_gemm(::xla::AutotuneResult_GemmKey* gemm) { + clear_key(); + if (gemm) { + set_has_gemm(); + _impl_.key_.gemm_ = gemm; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.gemm) +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult::_internal_mutable_gemm() { + if (!_internal_has_gemm()) { + clear_key(); + set_has_gemm(); + _impl_.key_.gemm_ = CreateMaybeMessage< ::xla::AutotuneResult_GemmKey >(GetArenaForAllocation()); + } + return _impl_.key_.gemm_; +} +inline ::xla::AutotuneResult_GemmKey* AutotuneResult::mutable_gemm() { + ::xla::AutotuneResult_GemmKey* _msg = _internal_mutable_gemm(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.gemm) + return _msg; +} + +// .xla.AutotuneResult.TritonGemmKey triton = 17; +inline bool AutotuneResult::_internal_has_triton() const { + return key_case() == kTriton; +} +inline bool AutotuneResult::has_triton() const { + return _internal_has_triton(); +} +inline void AutotuneResult::set_has_triton() { + _impl_._oneof_case_[0] = kTriton; +} +inline void AutotuneResult::clear_triton() { + if (_internal_has_triton()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.triton_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_TritonGemmKey* AutotuneResult::release_triton() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.triton) + if (_internal_has_triton()) { + clear_has_key(); + ::xla::AutotuneResult_TritonGemmKey* temp = _impl_.key_.triton_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.triton_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_TritonGemmKey& AutotuneResult::_internal_triton() const { + return _internal_has_triton() + ? *_impl_.key_.triton_ + : reinterpret_cast< ::xla::AutotuneResult_TritonGemmKey&>(::xla::_AutotuneResult_TritonGemmKey_default_instance_); +} +inline const ::xla::AutotuneResult_TritonGemmKey& AutotuneResult::triton() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.triton) + return _internal_triton(); +} +inline ::xla::AutotuneResult_TritonGemmKey* AutotuneResult::unsafe_arena_release_triton() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.triton) + if (_internal_has_triton()) { + clear_has_key(); + ::xla::AutotuneResult_TritonGemmKey* temp = _impl_.key_.triton_; + _impl_.key_.triton_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult::unsafe_arena_set_allocated_triton(::xla::AutotuneResult_TritonGemmKey* triton) { + clear_key(); + if (triton) { + set_has_triton(); + _impl_.key_.triton_ = triton; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.triton) +} +inline ::xla::AutotuneResult_TritonGemmKey* AutotuneResult::_internal_mutable_triton() { + if (!_internal_has_triton()) { + clear_key(); + set_has_triton(); + _impl_.key_.triton_ = CreateMaybeMessage< ::xla::AutotuneResult_TritonGemmKey >(GetArenaForAllocation()); + } + return _impl_.key_.triton_; +} +inline ::xla::AutotuneResult_TritonGemmKey* AutotuneResult::mutable_triton() { + ::xla::AutotuneResult_TritonGemmKey* _msg = _internal_mutable_triton(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.triton) + return _msg; +} + +// .xla.AutotuneResult.CudaConvPlanKey cuda_conv_plan = 15; +inline bool AutotuneResult::_internal_has_cuda_conv_plan() const { + return key_case() == kCudaConvPlan; +} +inline bool AutotuneResult::has_cuda_conv_plan() const { + return _internal_has_cuda_conv_plan(); +} +inline void AutotuneResult::set_has_cuda_conv_plan() { + _impl_._oneof_case_[0] = kCudaConvPlan; +} +inline void AutotuneResult::clear_cuda_conv_plan() { + if (_internal_has_cuda_conv_plan()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.key_.cuda_conv_plan_; + } + clear_has_key(); + } +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult::release_cuda_conv_plan() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.cuda_conv_plan) + if (_internal_has_cuda_conv_plan()) { + clear_has_key(); + ::xla::AutotuneResult_CudaConvPlanKey* temp = _impl_.key_.cuda_conv_plan_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.cuda_conv_plan_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::xla::AutotuneResult_CudaConvPlanKey& AutotuneResult::_internal_cuda_conv_plan() const { + return _internal_has_cuda_conv_plan() + ? *_impl_.key_.cuda_conv_plan_ + : reinterpret_cast< ::xla::AutotuneResult_CudaConvPlanKey&>(::xla::_AutotuneResult_CudaConvPlanKey_default_instance_); +} +inline const ::xla::AutotuneResult_CudaConvPlanKey& AutotuneResult::cuda_conv_plan() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.cuda_conv_plan) + return _internal_cuda_conv_plan(); +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult::unsafe_arena_release_cuda_conv_plan() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.cuda_conv_plan) + if (_internal_has_cuda_conv_plan()) { + clear_has_key(); + ::xla::AutotuneResult_CudaConvPlanKey* temp = _impl_.key_.cuda_conv_plan_; + _impl_.key_.cuda_conv_plan_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult::unsafe_arena_set_allocated_cuda_conv_plan(::xla::AutotuneResult_CudaConvPlanKey* cuda_conv_plan) { + clear_key(); + if (cuda_conv_plan) { + set_has_cuda_conv_plan(); + _impl_.key_.cuda_conv_plan_ = cuda_conv_plan; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.cuda_conv_plan) +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult::_internal_mutable_cuda_conv_plan() { + if (!_internal_has_cuda_conv_plan()) { + clear_key(); + set_has_cuda_conv_plan(); + _impl_.key_.cuda_conv_plan_ = CreateMaybeMessage< ::xla::AutotuneResult_CudaConvPlanKey >(GetArenaForAllocation()); + } + return _impl_.key_.cuda_conv_plan_; +} +inline ::xla::AutotuneResult_CudaConvPlanKey* AutotuneResult::mutable_cuda_conv_plan() { + ::xla::AutotuneResult_CudaConvPlanKey* _msg = _internal_mutable_cuda_conv_plan(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.cuda_conv_plan) + return _msg; +} + +// .stream_executor.dnn.AlgorithmProto algorithm = 16; +inline bool AutotuneResult::_internal_has_algorithm() const { + return key_case() == kAlgorithm; +} +inline bool AutotuneResult::has_algorithm() const { + return _internal_has_algorithm(); +} +inline void AutotuneResult::set_has_algorithm() { + _impl_._oneof_case_[0] = kAlgorithm; +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult::release_algorithm() { + // @@protoc_insertion_point(field_release:xla.AutotuneResult.algorithm) + if (_internal_has_algorithm()) { + clear_has_key(); + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.key_.algorithm_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.key_.algorithm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::dnn::AlgorithmProto& AutotuneResult::_internal_algorithm() const { + return _internal_has_algorithm() + ? *_impl_.key_.algorithm_ + : reinterpret_cast< ::stream_executor::dnn::AlgorithmProto&>(::stream_executor::dnn::_AlgorithmProto_default_instance_); +} +inline const ::stream_executor::dnn::AlgorithmProto& AutotuneResult::algorithm() const { + // @@protoc_insertion_point(field_get:xla.AutotuneResult.algorithm) + return _internal_algorithm(); +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult::unsafe_arena_release_algorithm() { + // @@protoc_insertion_point(field_unsafe_arena_release:xla.AutotuneResult.algorithm) + if (_internal_has_algorithm()) { + clear_has_key(); + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.key_.algorithm_; + _impl_.key_.algorithm_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AutotuneResult::unsafe_arena_set_allocated_algorithm(::stream_executor::dnn::AlgorithmProto* algorithm) { + clear_key(); + if (algorithm) { + set_has_algorithm(); + _impl_.key_.algorithm_ = algorithm; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuneResult.algorithm) +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult::_internal_mutable_algorithm() { + if (!_internal_has_algorithm()) { + clear_key(); + set_has_algorithm(); + _impl_.key_.algorithm_ = CreateMaybeMessage< ::stream_executor::dnn::AlgorithmProto >(GetArenaForAllocation()); + } + return _impl_.key_.algorithm_; +} +inline ::stream_executor::dnn::AlgorithmProto* AutotuneResult::mutable_algorithm() { + ::stream_executor::dnn::AlgorithmProto* _msg = _internal_mutable_algorithm(); + // @@protoc_insertion_point(field_mutable:xla.AutotuneResult.algorithm) + return _msg; +} + +inline bool AutotuneResult::has_key() const { + return key_case() != KEY_NOT_SET; +} +inline void AutotuneResult::clear_has_key() { + _impl_._oneof_case_[0] = KEY_NOT_SET; +} +inline AutotuneResult::KeyCase AutotuneResult::key_case() const { + return AutotuneResult::KeyCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// AutotuningLog + +// .google.protobuf.Any instr = 1; +inline bool AutotuningLog::_internal_has_instr() const { + return this != internal_default_instance() && _impl_.instr_ != nullptr; +} +inline bool AutotuningLog::has_instr() const { + return _internal_has_instr(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Any& AutotuningLog::_internal_instr() const { + const ::PROTOBUF_NAMESPACE_ID::Any* p = _impl_.instr_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_Any_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Any& AutotuningLog::instr() const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.instr) + return _internal_instr(); +} +inline void AutotuningLog::unsafe_arena_set_allocated_instr( + ::PROTOBUF_NAMESPACE_ID::Any* instr) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instr_); + } + _impl_.instr_ = instr; + if (instr) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuningLog.instr) +} +inline ::PROTOBUF_NAMESPACE_ID::Any* AutotuningLog::release_instr() { + + ::PROTOBUF_NAMESPACE_ID::Any* temp = _impl_.instr_; + _impl_.instr_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Any* AutotuningLog::unsafe_arena_release_instr() { + // @@protoc_insertion_point(field_release:xla.AutotuningLog.instr) + + ::PROTOBUF_NAMESPACE_ID::Any* temp = _impl_.instr_; + _impl_.instr_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Any* AutotuningLog::_internal_mutable_instr() { + + if (_impl_.instr_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Any>(GetArenaForAllocation()); + _impl_.instr_ = p; + } + return _impl_.instr_; +} +inline ::PROTOBUF_NAMESPACE_ID::Any* AutotuningLog::mutable_instr() { + ::PROTOBUF_NAMESPACE_ID::Any* _msg = _internal_mutable_instr(); + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.instr) + return _msg; +} +inline void AutotuningLog::set_allocated_instr(::PROTOBUF_NAMESPACE_ID::Any* instr) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instr_); + } + if (instr) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(instr)); + if (message_arena != submessage_arena) { + instr = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, instr, submessage_arena); + } + + } else { + + } + _impl_.instr_ = instr; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuningLog.instr) +} + +// repeated .xla.AutotuneResult results = 2; +inline int AutotuningLog::_internal_results_size() const { + return _impl_.results_.size(); +} +inline int AutotuningLog::results_size() const { + return _internal_results_size(); +} +inline void AutotuningLog::clear_results() { + _impl_.results_.Clear(); +} +inline ::xla::AutotuneResult* AutotuningLog::mutable_results(int index) { + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.results) + return _impl_.results_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResult >* +AutotuningLog::mutable_results() { + // @@protoc_insertion_point(field_mutable_list:xla.AutotuningLog.results) + return &_impl_.results_; +} +inline const ::xla::AutotuneResult& AutotuningLog::_internal_results(int index) const { + return _impl_.results_.Get(index); +} +inline const ::xla::AutotuneResult& AutotuningLog::results(int index) const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.results) + return _internal_results(index); +} +inline ::xla::AutotuneResult* AutotuningLog::_internal_add_results() { + return _impl_.results_.Add(); +} +inline ::xla::AutotuneResult* AutotuningLog::add_results() { + ::xla::AutotuneResult* _add = _internal_add_results(); + // @@protoc_insertion_point(field_add:xla.AutotuningLog.results) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::AutotuneResult >& +AutotuningLog::results() const { + // @@protoc_insertion_point(field_list:xla.AutotuningLog.results) + return _impl_.results_; +} + +// .xla.CudnnVersion cudnn_version = 3; +inline bool AutotuningLog::_internal_has_cudnn_version() const { + return this != internal_default_instance() && _impl_.cudnn_version_ != nullptr; +} +inline bool AutotuningLog::has_cudnn_version() const { + return _internal_has_cudnn_version(); +} +inline void AutotuningLog::clear_cudnn_version() { + if (GetArenaForAllocation() == nullptr && _impl_.cudnn_version_ != nullptr) { + delete _impl_.cudnn_version_; + } + _impl_.cudnn_version_ = nullptr; +} +inline const ::xla::CudnnVersion& AutotuningLog::_internal_cudnn_version() const { + const ::xla::CudnnVersion* p = _impl_.cudnn_version_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_CudnnVersion_default_instance_); +} +inline const ::xla::CudnnVersion& AutotuningLog::cudnn_version() const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.cudnn_version) + return _internal_cudnn_version(); +} +inline void AutotuningLog::unsafe_arena_set_allocated_cudnn_version( + ::xla::CudnnVersion* cudnn_version) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cudnn_version_); + } + _impl_.cudnn_version_ = cudnn_version; + if (cudnn_version) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuningLog.cudnn_version) +} +inline ::xla::CudnnVersion* AutotuningLog::release_cudnn_version() { + + ::xla::CudnnVersion* temp = _impl_.cudnn_version_; + _impl_.cudnn_version_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::CudnnVersion* AutotuningLog::unsafe_arena_release_cudnn_version() { + // @@protoc_insertion_point(field_release:xla.AutotuningLog.cudnn_version) + + ::xla::CudnnVersion* temp = _impl_.cudnn_version_; + _impl_.cudnn_version_ = nullptr; + return temp; +} +inline ::xla::CudnnVersion* AutotuningLog::_internal_mutable_cudnn_version() { + + if (_impl_.cudnn_version_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::CudnnVersion>(GetArenaForAllocation()); + _impl_.cudnn_version_ = p; + } + return _impl_.cudnn_version_; +} +inline ::xla::CudnnVersion* AutotuningLog::mutable_cudnn_version() { + ::xla::CudnnVersion* _msg = _internal_mutable_cudnn_version(); + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.cudnn_version) + return _msg; +} +inline void AutotuningLog::set_allocated_cudnn_version(::xla::CudnnVersion* cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.cudnn_version_; + } + if (cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(cudnn_version); + if (message_arena != submessage_arena) { + cudnn_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cudnn_version, submessage_arena); + } + + } else { + + } + _impl_.cudnn_version_ = cudnn_version; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuningLog.cudnn_version) +} + +// .xla.ComputeCapability compute_capability = 4; +inline bool AutotuningLog::_internal_has_compute_capability() const { + return this != internal_default_instance() && _impl_.compute_capability_ != nullptr; +} +inline bool AutotuningLog::has_compute_capability() const { + return _internal_has_compute_capability(); +} +inline void AutotuningLog::clear_compute_capability() { + if (GetArenaForAllocation() == nullptr && _impl_.compute_capability_ != nullptr) { + delete _impl_.compute_capability_; + } + _impl_.compute_capability_ = nullptr; +} +inline const ::xla::ComputeCapability& AutotuningLog::_internal_compute_capability() const { + const ::xla::ComputeCapability* p = _impl_.compute_capability_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ComputeCapability_default_instance_); +} +inline const ::xla::ComputeCapability& AutotuningLog::compute_capability() const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.compute_capability) + return _internal_compute_capability(); +} +inline void AutotuningLog::unsafe_arena_set_allocated_compute_capability( + ::xla::ComputeCapability* compute_capability) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.compute_capability_); + } + _impl_.compute_capability_ = compute_capability; + if (compute_capability) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.AutotuningLog.compute_capability) +} +inline ::xla::ComputeCapability* AutotuningLog::release_compute_capability() { + + ::xla::ComputeCapability* temp = _impl_.compute_capability_; + _impl_.compute_capability_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::ComputeCapability* AutotuningLog::unsafe_arena_release_compute_capability() { + // @@protoc_insertion_point(field_release:xla.AutotuningLog.compute_capability) + + ::xla::ComputeCapability* temp = _impl_.compute_capability_; + _impl_.compute_capability_ = nullptr; + return temp; +} +inline ::xla::ComputeCapability* AutotuningLog::_internal_mutable_compute_capability() { + + if (_impl_.compute_capability_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ComputeCapability>(GetArenaForAllocation()); + _impl_.compute_capability_ = p; + } + return _impl_.compute_capability_; +} +inline ::xla::ComputeCapability* AutotuningLog::mutable_compute_capability() { + ::xla::ComputeCapability* _msg = _internal_mutable_compute_capability(); + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.compute_capability) + return _msg; +} +inline void AutotuningLog::set_allocated_compute_capability(::xla::ComputeCapability* compute_capability) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.compute_capability_; + } + if (compute_capability) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(compute_capability); + if (message_arena != submessage_arena) { + compute_capability = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, compute_capability, submessage_arena); + } + + } else { + + } + _impl_.compute_capability_ = compute_capability; + // @@protoc_insertion_point(field_set_allocated:xla.AutotuningLog.compute_capability) +} + +// string device_pci_bus_id = 5; +inline void AutotuningLog::clear_device_pci_bus_id() { + _impl_.device_pci_bus_id_.ClearToEmpty(); +} +inline const std::string& AutotuningLog::device_pci_bus_id() const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.device_pci_bus_id) + return _internal_device_pci_bus_id(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuningLog::set_device_pci_bus_id(ArgT0&& arg0, ArgT... args) { + + _impl_.device_pci_bus_id_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuningLog.device_pci_bus_id) +} +inline std::string* AutotuningLog::mutable_device_pci_bus_id() { + std::string* _s = _internal_mutable_device_pci_bus_id(); + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.device_pci_bus_id) + return _s; +} +inline const std::string& AutotuningLog::_internal_device_pci_bus_id() const { + return _impl_.device_pci_bus_id_.Get(); +} +inline void AutotuningLog::_internal_set_device_pci_bus_id(const std::string& value) { + + _impl_.device_pci_bus_id_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuningLog::_internal_mutable_device_pci_bus_id() { + + return _impl_.device_pci_bus_id_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuningLog::release_device_pci_bus_id() { + // @@protoc_insertion_point(field_release:xla.AutotuningLog.device_pci_bus_id) + return _impl_.device_pci_bus_id_.Release(); +} +inline void AutotuningLog::set_allocated_device_pci_bus_id(std::string* device_pci_bus_id) { + if (device_pci_bus_id != nullptr) { + + } else { + + } + _impl_.device_pci_bus_id_.SetAllocated(device_pci_bus_id, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_pci_bus_id_.IsDefault()) { + _impl_.device_pci_bus_id_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuningLog.device_pci_bus_id) +} + +// string blas_version = 6; +inline void AutotuningLog::clear_blas_version() { + _impl_.blas_version_.ClearToEmpty(); +} +inline const std::string& AutotuningLog::blas_version() const { + // @@protoc_insertion_point(field_get:xla.AutotuningLog.blas_version) + return _internal_blas_version(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AutotuningLog::set_blas_version(ArgT0&& arg0, ArgT... args) { + + _impl_.blas_version_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.AutotuningLog.blas_version) +} +inline std::string* AutotuningLog::mutable_blas_version() { + std::string* _s = _internal_mutable_blas_version(); + // @@protoc_insertion_point(field_mutable:xla.AutotuningLog.blas_version) + return _s; +} +inline const std::string& AutotuningLog::_internal_blas_version() const { + return _impl_.blas_version_.Get(); +} +inline void AutotuningLog::_internal_set_blas_version(const std::string& value) { + + _impl_.blas_version_.Set(value, GetArenaForAllocation()); +} +inline std::string* AutotuningLog::_internal_mutable_blas_version() { + + return _impl_.blas_version_.Mutable(GetArenaForAllocation()); +} +inline std::string* AutotuningLog::release_blas_version() { + // @@protoc_insertion_point(field_release:xla.AutotuningLog.blas_version) + return _impl_.blas_version_.Release(); +} +inline void AutotuningLog::set_allocated_blas_version(std::string* blas_version) { + if (blas_version != nullptr) { + + } else { + + } + _impl_.blas_version_.SetAllocated(blas_version, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.blas_version_.IsDefault()) { + _impl_.blas_version_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.AutotuningLog.blas_version) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace xla + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::xla::AutotuneResult_FailureKind> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::AutotuneResult_FailureKind>() { + return ::xla::AutotuneResult_FailureKind_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fautotuning_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/host_tracer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/host_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..fb2bdd20fedb31788baa0247273a7f2485a34169 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/host_tracer.h @@ -0,0 +1,43 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_BACKENDS_PROFILER_CPU_HOST_TRACER_H_ +#define XLA_BACKENDS_PROFILER_CPU_HOST_TRACER_H_ + +#include + +#include "tsl/profiler/lib/profiler_interface.h" + +namespace xla { +namespace profiler { + +struct HostTracerOptions { + // Levels of host tracing: + // - Level 0 is used to disable host traces. + // - Level 1 enables tracing of only user instrumented (or default) TraceMe. + // - Level 2 enables tracing of all level 1 TraceMe(s) and instrumented high + // level program execution details (expensive TF ops, XLA ops, etc). + // This is the default. + // - Level 3 enables tracing of all level 2 TraceMe(s) and more verbose + // (low-level) program execution details (cheap TF ops, etc). + int trace_level = 2; +}; + +std::unique_ptr CreateHostTracer( + const HostTracerOptions& options); + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_CPU_HOST_TRACER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/metadata_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/metadata_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1e3c8a215faa5945f6e687475555ed13c1cd3cac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/cpu/metadata_utils.h @@ -0,0 +1,55 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_CPU_METADATA_UTILS_H_ +#define XLA_BACKENDS_PROFILER_CPU_METADATA_UTILS_H_ + +#include "xla/service/hlo.pb.h" +#include "tsl/profiler/convert/xla_op_utils.h" +#include "tsl/profiler/protobuf/xplane.pb.h" +#include "tsl/profiler/utils/xplane_builder.h" +#include "tsl/profiler/utils/xplane_schema.h" + +namespace xla { +namespace profiler { + +class MetadataXPlaneBuilder { + public: + explicit MetadataXPlaneBuilder(tsl::profiler::XPlane* raw_plane) + : plane_(raw_plane), + hlo_proto_stat_(plane_.GetOrCreateStatMetadata( + GetStatTypeStr(tsl::profiler::StatType::kHloProto))) {} + + void AddHloProto(uint64_t program_id, const xla::HloProto& hlo_proto) { + tsl::profiler::XEventMetadata* event_metadata = + plane_.GetOrCreateEventMetadata(program_id); + if (event_metadata->name().empty()) { + event_metadata->set_name(tsl::profiler::HloModuleNameWithProgramId( + hlo_proto.hlo_module().name(), program_id)); + tsl::profiler::XStatsBuilder event_stats( + event_metadata, &plane_); + event_stats.AddStatValue(*hlo_proto_stat_, hlo_proto); + } + } + + private: + tsl::profiler::XPlaneBuilder plane_; + const tsl::profiler::XStatMetadata* hlo_proto_stat_ = nullptr; +}; + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_CPU_METADATA_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_collector.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_collector.h new file mode 100644 index 0000000000000000000000000000000000000000..8af5927269de52ffe90967096eac79ccf9ccea1e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_collector.h @@ -0,0 +1,297 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_COLLECTOR_H_ +#define XLA_BACKENDS_PROFILER_GPU_CUPTI_COLLECTOR_H_ + +#include + +#include "absl/container/fixed_array.h" +#include "absl/container/flat_hash_map.h" +#include "absl/container/node_hash_set.h" +#include "absl/strings/string_view.h" +#include "tsl/platform/macros.h" +#include "tsl/platform/status.h" +#include "tsl/platform/types.h" +#include "tsl/profiler/protobuf/xplane.pb.h" + +namespace xla { +namespace profiler { + +struct MemcpyDetails { + // The amount of data copied for memcpy events. + size_t num_bytes; + // The destination device for peer-2-peer communication (memcpy). The source + // device is implicit: it's the current device. + tsl::uint32 destination; + // Whether or not the memcpy is asynchronous. + bool async; + // This contains CUpti_ActivityMemcpyKind for activity event (on device). + // For events from other CuptiTracerEventSource, it is always 0. + tsl::int8 copy_kind; + // CUpti_ActivityMemoryKind of source. + tsl::int8 src_mem_kind; + // CUpti_ActivityMemoryKind of destination. + tsl::int8 dst_mem_kind; + + // ID of the hardware channel on which this operation ran. + uint32_t channel_id = -1; + // CUpti_ChannelType of the channel above. + int8_t channel_type = 0; // CUPTI_CHANNEL_TYPE_INVALID +}; + +struct MemAllocDetails { + // Size of memory to be written over in bytes. + size_t num_bytes; + // The CUpti_ActivityMemoryKind value for this activity event. + tsl::int8 mem_kind; + // The virtual address of allocation. 0 if it is a free operation. + tsl::uint64 address; +}; + +using MemFreeDetails = MemAllocDetails; + +// Memory residency contains details read from CUpti_ActivityMemory type. This +// is populated in the CUPTI tracer encounters a CUPTI_ACTIVITY_KIND_MEMORY +// event. The start of this even corresponse to a cudaMalloc, and the end +// corresponds to a cudaFree. +using MemoryResidencyDetails = MemAllocDetails; + +// cudaHostRegister +struct HostRegisterDetails { + size_t num_bytes; + tsl::uint64 address; + unsigned int flags; +}; + +// cudaHostUnregister +struct HostUnregisterDetails { + tsl::uint64 address; +}; + +struct MemsetDetails { + // Size of memory to be written over in bytes. + size_t num_bytes; + // The CUpti_ActivityMemoryKind value for this activity event. + tsl::int8 mem_kind; + // Whether or not the memset is asynchronous. + bool async; + + // ID of the hardware channel on which this operation ran. + uint32_t channel_id = -1; + // CUpti_ChannelType of the channel above. + int8_t channel_type = 0; // CUPTI_CHANNEL_TYPE_INVALID +}; + +struct KernelDetails { + // The number of registers used in this kernel. + tsl::uint32 registers_per_thread; + // The amount of shared memory space used by a thread block. + tsl::uint32 static_shared_memory_usage; + // The amount of dynamic memory space used by a thread block. + tsl::uint32 dynamic_shared_memory_usage; + // X-dimension of a thread block. + tsl::uint32 block_x; + // Y-dimension of a thread block. + tsl::uint32 block_y; + // Z-dimension of a thread block. + tsl::uint32 block_z; + // X-dimension of a grid. + tsl::uint32 grid_x; + // Y-dimension of a grid. + tsl::uint32 grid_y; + // Z-dimension of a grid. + tsl::uint32 grid_z; + + // ID of the hardware channel on which this operation ran. + uint32_t channel_id = -1; + // CUpti_ChannelType of the channel above. + int8_t channel_type = 0; // CUPTI_CHANNEL_TYPE_INVALID +}; + +inline std::string ToXStat(const KernelDetails& kernel_info, + double occupancy_pct) { + return absl::StrCat( + "regs:", kernel_info.registers_per_thread, + " static_shared:", kernel_info.static_shared_memory_usage, + " dynamic_shared:", kernel_info.dynamic_shared_memory_usage, + " grid:", kernel_info.grid_x, ",", kernel_info.grid_y, ",", + kernel_info.grid_z, " block:", kernel_info.block_x, ",", + kernel_info.block_y, ",", kernel_info.block_z, + " occ_pct:", occupancy_pct); +} + +// Gets the name of the CUpti_ActivityMemoryKind value. +absl::string_view GetMemoryKindName(int8_t memory_kind); + +enum class CuptiTracerEventType { + Unsupported = 0, + Kernel = 1, + MemcpyH2D = 2, + MemcpyD2H = 3, + MemcpyD2D = 4, + MemcpyP2P = 5, + MemcpyOther = 6, + MemoryAlloc = 7, + Overhead = 8, + UnifiedMemory = 9, + MemoryFree = 10, + Memset = 11, + MemoryResidency = 12, + HostRegister = 13, + HostUnregister = 14, + Generic = 100, +}; + +const char* GetTraceEventTypeName(const CuptiTracerEventType& type); + +enum class CuptiTracerEventSource { + Invalid = 0, + DriverCallback = 1, + Activity = 2, + // Maybe consider adding runtime callback and metric api in the future. +}; + +struct CuptiTracerEvent { + static constexpr tsl::uint32 kInvalidThreadId = + std::numeric_limits::max(); + static constexpr tsl::uint32 kInvalidCorrelationId = + std::numeric_limits::max(); + static constexpr tsl::uint64 kInvalidContextId = + std::numeric_limits::max(); + static constexpr tsl::uint64 kInvalidStreamId = + std::numeric_limits::max(); + CuptiTracerEventType type = CuptiTracerEventType::Unsupported; + CuptiTracerEventSource source = CuptiTracerEventSource::Invalid; + // Although CUpti_CallbackData::functionName is persistent, however + // CUpti_ActivityKernel4::name is not persistent, therefore we need a copy of + // it. + std::string name; + // This points to strings in AnnotationMap, which should outlive the point + // where serialization happens. + absl::string_view annotation; + absl::string_view nvtx_range; + tsl::uint64 start_time_ns = 0; + tsl::uint64 end_time_ns = 0; + tsl::uint32 device_id = 0; + tsl::uint32 correlation_id = kInvalidCorrelationId; + tsl::uint32 thread_id = kInvalidThreadId; + int64_t context_id = kInvalidContextId; + int64_t stream_id = kInvalidStreamId; + union { + // For Memcpy API and activities. `type` must be Memcpy*. + MemcpyDetails memcpy_info; + // Used for MemAlloc API. `type` must be MemoryAlloc. + MemAllocDetails memalloc_info; + // Used for kernel activities. `type` must be Kernel. + KernelDetails kernel_info; + // Used for MemFree activities. `type` must be MemoryFree. + MemFreeDetails memfree_info; + // Used for cuMemHostRegister. `type` must be HostRegister. + HostRegisterDetails host_register_info; + // Used for cuMemHostUnregister. `type` must be HostUnregister. + HostUnregisterDetails host_unregister_info; + // Used for Memset API and activities. `type` must be Memset. + MemsetDetails memset_info; + // Used for Memory residency activities. `type` must be MemoryResidency. + MemoryResidencyDetails memory_residency_info; + }; +}; + +struct CuptiTracerCollectorOptions { + // Maximum number of events to collect from callback API; if -1, no limit. + // if 0, the callback API is enabled to build a correlation map, but no + // events are collected. + tsl::uint64 max_callback_api_events = 2 * 1024 * 1024; + // Maximum number of events to collect from activity API; if -1, no limit. + tsl::uint64 max_activity_api_events = 2 * 1024 * 1024; + // Maximum number of annotation strings that we can accommodate. + tsl::uint64 max_annotation_strings = 1024 * 1024; + // Number of GPUs involved. + tsl::uint32 num_gpus; +}; + +class AnnotationMap { + public: + struct AnnotationInfo { + absl::string_view annotation; + absl::string_view nvtx_range; + }; + + explicit AnnotationMap(tsl::uint64 max_size, tsl::uint32 num_gpus) + : max_size_(max_size), per_device_map_(num_gpus) {} + void Add(tsl::uint32 device_id, tsl::uint32 correlation_id, + const absl::string_view annotation, + const absl::string_view nvtx_range); + AnnotationInfo LookUp(tsl::uint32 device_id, tsl::uint32 correlation_id); + + private: + struct PerDeviceAnnotationMap { + // The population/consumption of annotations might happen from multiple + // callback/activity api related threads. + absl::Mutex mutex; + // Annotation tends to be repetitive, use a hash_set to store the strings, + // an use the reference to the string in the map. + absl::node_hash_set annotations; + absl::node_hash_set nvtx_ranges; + absl::flat_hash_map correlation_map; + }; + const tsl::uint64 max_size_; + absl::FixedArray per_device_map_; + + AnnotationMap(const AnnotationMap&) = delete; + void operator=(const AnnotationMap&) = delete; +}; + +class CuptiTraceCollector { + public: + explicit CuptiTraceCollector(const CuptiTracerCollectorOptions& options) + : options_(options), + annotation_map_(options.max_annotation_strings, options.num_gpus) {} + virtual ~CuptiTraceCollector() {} + + // Producer side functions (i.e. called by CuptiTracer). + virtual void AddEvent(CuptiTracerEvent&& event) = 0; + virtual void OnEventsDropped(const std::string& reason, + tsl::uint32 num_events) = 0; + virtual void Flush() = 0; + + // Consumer side functions (i.e. called by GPU tracer); + virtual bool Export(tensorflow::profiler::XSpace* space, + tsl::uint64 end_gpu_ns) { + return true; + } + virtual std::string ReportNumEventsIfDropped() { return ""; } + + AnnotationMap* annotation_map() { return &annotation_map_; } + + protected: + CuptiTracerCollectorOptions options_; + + private: + AnnotationMap annotation_map_; + + CuptiTraceCollector(const CuptiTraceCollector&) = delete; + void operator=(const CuptiTraceCollector&) = delete; +}; + +std::unique_ptr CreateCuptiCollector( + const CuptiTracerCollectorOptions& options, + const tsl::uint64 start_walltime_ns, const tsl::uint64 start_gputime_ns); + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_CUPTI_COLLECTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_error_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_error_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..9ee29433b6a7db07bb5d6dda5e7a91ac6059ccf5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_error_manager.h @@ -0,0 +1,278 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_ERROR_MANAGER_H_ +#define XLA_BACKENDS_PROFILER_GPU_CUPTI_ERROR_MANAGER_H_ + +#include +#include + +#include +#include +#include +#include +#include + +#include "xla/backends/profiler/gpu/cupti_interface.h" +#include "tsl/platform/mutex.h" +#include "tsl/platform/thread_annotations.h" + +namespace xla { +namespace profiler { + +class CuptiErrorManager : public xla::profiler::CuptiInterface { + public: + explicit CuptiErrorManager(std::unique_ptr interface); + + // Returns whether CUPTI is disabled. + bool Disabled() const override { return disabled_.load(); } + + // CUPTI activity API: all thread-safe + // Disables activity monitoring. + CUptiResult ActivityDisable(CUpti_ActivityKind kind) override; + + // Enables activity monitoring. If this is successfully executed, we add + // ActivityDisable to the undo log. + CUptiResult ActivityEnable(CUpti_ActivityKind kind) override; + + // Flushes all outstanding activities. + CUptiResult ActivityFlushAll(uint32_t flag) override; + + // Gets a next activity record from a pool of already collected activity + // records. + CUptiResult ActivityGetNextRecord(uint8_t* buffer, + size_t valid_buffer_size_bytes, + CUpti_Activity** record) override; + + // Reports the number of dropped activity records. + CUptiResult ActivityGetNumDroppedRecords(CUcontext context, + uint32_t stream_id, + size_t* dropped) override; + + CUptiResult ActivityConfigureUnifiedMemoryCounter( + CUpti_ActivityUnifiedMemoryCounterConfig* config, + uint32_t count) override; + + // Registers callback functions handling activity. + CUptiResult ActivityRegisterCallbacks( + CUpti_BuffersCallbackRequestFunc func_buffer_requested, + CUpti_BuffersCallbackCompleteFunc func_buffer_completed) override; + + // Returns device ID for a given context. + CUptiResult GetDeviceId(CUcontext context, uint32_t* device_id) override; + + // Returns CUPTI timestamp. + CUptiResult GetTimestamp(uint64_t* timestamp) override; + + // Explicitly destroys and cleans up all resources associated with CUPTI in + // the current process. + CUptiResult Finalize() override; + + // CUPTI callback API + // Enables or disables callback. If we successfully enables callback, we add + // EnableCallback to disable callback to the undo log. + CUptiResult EnableCallback(uint32_t enable, CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain, + CUpti_CallbackId callback_id) override; + + // Enables or disables callback domain. If we successfully enables a domain, + // we add EnableDomain to disable the domain to the undo log. + CUptiResult EnableDomain(uint32_t enable, CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain) override; + + // Subscribes callbacks. If we successfully subscribes the callback, we add + // Unsubscribe to the undo log. + CUptiResult Subscribe(CUpti_SubscriberHandle* subscriber, + CUpti_CallbackFunc callback, void* userdata) override; + + // Unsubscribes callbacks. + CUptiResult Unsubscribe(CUpti_SubscriberHandle subscriber) override; + + // CUPTI event API + // Returns a list of event domains. + CUptiResult DeviceEnumEventDomains( + CUdevice device, size_t* array_size_bytes, + CUpti_EventDomainID* domain_array) override; + + // Returns domain attributes. + CUptiResult DeviceGetEventDomainAttribute(CUdevice device, + CUpti_EventDomainID event_domain, + CUpti_EventDomainAttribute attrib, + size_t* value_size, + void* value) override; + + // Disables kernel replay mode. + CUptiResult DisableKernelReplayMode(CUcontext context) override; + + // Enables kernel replay mode. If we successfully enable kernel replay mode, + // we add DisableKernelReplayMode to the undo log. + CUptiResult EnableKernelReplayMode(CUcontext context) override; + + // Returns the number of event domains. + CUptiResult DeviceGetNumEventDomains(CUdevice device, + uint32_t* num_domains) override; + + // Returns a list of events. + CUptiResult EventDomainEnumEvents(CUpti_EventDomainID event_domain, + size_t* array_size_bytes, + CUpti_EventID* event_array) override; + + // Returns the number of events. + CUptiResult EventDomainGetNumEvents(CUpti_EventDomainID event_domain, + uint32_t* num_events) override; + + // Returns an event attribute. + CUptiResult EventGetAttribute(CUpti_EventID event, + CUpti_EventAttribute attrib, size_t* value_size, + void* value) override; + + // Convverts event ID from event name. + CUptiResult EventGetIdFromName(CUdevice device, const char* event_name, + CUpti_EventID* event) override; + + // Disables event group. + CUptiResult EventGroupDisable(CUpti_EventGroup event_group) override; + + // Enables event group. If we successfully enable an event group, we add + // EventGroupDisable to the undo log. + CUptiResult EventGroupEnable(CUpti_EventGroup event_group) override; + + // Returns an event group attribute. + CUptiResult EventGroupGetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t* value_size, void* value) override; + + // Returns a performance counter value. + CUptiResult EventGroupReadEvent(CUpti_EventGroup event_group, + CUpti_ReadEventFlags flags, + CUpti_EventID event, + size_t* event_value_buffer_size_bytes, + uint64_t* event_value_buffer) override; + + // Returns an event group set attribute. + CUptiResult EventGroupSetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t value_size, void* value) override; + + // Creates an event group set. If we successfully creates an event group set, + // we add EventGroupSetsDestroy to the undo log. + CUptiResult EventGroupSetsCreate( + CUcontext context, size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + CUpti_EventGroupSets** event_group_passes) override; + + // Destroys an event group set. + CUptiResult EventGroupSetsDestroy( + CUpti_EventGroupSets* event_group_sets) override; + + // CUPTI metric API: all thread-safe + // Enumerates metrics. + CUptiResult DeviceEnumMetrics(CUdevice device, size_t* arraySizeBytes, + CUpti_MetricID* metricArray) override; + + // Returns the number of metrics. + CUptiResult DeviceGetNumMetrics(CUdevice device, + uint32_t* num_metrics) override; + + // Converts a metric ID to a metric name. + CUptiResult MetricGetIdFromName(CUdevice device, const char* metric_name, + CUpti_MetricID* metric) override; + + // Returns the number of events required to calculate a particular metric. + CUptiResult MetricGetNumEvents(CUpti_MetricID metric, + uint32_t* num_events) override; + + // Returns a list of events required to calculate a particular metric. + CUptiResult MetricEnumEvents(CUpti_MetricID metric, + size_t* event_id_array_size_bytes, + CUpti_EventID* event_id_array) override; + + // Returns a metric attribute. + CUptiResult MetricGetAttribute(CUpti_MetricID metric, + CUpti_MetricAttribute attrib, + size_t* value_size, void* value) override; + + // Returns a metric value. + CUptiResult MetricGetValue(CUdevice device, CUpti_MetricID metric, + size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + size_t event_value_array_size_bytes, + uint64_t* event_value_array, + uint64_t time_duration, + CUpti_MetricValue* metric_value) override; + + CUptiResult GetResultString(CUptiResult result, const char** str) override; + + CUptiResult GetContextId(CUcontext context, uint32_t* context_id) override; + + CUptiResult GetStreamIdEx(CUcontext context, CUstream stream, + uint8_t per_thread_stream, + uint32_t* stream_id) override; + + // Clears Undo stack. We are maintaining undo stack for each profiling phase. + // Once the profiling is done, we need to clear the undo stack. + void CleanUp() override; + + private: + typedef std::function UndoFunction; + + // Register undo function. + void RegisterUndoFunction(const UndoFunction& func); + + // Resets profiling status by calling some undo functions registered, + // and then disables profiling. + void UndoAndDisable(); + + // Returns a descriptive string for a CUptiResult. + std::string ResultString(CUptiResult result) const; + + // Contains a pointer to a cupti interface instance. Normally, this will point + // to a real CUPTI interface that interacts with underlying hardware, but for + // testing, we often replace this with a CUPTI mock object to mock hardware + // behavior. This will be set when CuptiBase singleton was created and an + // object that this variable points to will die when CuptiBase singleton dies, + // i.e., at the end of program execution. + std::unique_ptr interface_; + + // A vector of functions that needs to be called by Undo upon an error + // detected. This vector is managed like a statck through push_back and + // pop_back. Whenever an API function is successfully executed, its + // corresponding undo function will be pushed into this stack and Undo will + // pop and execute the unroll function upon detecting an error. + std::vector undo_stack_ TF_GUARDED_BY(undo_stack_mu_); + + // A mutex to guarantee atomicity for undo_stack_. Given that threads that + // can update undo_stack_ are a profiling control thread such as a webserver + // thread or a thread that executes a kernel during performance counter + // profiling, which is already serialized, the contention for this lock will + // be extremely low. In other words, it will be contended only when the + // profiling is being enabled or disabled, and we will have at most two + // threads that will contend for this mutex. + tsl::mutex undo_stack_mu_; + + // Once an error is detected, we will ignore any CUPTI API call. + std::atomic disabled_; + + // Prevent recursive undo if an UndoFunction fails. + bool undo_disabled_; + + CuptiErrorManager(const CuptiErrorManager&) = delete; + void operator=(const CuptiErrorManager&) = delete; +}; + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_CUPTI_ERROR_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..631780e1792de70fdce7c0e9bda575bd70542f3e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_interface.h @@ -0,0 +1,205 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_INTERFACE_H_ +#define XLA_BACKENDS_PROFILER_GPU_CUPTI_INTERFACE_H_ + +#include +#include + +#include "third_party/gpus/cuda/extras/CUPTI/include/cupti.h" +#include "third_party/gpus/cuda/include/cuda.h" +#include "tsl/platform/macros.h" +#include "tsl/platform/types.h" + +namespace xla { +namespace profiler { + +// Provides a wrapper interface to every single CUPTI API function. This class +// is needed to create an easy mock object for CUPTI API calls. All member +// functions are defined in the following order: activity related APIs, callback +// related APIs, Event APIs, and metric APIs. Within each category, we follow +// the order in the original CUPTI documentation. +class CuptiInterface { + public: + CuptiInterface() {} + + virtual ~CuptiInterface() {} + + // CUPTI activity API + virtual CUptiResult ActivityDisable(CUpti_ActivityKind kind) = 0; + + virtual CUptiResult ActivityEnable(CUpti_ActivityKind kind) = 0; + + virtual CUptiResult ActivityFlushAll(uint32_t flag) = 0; + + virtual CUptiResult ActivityGetNextRecord(uint8_t* buffer, + size_t valid_buffer_size_bytes, + CUpti_Activity** record) = 0; + + virtual CUptiResult ActivityGetNumDroppedRecords(CUcontext context, + uint32_t stream_id, + size_t* dropped) = 0; + + virtual CUptiResult ActivityConfigureUnifiedMemoryCounter( + CUpti_ActivityUnifiedMemoryCounterConfig* config, uint32_t count) = 0; + + virtual CUptiResult ActivityRegisterCallbacks( + CUpti_BuffersCallbackRequestFunc func_buffer_requested, + CUpti_BuffersCallbackCompleteFunc func_buffer_completed) = 0; + + virtual CUptiResult GetDeviceId(CUcontext context, tsl::uint32* deviceId) = 0; + + virtual CUptiResult GetTimestamp(uint64_t* timestamp) = 0; + + virtual CUptiResult Finalize() = 0; + + // CUPTI callback API + virtual CUptiResult EnableCallback(uint32_t enable, + CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain, + CUpti_CallbackId cbid) = 0; + + virtual CUptiResult EnableDomain(uint32_t enable, + CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain) = 0; + + virtual CUptiResult Subscribe(CUpti_SubscriberHandle* subscriber, + CUpti_CallbackFunc callback, + void* userdata) = 0; + + virtual CUptiResult Unsubscribe(CUpti_SubscriberHandle subscriber) = 0; + + // CUPTI event API + virtual CUptiResult DeviceEnumEventDomains( + CUdevice device, size_t* array_size_bytes, + CUpti_EventDomainID* domain_array) = 0; + + virtual CUptiResult DeviceGetEventDomainAttribute( + CUdevice device, CUpti_EventDomainID event_domain, + CUpti_EventDomainAttribute attrib, size_t* value_size, void* value) = 0; + + virtual CUptiResult DisableKernelReplayMode(CUcontext context) = 0; + + virtual CUptiResult EnableKernelReplayMode(CUcontext context) = 0; + + virtual CUptiResult DeviceGetNumEventDomains(CUdevice device, + uint32_t* num_domains) = 0; + + virtual CUptiResult EventDomainEnumEvents(CUpti_EventDomainID event_domain, + size_t* array_size_bytes, + CUpti_EventID* event_array) = 0; + + virtual CUptiResult EventDomainGetNumEvents(CUpti_EventDomainID event_domain, + uint32_t* num_events) = 0; + + virtual CUptiResult EventGetAttribute(CUpti_EventID event, + CUpti_EventAttribute attrib, + size_t* value_size, void* value) = 0; + + virtual CUptiResult EventGetIdFromName(CUdevice device, + const char* event_name, + CUpti_EventID* event) = 0; + + virtual CUptiResult EventGroupDisable(CUpti_EventGroup event_group) = 0; + + virtual CUptiResult EventGroupEnable(CUpti_EventGroup event_group) = 0; + + virtual CUptiResult EventGroupGetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t* value_size, + void* value) = 0; + + virtual CUptiResult EventGroupReadEvent(CUpti_EventGroup event_group, + CUpti_ReadEventFlags flags, + CUpti_EventID event, + size_t* event_value_buffer_size_bytes, + uint64_t* eventValueBuffer) = 0; + + virtual CUptiResult EventGroupSetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t value_size, + void* value) = 0; + + virtual CUptiResult EventGroupSetsCreate( + CUcontext context, size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + CUpti_EventGroupSets** event_group_passes) = 0; + + virtual CUptiResult EventGroupSetsDestroy( + CUpti_EventGroupSets* event_group_sets) = 0; + + // CUPTI metric API + virtual CUptiResult DeviceEnumMetrics(CUdevice device, size_t* arraySizeBytes, + CUpti_MetricID* metricArray) = 0; + + virtual CUptiResult DeviceGetNumMetrics(CUdevice device, + uint32_t* num_metrics) = 0; + + virtual CUptiResult MetricGetIdFromName(CUdevice device, + const char* metric_name, + CUpti_MetricID* metric) = 0; + + virtual CUptiResult MetricGetNumEvents(CUpti_MetricID metric, + uint32_t* num_events) = 0; + + virtual CUptiResult MetricEnumEvents(CUpti_MetricID metric, + size_t* event_id_array_size_bytes, + CUpti_EventID* event_id_array) = 0; + + virtual CUptiResult MetricGetAttribute(CUpti_MetricID metric, + CUpti_MetricAttribute attrib, + size_t* value_size, void* value) = 0; + + virtual CUptiResult MetricGetValue(CUdevice device, CUpti_MetricID metric, + size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + size_t event_value_array_size_bytes, + uint64_t* event_value_array, + uint64_t time_duration, + CUpti_MetricValue* metric_value) = 0; + + virtual CUptiResult GetResultString(CUptiResult result, const char** str) = 0; + + virtual CUptiResult GetContextId(CUcontext context, uint32_t* context_id) = 0; + + virtual CUptiResult GetStreamIdEx(CUcontext context, CUstream stream, + uint8_t per_thread_stream, + uint32_t* stream_id) = 0; + + // Interface maintenance functions. Not directly related to CUPTI, but + // required for implementing an error resilient layer over CUPTI API. + + // Performance any clean up work that is required each time profile session + // is done. Therefore this can be called multiple times during process life + // time. + virtual void CleanUp() = 0; + + // Whether CUPTI API is currently disabled due to unrecoverable errors. + // All subsequent calls will fail immediately without forwarding calls to + // CUPTI library. + virtual bool Disabled() const = 0; + + private: + CuptiInterface(const CuptiInterface&) = delete; + void operator=(const CuptiInterface&) = delete; +}; + +CuptiInterface* GetCuptiInterface(); + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_CUPTI_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_tracer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_tracer.h new file mode 100644 index 0000000000000000000000000000000000000000..a7ed77160d0e817f07192bdae940b8eee1656540 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_tracer.h @@ -0,0 +1,156 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_TRACER_H_ +#define XLA_BACKENDS_PROFILER_GPU_CUPTI_TRACER_H_ + +#include "absl/types/optional.h" +#include "third_party/gpus/cuda/extras/CUPTI/include/cupti.h" +#include "third_party/gpus/cuda/include/nvtx3/nvToolsExt.h" +#include "xla/backends/profiler/gpu/cupti_collector.h" +#include "xla/backends/profiler/gpu/cupti_interface.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/types.h" +#include "tsl/profiler/utils/buffer_pool.h" + +namespace xla { +namespace profiler { + +struct CuptiTracerOptions { + bool enable_activity_api = true; + + // Use cuda events to enclose the kernel/memcpy to measure device activity. + // enable_event_based_activity, if true, will override the enable_activity_api + // setting. + bool enable_event_based_activity = false; + + bool required_callback_api_events = true; + // The callback ids that will be enabled and monitored, if empty, all + // Callback ids to be enabled using Callback API. + // We only care CUPTI_CB_DOMAIN_DRIVER_API domain for now. It is kind of + // redundant to have both CUPTI_CB_DOMAIN_DRIVER_API and + // CUPTI_CB_DOMAIN_RUNTIME_API. + std::vector cbids_selected; + // Activity kinds to be collected using Activity API. If empty, the Activity + // API is disable. + std::vector activities_selected; + // Whether to call cuptiFinalize. + bool cupti_finalize = false; + // Whether to call cuCtxSynchronize for each device before Stop(). + bool sync_devices_before_stop = false; + // Whether to enable NVTX tracking, we need this for TensorRT tracking. + bool enable_nvtx_tracking = false; +}; + +class CuptiDriverApiHook { + public: + virtual ~CuptiDriverApiHook() {} + + virtual tsl::Status OnDriverApiEnter( + int device_id, CUpti_CallbackDomain domain, CUpti_CallbackId cbid, + const CUpti_CallbackData* callback_info) = 0; + virtual tsl::Status OnDriverApiExit( + int device_id, CUpti_CallbackDomain domain, CUpti_CallbackId cbid, + const CUpti_CallbackData* callback_info) = 0; + virtual tsl::Status SyncAndFlush() = 0; + + protected: + static tsl::Status AddDriverApiCallbackEvent( + CuptiTraceCollector* collector, CuptiInterface* cupti_interface, + int device_id, tsl::uint64 start_tsc, tsl::uint64 end_tsc, + CUpti_CallbackDomain domain, CUpti_CallbackId cbid, + const CUpti_CallbackData* callback_info); +}; + +// The class use to enable cupti callback/activity API and forward the collected +// trace events to CuptiTraceCollector. There should be only one CuptiTracer +// per process. +class CuptiTracer { + public: + // Not copyable or movable + CuptiTracer(const CuptiTracer&) = delete; + CuptiTracer& operator=(const CuptiTracer&) = delete; + + // Returns a pointer to singleton CuptiTracer. + static CuptiTracer* GetCuptiTracerSingleton(); + + // Only one profile session can be live in the same time. + bool IsAvailable() const; + bool NeedRootAccess() const { return need_root_access_; } + + void Enable(const CuptiTracerOptions& option, CuptiTraceCollector* collector); + void Disable(); + + tsl::Status HandleCallback(CUpti_CallbackDomain domain, CUpti_CallbackId cbid, + const CUpti_CallbackData* callback_info); + + // Returns a buffer and its size for CUPTI to store activities. This buffer + // will be reclaimed when CUPTI makes a callback to ProcessActivityBuffer. + void RequestActivityBuffer(uint8_t** buffer, size_t* size); + + // Parses CUPTI activity events from activity buffer, and emits events for + // CuptiTraceCollector. This function is public because called from registered + // callback. + tsl::Status ProcessActivityBuffer(CUcontext context, uint32_t stream_id, + uint8_t* buffer, size_t size); + + static uint64_t GetTimestamp(); + static int NumGpus(); + // Returns the error (if any) when using libcupti. + static std::string ErrorIfAny(); + + protected: + // protected constructor for injecting mock cupti interface for testing. + explicit CuptiTracer(CuptiInterface* cupti_interface); + + private: + // Buffer size and alignment, 32K and 8 as in CUPTI samples. + static constexpr size_t kBufferSizeInBytes = 32 * 1024; + + tsl::Status EnableApiTracing(); + tsl::Status EnableActivityTracing(); + tsl::Status DisableApiTracing(); + tsl::Status DisableActivityTracing(); + tsl::Status Finalize(); + void ConfigureActivityUnifiedMemoryCounter(bool enable); + tsl::Status HandleNVTXCallback(CUpti_CallbackId cbid, + const CUpti_CallbackData* cbdata); + + int num_gpus_; + std::optional option_; + CuptiInterface* cupti_interface_ = nullptr; + CuptiTraceCollector* collector_ = nullptr; + + // CUPTI 10.1 and higher need root access to profile. + bool need_root_access_ = false; + + bool api_tracing_enabled_ = false; + // Cupti handle for driver or runtime API callbacks. Cupti permits a single + // subscriber to be active at any time and can be used to trace Cuda runtime + // as and driver calls for all contexts and devices. + CUpti_SubscriberHandle subscriber_; // valid when api_tracing_enabled_. + + bool activity_tracing_enabled_ = false; + + std::unique_ptr cupti_driver_api_hook_; + + tsl::profiler::BufferPool buffer_pool_; +}; + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_CUPTI_TRACER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_wrapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..658148106d272f9190a476fe27353330b3a84c1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/cupti_wrapper.h @@ -0,0 +1,186 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_CUPTI_WRAPPER_H_ +#define XLA_BACKENDS_PROFILER_GPU_CUPTI_WRAPPER_H_ + +#include +#include + +#include "third_party/gpus/cuda/extras/CUPTI/include/cupti.h" +#include "third_party/gpus/cuda/include/cuda.h" +#include "xla/backends/profiler/gpu/cupti_interface.h" + +namespace xla { +namespace profiler { + +class CuptiWrapper : public xla::profiler::CuptiInterface { + public: + CuptiWrapper() {} + + ~CuptiWrapper() override {} + + // CUPTI activity API + CUptiResult ActivityDisable(CUpti_ActivityKind kind) override; + + CUptiResult ActivityEnable(CUpti_ActivityKind kind) override; + + CUptiResult ActivityFlushAll(uint32_t flag) override; + + CUptiResult ActivityGetNextRecord(uint8_t* buffer, + size_t valid_buffer_size_bytes, + CUpti_Activity** record) override; + + CUptiResult ActivityGetNumDroppedRecords(CUcontext context, + uint32_t stream_id, + size_t* dropped) override; + + CUptiResult ActivityConfigureUnifiedMemoryCounter( + CUpti_ActivityUnifiedMemoryCounterConfig* config, + uint32_t count) override; + + CUptiResult ActivityRegisterCallbacks( + CUpti_BuffersCallbackRequestFunc func_buffer_requested, + CUpti_BuffersCallbackCompleteFunc func_buffer_completed) override; + + CUptiResult GetDeviceId(CUcontext context, tsl::uint32* deviceId) override; + + CUptiResult GetTimestamp(uint64_t* timestamp) override; + + // cuptiFinalize is only defined in CUDA8 and above. + // To enable it in CUDA8, the environment variable CUPTI_ENABLE_FINALIZE must + // be set to 1. + CUptiResult Finalize() override; + + // CUPTI callback API + CUptiResult EnableCallback(uint32_t enable, CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain, + CUpti_CallbackId cbid) override; + + CUptiResult EnableDomain(uint32_t enable, CUpti_SubscriberHandle subscriber, + CUpti_CallbackDomain domain) override; + + CUptiResult Subscribe(CUpti_SubscriberHandle* subscriber, + CUpti_CallbackFunc callback, void* userdata) override; + + CUptiResult Unsubscribe(CUpti_SubscriberHandle subscriber) override; + + // CUPTI event API + CUptiResult DeviceEnumEventDomains( + CUdevice device, size_t* array_size_bytes, + CUpti_EventDomainID* domain_array) override; + + CUptiResult DeviceGetEventDomainAttribute(CUdevice device, + CUpti_EventDomainID event_domain, + CUpti_EventDomainAttribute attrib, + size_t* value_size, + void* value) override; + + CUptiResult DisableKernelReplayMode(CUcontext context) override; + + CUptiResult EnableKernelReplayMode(CUcontext context) override; + + CUptiResult DeviceGetNumEventDomains(CUdevice device, + uint32_t* num_domains) override; + + CUptiResult EventDomainEnumEvents(CUpti_EventDomainID event_domain, + size_t* array_size_bytes, + CUpti_EventID* event_array) override; + + CUptiResult EventDomainGetNumEvents(CUpti_EventDomainID event_domain, + uint32_t* num_events) override; + + CUptiResult EventGetAttribute(CUpti_EventID event, + CUpti_EventAttribute attrib, size_t* value_size, + void* value) override; + + CUptiResult EventGetIdFromName(CUdevice device, const char* event_name, + CUpti_EventID* event) override; + + CUptiResult EventGroupDisable(CUpti_EventGroup event_group) override; + + CUptiResult EventGroupEnable(CUpti_EventGroup event_group) override; + + CUptiResult EventGroupGetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t* value_size, void* value) override; + + CUptiResult EventGroupReadEvent(CUpti_EventGroup event_group, + CUpti_ReadEventFlags flags, + CUpti_EventID event, + size_t* event_value_buffer_size_bytes, + uint64_t* event_value_buffer) override; + + CUptiResult EventGroupSetAttribute(CUpti_EventGroup event_group, + CUpti_EventGroupAttribute attrib, + size_t value_size, void* value) override; + + CUptiResult EventGroupSetsCreate( + CUcontext context, size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + CUpti_EventGroupSets** event_group_passes) override; + + CUptiResult EventGroupSetsDestroy( + CUpti_EventGroupSets* event_group_sets) override; + + // CUPTI metric API + CUptiResult DeviceEnumMetrics(CUdevice device, size_t* arraySizeBytes, + CUpti_MetricID* metricArray) override; + + CUptiResult DeviceGetNumMetrics(CUdevice device, + uint32_t* num_metrics) override; + + CUptiResult MetricGetIdFromName(CUdevice device, const char* metric_name, + CUpti_MetricID* metric) override; + + CUptiResult MetricGetNumEvents(CUpti_MetricID metric, + uint32_t* num_events) override; + + CUptiResult MetricEnumEvents(CUpti_MetricID metric, + size_t* event_id_array_size_bytes, + CUpti_EventID* event_id_array) override; + + CUptiResult MetricGetAttribute(CUpti_MetricID metric, + CUpti_MetricAttribute attrib, + size_t* value_size, void* value) override; + + CUptiResult MetricGetValue(CUdevice device, CUpti_MetricID metric, + size_t event_id_array_size_bytes, + CUpti_EventID* event_id_array, + size_t event_value_array_size_bytes, + uint64_t* event_value_array, + uint64_t time_duration, + CUpti_MetricValue* metric_value) override; + + CUptiResult GetResultString(CUptiResult result, const char** str) override; + + CUptiResult GetContextId(CUcontext context, uint32_t* context_id) override; + + CUptiResult GetStreamIdEx(CUcontext context, CUstream stream, + uint8_t per_thread_stream, + uint32_t* stream_id) override; + + void CleanUp() override {} + bool Disabled() const override { return false; } + + private: + CuptiWrapper(const CuptiWrapper&) = delete; + void operator=(const CuptiWrapper&) = delete; +}; + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_CUPTI_WRAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/nvtx_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/nvtx_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..58be1980e2a293bb25c6337138f54e9832f31411 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/backends/profiler/gpu/nvtx_utils.h @@ -0,0 +1,59 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_BACKENDS_PROFILER_GPU_NVTX_UTILS_H_ +#define XLA_BACKENDS_PROFILER_GPU_NVTX_UTILS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "tsl/platform/macros.h" + +namespace xla { +namespace profiler { + +/*** + * We have no intention to use NVTX in tensorflow right now, we use this class + * to track NVTX instrumentation inside NVIDIA libraries (such as TensorRT). + * This bears a lot of resemblance to ScopedAnnotation for now. In the future, + * we will use TraceMe to keep track trace context within a thread. + */ +class NVTXRangeTracker { + public: + static void EnterRange(const std::string& range) { + auto& range_stack = GetRangeStack(); + range_stack.push(range); + } + static void ExitRange() { + auto& range_stack = GetRangeStack(); + if (!range_stack.empty()) range_stack.pop(); + } + static const absl::string_view CurrentRange() { + auto& range_stack = GetRangeStack(); + if (!range_stack.empty()) return range_stack.top(); + return ""; + } + + private: + static std::stack& GetRangeStack(); + + NVTXRangeTracker(const NVTXRangeTracker&) = delete; + void operator=(const NVTXRangeTracker&) = delete; +}; + +} // namespace profiler +} // namespace xla + +#endif // XLA_BACKENDS_PROFILER_GPU_NVTX_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/c/c_api_decl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/c/c_api_decl.h new file mode 100644 index 0000000000000000000000000000000000000000..a7c0c3b61fd5069c9f85ccc7617d41bb6aa12ef5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/c/c_api_decl.h @@ -0,0 +1,29 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_C_C_API_DECL_H_ +#define XLA_C_C_API_DECL_H_ + +extern "C" { + +// XLA Layout preferences. +typedef enum { + XLA_LayoutPreference_kNoPreference, + XLA_LayoutPreference_kTpuPreferCompactChunkPaddedLayout, + XLA_LayoutPreference_kTpuPreferLinearLayout, +} XLA_LayoutPreference; +} + +#endif // XLA_C_C_API_DECL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client.h new file mode 100644 index 0000000000000000000000000000000000000000..bdd7cfaaa93d3a185c8f209014b2e0b77bde4c7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client.h @@ -0,0 +1,247 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_CLIENT_H_ +#define XLA_CLIENT_CLIENT_H_ + +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/client/global_data.h" +#include "xla/client/xla_computation.h" +#include "xla/literal.h" +#include "xla/service/hlo.pb.h" +#include "xla/service_interface.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla.pb.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// XLA service's client object -- wraps the service with convenience and +// lifetime-oriented methods. +class Client { + public: + explicit Client(ServiceInterface* stub); + virtual ~Client(); + + // Compile the computation with the given argument shapes and returns the + // handle to the compiled executable. The compiled executable is cached on the + // service, and the returned handle can be used for execution without + // re-compile. + // * The shape and layout of the arguments being executed with will affect how + // the computation is compiled. If argument_shapes is empty, the parameters' + // shape and layout will be used in the compilation. + // * If execution_options is not nullptr, these options are passed to the + // service to affect how it compiles our computation. (The pointer does not + // need to live beyond this call.) + // * If execution_options.device_handles should be empty. If you need + // non-empty device handles, call 'Execute' instead. + // + // TODO(b/122731460): This call caches the resulting Executable in the Service + // *forever*. If you're only going to run the computation once, you may want + // to call the Execute(const XlaComputation&) overload. If you're going to + // run the computation more than once but you want control over when the + // Executable is unloaded, use the LocalClient API. + StatusOr Compile( + const XlaComputation& computation, + absl::Span argument_shapes, + const ExecutionOptions* execution_options = nullptr); + + // Executes the compiled executable for the given handle with the given + // arguments and returns the global data that was produced from the execution. + // * If execution_profile is not nullptr then the pointed-to ExecutionProfile + // will be filled with profile data from the execution. + StatusOr> Execute( + const ExecutionHandle& handle, absl::Span arguments, + ExecutionProfile* execution_profile = nullptr); + + // Executes the computation with the given arguments and returns the global + // data that was produced from the execution. + // * If execution_options is not nullptr, these options are passed to the + // service to affect how it compiles our computation. (The pointer does not + // need to live beyond this call.) + // * If execution_options.device_handles is not empty, the computation is + // executed on the devices associated with the handles by partitioning the + // computation based on the attached sharding attributes. Otherwise, a + // device is chosen by the service. + // * If execution_profile is not nullptr then the pointed-to ExecutionProfile + // will be filled with profile data from the execution. + // + // TODO(b/122731460): The given computation is compiled and then thrown away + // immediately after it's run. If you want control over how long the + // resulting Executable lives, use the LocalClient API. + StatusOr> Execute( + const XlaComputation& computation, + absl::Span arguments, + const ExecutionOptions* execution_options = nullptr, + ExecutionProfile* execution_profile = nullptr); + + // A struct to represent a computation instance to be executed. + // * If execution_options.device_handles is not empty, the computation is + // executed on the devices associated with the handles by partitioning the + // computation based on the attached sharding attributes. Otherwise, a + // device is chosen by the service. + struct XlaComputationInstance { + const XlaComputation& computation; + std::vector arguments; + ExecutionOptions execution_options; + ExecutionProfile* execution_profile; + + XlaComputationInstance(const XlaComputation& computation, + std::vector arguments, + ExecutionOptions execution_options, + ExecutionProfile* execution_profile) + : computation(computation), + arguments(std::move(arguments)), + execution_options(execution_options), + execution_profile(execution_profile) {} + }; + + // Executes a list XlaComputationInstances and returns global data produced + // from each computation. + // + StatusOr>> ExecuteParallel( + absl::Span computations); + + // Requests device_count device handles available on the target. The returned + // device handles are used to specify the devices to execute the computations + // (see ExecuteParallel) or to transfer data (see TransferToServer or + // TransferToInfeed). + StatusOr> GetDeviceHandles(int64_t device_count); + + // Transfer the global data provided to this client process, which is + // returned in the provided literal. Use sparingly to avoid transfer + // overheads. + // + // If shape_with_layout is not nullptr, it points to a shape whose layout will + // be the layout of the returned literal. + StatusOr Transfer(const GlobalData& data, + const Shape* shape_with_layout = nullptr); + + // Transfer the given literal to the server. This allocates memory on the + // device and copies the literal's contents over. Returns a global data handle + // that can be used to refer to this value from the client. + // + // If device_handle is not nullptr, data is transferred to the associated + // device (and its replicas if replication is enabled). Otherwise, data is + // transferred to the default device (and its replicas). + StatusOr> TransferToServer( + const LiteralSlice& literal, const DeviceHandle* device_handle = nullptr); + + // Transfer the given literal to the Infeed interface of the device. + // + // device_handle and replica_id together specify a particular device; a device + // assigned for the given replica_id among the replicas that the given device + // handle belongs to. + Status TransferToInfeed(const LiteralSlice& literal, int64_t replica_id = 0, + const DeviceHandle* device_handle = nullptr); + + // Transfers from the Outfeed of the device. + // + // device_handle and replica_id together specify a particular device; a device + // assigned for the given replica_id among the replicas that the given device + // handle belongs to. + StatusOr TransferFromOutfeed( + const Shape* shape_with_layout, int64_t replica_id = 0, + const DeviceHandle* device_handle = nullptr); + + // Resets the device, clearing all existing state on the device. + Status ResetDevice(); + + // Executes the computation with the given arguments and transfers the result + // to the client as a literal. Parameters are defined the same as for + // Execute() and Transfer(). + StatusOr ExecuteAndTransfer( + const XlaComputation& computation, + absl::Span arguments, + const ExecutionOptions* execution_options = nullptr, + ExecutionProfile* execution_profile = nullptr); + + // Computes the value of the given computation using a non-optimized + // interpreter on the host. + // + // The computation must not depend on any parameters, or on stateful operators + // such as `RngNormal` or `Infeed`. + // + // This functionality can be useful when translating a computation into XLA + // where something that looked dynamic is required by XLA to be specified as a + // constant. E.g. the source computation (outside of XLA) may include a + // dynamic computation of the shape of something and ComputeConstant lets you + // determine what the value of that computation is in the case where the value + // can be determined at compile time. + // + // If output_layout is non-null, then the output of the computation will be + // stored using that layout. + StatusOr ComputeConstant( + const XlaComputation& computation, + const Layout* output_layout = nullptr) const; + + // Unregister the memory for the given GlobalData on the device. + Status Unregister(const GlobalData& data); + + // Returns a vector of global data handles that point to the tuple elements. + StatusOr>> DeconstructTuple( + const GlobalData& data); + + // Retrieves the statistics of the given computation. + StatusOr GetComputationStats( + const XlaComputation& computation, + const DebugOptions& debug_options) const; + + // Returns the Shape of the given array specified by 'data'. The shape + // includes the Layout of the array as it is stored on the service. + StatusOr GetShape(const GlobalData& data); + + // As above, but returns the shape of the provided computation (parameter + // types/names and return type). + StatusOr> GetComputationShape( + const XlaComputation& computation); + + // Creates a channel handle that can be used to transfer data between two + // computations on different devices via a pair of Send and Recv instructions. + StatusOr CreateChannelHandle(); + + // Create a channel for communicating with the host via a SendtoHost or + // RecvFromHost operation. + StatusOr CreateHostToDeviceChannelHandle(); + StatusOr CreateDeviceToHostChannelHandle(); + + StatusOr LoadSnapshot(const HloSnapshot& module); + + ServiceInterface* stub() { return stub_; } + + private: + // Returns the execution statistics (e.g., gflop/s) as a string from the + // ExecutionProfile returned from an execution of the computation. + StatusOr ExecutionStatsAsString( + const XlaComputation& computation, const ExecutionProfile& profile); + + StatusOr CreateChannelHandleByType( + ChannelHandle::ChannelType type); + + ServiceInterface* stub_; // Stub that this client is connected on. + + Client(const Client&) = delete; + Client& operator=(const Client&) = delete; +}; + +} // namespace xla + +#endif // XLA_CLIENT_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client_library.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client_library.h new file mode 100644 index 0000000000000000000000000000000000000000..f98a01aa9697ad0616af9885c5c432633fe6b08c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/client_library.h @@ -0,0 +1,146 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The "client library" instantiates a local (in-process) XLA service for +// use by this process, and connects to it with a singleton XLA local +// client. ClientLibrary::GetOrCreateLocalClient will spawn a local service, +// and return a client that's connected to it and ready to run XLA +// computations. +#ifndef XLA_CLIENT_CLIENT_LIBRARY_H_ +#define XLA_CLIENT_CLIENT_LIBRARY_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/client/compile_only_client.h" +#include "xla/client/local_client.h" +#include "xla/service/compile_only_service.h" +#include "xla/service/local_service.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { + +// Options to configure the local client when it is created. +class LocalClientOptions { + public: + LocalClientOptions( + se::Platform* platform = nullptr, int number_of_replicas = 1, + int intra_op_parallelism_threads = -1, + const std::optional>& allowed_devices = std::nullopt); + + // Set the platform backing the service, or nullptr for the default platform. + LocalClientOptions& set_platform(se::Platform* platform); + se::Platform* platform() const; + + // Set the number of replicas to use when compiling replicated + // programs. + LocalClientOptions& set_number_of_replicas(int number_of_replicas); + int number_of_replicas() const; + + // Sets the thread pool size for parallel execution of an individual operator. + LocalClientOptions& set_intra_op_parallelism_threads(int num_threads); + int intra_op_parallelism_threads() const; + + // Sets the allowed_devices set for selectively constructing stream executors + // on the platform. + LocalClientOptions& set_allowed_devices( + const std::optional>& allowed_devices); + const std::optional>& allowed_devices() const; + + private: + se::Platform* platform_; + int number_of_replicas_; + int intra_op_parallelism_threads_; + std::optional> allowed_devices_; +}; + +class ClientLibrary { + public: + // Singleton constructor-or-accessor -- returns a client for the application + // to issue XLA commands on. Arguments: + // + // platform : The platform the underlying XLA service should target. If + // null then default platform is used. + // device_set: Set of device IDs for which the stream executor will be + // created, for the given platform. + static StatusOr GetOrCreateLocalClient( + se::Platform* platform = nullptr, + const std::optional>& device_set = std::nullopt); + static StatusOr GetOrCreateLocalClient( + const LocalClientOptions& options); + + // Convenience "or-die" wrapper around the above which returns the existing + // client library or creates one with default platform and allocator. + static LocalClient* LocalClientOrDie(); + + // Returns the service from the service thread. Only used in unit tests to + // access user computations from client. + static LocalService* GetXlaService(se::Platform* platform); + + // Singleton constructor-or-accessor for compile-only clients. Arguments: + // + // platform : The platform the underlying XLA service should target. If + // null then default platform is used. + static StatusOr GetOrCreateCompileOnlyClient( + se::Platform* platform = nullptr); + + // Clears the local instance and compile only instance caches. The client + // pointers returned by the previous GetOrCreateLocalClient() or + // GetOrCreateCompileOnlyClient() invocations are not valid anymore. + static void DestroyLocalInstances(); + + private: + // Returns the singleton instance of ClientLibrary. + static ClientLibrary& Singleton(); + + ClientLibrary(); + ~ClientLibrary(); + + struct LocalInstance { + // Service that is wrapped by the singleton client object. + std::unique_ptr service; + // Singleton client object. + std::unique_ptr client; + }; + + struct CompileOnlyInstance { + // Service that is wrapped by the singleton client object. + std::unique_ptr service; + // Singleton client object. + std::unique_ptr client; + }; + + absl::Mutex service_mutex_; // Guards the singleton creation state. + absl::flat_hash_map> + local_instances_ ABSL_GUARDED_BY(service_mutex_); + + absl::flat_hash_map> + compile_only_instances_ ABSL_GUARDED_BY(service_mutex_); + + ClientLibrary(const ClientLibrary&) = delete; + ClientLibrary& operator=(const ClientLibrary&) = delete; +}; + +} // namespace xla + +#endif // XLA_CLIENT_CLIENT_LIBRARY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/compile_only_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/compile_only_client.h new file mode 100644 index 0000000000000000000000000000000000000000..3b737fc26cf89d10b4cfa10f4ad39bce211765ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/compile_only_client.h @@ -0,0 +1,78 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_COMPILE_ONLY_CLIENT_H_ +#define XLA_CLIENT_COMPILE_ONLY_CLIENT_H_ + +#include +#include + +#include "xla/client/client.h" +#include "xla/client/xla_computation.h" +#include "xla/service/compile_only_service.h" +#include "xla/service/compiler.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// An XLA Client specialization for doing ahead-of-time compilation. This does +// not require (or attempt to instantiate) an execution-capable backend for the +// relevant platform. +class CompileOnlyClient : public Client { + public: + explicit CompileOnlyClient(CompileOnlyService* service) + : Client(service), compiler_service_(service) {} + + CompileOnlyClient(const CompileOnlyClient&) = delete; + void operator=(const CompileOnlyClient&) = delete; + + // A description of an xla computation to compile using CompileAheadOfTime. + struct AotXlaComputationInstance { + const XlaComputation* computation; + // Inform the compiler of the expected layout for arguments. + std::vector argument_layouts; + // Specifies the expected result layout. + const Shape* result_layout; + }; + + // Compiles a list of xla computations for ahead-of-time execution. + // This is intended for use in static compilation. The |options| + // parameter describes the target for which the compiler should emit + // code. |metadata|, if provided, is populated during compilation. + StatusOr>> + CompileAheadOfTime( + absl::Span computations, + const AotCompilationOptions& options, + std::unique_ptr* metadata = nullptr); + + // Create a Hlo module config for the given program shape and arguments. + // execution_options is optional; if not given a default is used. + StatusOr> CreateModuleConfig( + const ProgramShape& program_shape, + absl::Span argument_shapes, + const ExecutionOptions* execution_options); + + // Returns the size of a pointer in bytes for a given triple. + static int64_t PointerSizeForTriple(absl::string_view triple); + + private: + CompileOnlyService* compiler_service_; +}; + +} // namespace xla + +#endif // XLA_CLIENT_COMPILE_ONLY_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/executable_build_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/executable_build_options.h new file mode 100644 index 0000000000000000000000000000000000000000..bc0a039f565101bceef6bca25d48cf5c225d45bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/executable_build_options.h @@ -0,0 +1,255 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_EXECUTABLE_BUILD_OPTIONS_H_ +#define XLA_CLIENT_EXECUTABLE_BUILD_OPTIONS_H_ + +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/inlined_vector.h" +#include "xla/pjrt/compile_options.pb.h" +#include "xla/service/compilation_environments.h" +#include "xla/service/computation_placer.h" +#include "xla/shape.h" +#include "xla/xla.pb.h" +#include "tsl/platform/threadpool.h" + +namespace stream_executor { + +// Forward-declared to avoid StreamExecutor dependency. +class DeviceMemoryAllocator; + +} // namespace stream_executor + +namespace xla { +class HloModule; + +// Class containing options for building an LocalExecutable with +// LocalClient::Compile. +class ExecutableBuildOptions { + public: + // If set, this is the device to build the computation for. Valid + // device_ordinal values are: 0 to # of devices - 1. These values are + // identical to the device ordinal values used by StreamExecutor. The built + // executable will be executable on any device equivalent to the specified + // device as determined by Backend::devices_equivalent(). A value of -1 + // indicates this option has not been set. + ExecutableBuildOptions& set_device_ordinal(int device_ordinal); + int device_ordinal() const; + + // If set, this specifies the layout of the result of the computation. If not + // set, the service will chose the layout of the result. A Shape is used to + // store the layout to accommodate tuple result shapes. A value of nullptr + // indicates the option has not been set. + ExecutableBuildOptions& set_result_layout(const Shape& shape_with_layout); + const Shape* result_layout() const; + + // Expose access to the XLA compilation environments, which will be passed to + // the compilation process. `comp_envs()` must not be called if + // `has_comp_envs()` returns false. + bool has_comp_envs() const { return comp_envs_.has_value(); } + const CompilationEnvironments& comp_envs() const { return *comp_envs_; } + CompilationEnvironments* mutable_comp_envs(); + + // Expose access to the XLA debug options which will be passed to the + // compilation process. `debug_options()` must not be called if + // `has_debug_options()` returns false. + bool has_debug_options() const { return debug_options_.has_value(); } + const DebugOptions& debug_options() const { return *debug_options_; } + DebugOptions* mutable_debug_options(); + + // If set, this specifies an allocator that can be used to allocate temporary + // space on the device during compilation. For example, the compiler might + // want to run various algorithms on the device and pick the fastest one -- it + // might allocate buffers for use by these algorithms using this allocator. + // + // This does not need to be the same as the se::DeviceMemoryAllocator passed + // when running the executable. + ExecutableBuildOptions& set_device_allocator( + se::DeviceMemoryAllocator* allocator); + se::DeviceMemoryAllocator* device_allocator() const; + + // The number of replicas of this computation that are to be executed. + // Defaults to 1. + int num_replicas() const { return num_replicas_; } + ExecutableBuildOptions& set_num_replicas(int num_replicas); + + // The number of partitions in this computation. Defaults to 1. + int num_partitions() const { return num_partitions_; } + ExecutableBuildOptions& set_num_partitions(int num_partitions); + + // Indicates whether to use SPMD (true) or MPMD (false) partitioning when + // num_partitions > 1 and XLA is requested to partition the input program. + bool use_spmd_partitioning() const { return use_spmd_partitioning_; } + ExecutableBuildOptions& set_use_spmd_partitioning(bool use_spmd_partitioning); + + // Whether to automatically generate XLA shardings for SPMD partitioner. + bool use_auto_spmd_partitioning() const { + return use_auto_spmd_partitioning_; + } + ExecutableBuildOptions& set_use_auto_spmd_partitioning( + bool use_auto_spmd_partitioning); + + std::vector auto_spmd_partitioning_mesh_shape() const { + return auto_spmd_partitioning_mesh_shape_; + } + ExecutableBuildOptions& set_auto_spmd_partitioning_mesh_shape( + std::vector mesh_shape); + + std::vector auto_spmd_partitioning_mesh_ids() const { + return auto_spmd_partitioning_mesh_ids_; + } + ExecutableBuildOptions& set_auto_spmd_partitioning_mesh_ids( + std::vector mesh_ids); + + bool deduplicate_hlo() const { return deduplicate_hlo_; } + ExecutableBuildOptions& set_deduplicate_hlo(bool deduplicate_hlo); + + // If set, this specifies a static device assignment for the computation. + // Otherwise, the computation will be compiled generically and can be run with + // any device assignment compatible with the computation's replica and + // partition counts. + bool has_device_assignment() const { return device_assignment_.has_value(); } + ExecutableBuildOptions& set_device_assignment( + const DeviceAssignment& device_assignment); + const DeviceAssignment& device_assignment() const { + CHECK(device_assignment_.has_value()); + return device_assignment_.value(); + } + void clear_device_assignment() { device_assignment_.reset(); } + + // Whether input and output buffers are aliased if the associated parameter is + // passed-through XLA modules without being changed. + bool alias_passthrough_params() const { return alias_passthrough_params_; } + void set_alias_passthrough_params(bool alias_passthrough_params) { + alias_passthrough_params_ = alias_passthrough_params; + } + + bool run_backend_only() const { return run_backend_only_; } + // By default, XLA builds an executable by invoking standard compilation, i.e, + // running Compiler::Compile, or both Compiler::RunHloPasses and + // Compiler::RunBackend. When run_backend_only is set to true, XLA builds an + // executable by invoking only RunBackend and skip invoking RunHloPasses, + // which can be used to compile post-optimizations HLO modules. + ExecutableBuildOptions& set_run_backend_only(bool run_backend_only) { + run_backend_only_ = run_backend_only; + return *this; + } + + absl::Span allow_spmd_sharding_propagation_to_output() const { + return allow_spmd_sharding_propagation_to_output_; + } + bool any_allow_spmd_sharding_propagation_to_output() const { + return absl::c_linear_search(allow_spmd_sharding_propagation_to_output_, + true); + } + // Allows sharding propagation to propagate to the outputs. This changes the + // output shape of the computation (which is undesirable), but it can be used + // to allow to run partial compilation to determine what would be the output + // sharding of a computation if XLA would be allowed to propagate the sharding + // which can be used by higher level framework as a way to query intermediate + // sharding of operations when multiple computation would be chained and + // merged together. + ExecutableBuildOptions& set_allow_spmd_sharding_propagation_to_output( + absl::Span allow_spmd_sharding_propagation_to_output) { + allow_spmd_sharding_propagation_to_output_.assign( + allow_spmd_sharding_propagation_to_output.begin(), + allow_spmd_sharding_propagation_to_output.end()); + return *this; + } + + // Thread pool for parallel compilation. + tsl::thread::ThreadPool* compile_thread_pool() const { + return compile_thread_pool_; + } + ExecutableBuildOptions& set_compile_thread_pool( + tsl::thread::ThreadPool* compile_thread_pool) { + compile_thread_pool_ = compile_thread_pool; + return *this; + } + + using LayoutCanonicalizationCallback = + std::function, Shape>>( + const HloModule& module)>; + void set_layout_canonicalization_callback( + LayoutCanonicalizationCallback callback) { + layout_canonicalization_callback_ = std::move(callback); + } + LayoutCanonicalizationCallback layout_canonicalization_callback() const { + return layout_canonicalization_callback_; + } + + absl::string_view fdo_profile() const { return fdo_profile_; } + void set_fdo_profile(const std::string& fdo_profile) { + fdo_profile_ = fdo_profile; + } + std::string* mutable_fdo_profile() { return &fdo_profile_; } + + // The amount of device memory available for the executable. + int64_t device_memory_size() const { return device_memory_size_; } + ExecutableBuildOptions& set_device_memory_size(int64_t device_memory_size) { + device_memory_size_ = device_memory_size; + return *this; + } + + // Returns a string representation of the build options, suitable for + // debugging. + std::string ToString() const; + + StatusOr ToProto() const; + + private: + int device_ordinal_ = -1; + Shape result_layout_; + bool result_layout_set_ = false; + std::optional comp_envs_; + std::optional debug_options_; + se::DeviceMemoryAllocator* device_allocator_ = nullptr; + int num_replicas_ = 1; + int num_partitions_ = 1; + bool use_spmd_partitioning_ = false; + bool use_auto_spmd_partitioning_ = false; + std::vector auto_spmd_partitioning_mesh_shape_; + std::vector auto_spmd_partitioning_mesh_ids_; + bool deduplicate_hlo_ = false; + bool broadcast_replicated_params_ = false; + std::optional device_assignment_; + bool alias_passthrough_params_ = false; + bool run_backend_only_ = false; + absl::InlinedVector allow_spmd_sharding_propagation_to_output_ = { + false}; + tsl::thread::ThreadPool* compile_thread_pool_ = nullptr; + LayoutCanonicalizationCallback layout_canonicalization_callback_; + std::string fdo_profile_; + int64_t device_memory_size_ = 0; +}; + +StatusOr ExecutableBuildOptionsFromProto( + const ExecutableBuildOptionsProto& input); + +// Creates an ExecutionOptions based on a given ExecutableBuildOptions and +// ProgramShape. +ExecutionOptions CreateExecutionOptions( + const ExecutableBuildOptions& build_options, + const ProgramShape* program_shape); + +} // namespace xla + +#endif // XLA_CLIENT_EXECUTABLE_BUILD_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/global_data.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/global_data.h new file mode 100644 index 0000000000000000000000000000000000000000..f54735d4429ca4fec74935cc7f56a4e6bb1d0f83 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/global_data.h @@ -0,0 +1,63 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_GLOBAL_DATA_H_ +#define XLA_CLIENT_GLOBAL_DATA_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/service_interface.h" +#include "xla/xla.pb.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// A GlobalData object represents a globally-accessible allocation of +// data in the associated XLA service. +class GlobalData { + public: + // Gives ownership of the global data handle to this object. + GlobalData(ServiceInterface* parent, GlobalDataHandle handle); + + // Unregisters the wrapped handle, which causes the service to + // deallocate the associated data. + ~GlobalData(); + + const GlobalDataHandle& handle() const { return handle_; } + + // Releases a set of GlobalData handles. A single RPC will be issued + // per unique ServiceInterface of the given GlobalData objects. + static void Release(std::vector> instances); + + private: + // Detaches the global data handle from the object, such that the destructor + // will not try to release it. + GlobalDataHandle Release() { + parent_ = nullptr; + return handle_; + } + + GlobalDataHandle handle_; // Handle being wrapped. + ServiceInterface* parent_; // Service used to unregister handle_. + + GlobalData(const GlobalData&) = delete; + GlobalData& operator=(const GlobalData&) = delete; +}; + +} // namespace xla + +#endif // XLA_CLIENT_GLOBAL_DATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk.h new file mode 100644 index 0000000000000000000000000000000000000000..d92c784b9de65686aee5fe530f0218fdb7d684ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk.h @@ -0,0 +1,70 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_APPROX_TOPK_H_ +#define XLA_CLIENT_LIB_APPROX_TOPK_H_ + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Computes approximate top-ks by aggregating top-1s in equal-sized windows. +// The number and the size of the windows are determined by the `recall_target`. +// +// operand: A sequence of multi-dimensional arrays of type T_0, ..., T_{N-1} +// init_values: N starting values for top-1 reductions +// top_k: Determines the k in top-k operation. +// reduction_dim: Determines the dimension to compute top-k. +// comparator: The comparator computation to use, which should have function +// signatore of (T_0, T_0, T_1, T_1, ..., T_{N-1}, T_{N-1}) -> bool. +// recall_target: Valid range (0, 1]. User can trade-off quality and performance +// with this knob. +// aggregate_to_topk: When true, sorts the set of approximate top-k elements and +// only keep the final k elements on TPU. This option is useful when user +// wanted to forward the approximate results to host and aggregate the results +// on CPU for better throughput. +// reduction_input_size_override: When set to a positive value, it overrides the +// size determined by operands[reduction_dim] for evaluating the recall. This +// option is useful when the given operand is only a subset of the overall +// computation in SPMD or distributed pipelines, where the true input size +// cannot be deferred by the operand shape. +// +// Returns a sequence of multidimensional arrays of type T_0, ..., T_{N-1}, +// which contains the approximate top-ks from the input operands. When +// `aggregate_to_topk` is set to true, the output size is just top_k. When +// `aggregate_to_topk` is set to false, the output size varied by the target +// recall. For target recall = 0.9, the output size is roughly 10 * top_k. For +// target recall = 0.99, the output size is roughly 100 * top_k. +// +// TODO(fchern): Support other hardware platforms. +XlaOp ApproxTopK(XlaBuilder* builder, absl::Span operands, + absl::Span init_values, int64_t top_k, + int64_t reduction_dim, const XlaComputation& comparator, + float recall_target = 0.9, bool aggregate_to_topk = true, + int64_t reduction_input_size_override = -1); + +// Fallback for platforms that haven't been optimized. +XlaOp ApproxTopKFallback(XlaBuilder* builder, absl::Span operands, + absl::Span init_values, int64_t top_k, + int64_t reduction_dim, + const XlaComputation& comparator, + float recall_target = 0.9, + bool aggregate_to_topk = true, + int64_t reduction_input_size_override = -1); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_APPROX_TOPK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk_shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..c569aa3aa40c15ee1ca6a12317c7ea2031fdf6bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/approx_topk_shape.h @@ -0,0 +1,50 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_APPROX_TOPK_SHAPE_H_ +#define XLA_CLIENT_LIB_APPROX_TOPK_SHAPE_H_ + +#include + +#include "xla/statusor.h" + +namespace xla { + +// Determine the output size of the reduction dimension. This is useful for jax +// abstract eval to determine the output size. +// +// input_size: Input size of the reduction dimension. +// rank: Rank of the input operand. +// top_k: Determines the k in top-k operation. +// recall_target: Valid range (0, 1]. User can trade-off quality and performance +// with this knob. +// aggregate_to_topk: When true, sorts the set of approximate top-k elements and +// only keep the final k elements on TPU. This option is useful when user +// wanted to forward the approximate results to host and aggregate the results +// on CPU for better throughput. +// +// Returns a pair of +// 1. Reduction output size +// 2. Reduction amount in log2 form. +// +// 2. is invalid and set to -1 when the approximate output is disabled, i.e. +// top_k = 1 or aggregate_to_topk = true. +StatusOr> ApproxTopKReductionOutputSize( + int64_t input_size, int64_t rank, int64_t top_k, float recall_target, + bool aggregate_to_topk, int64_t input_size_override = -1); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_APPROX_TOPK_SHAPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/arithmetic.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/arithmetic.h new file mode 100644 index 0000000000000000000000000000000000000000..d7b0d2cb5d8adca9a204587664419508f8e3d38f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/arithmetic.h @@ -0,0 +1,94 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_ARITHMETIC_H_ +#define XLA_CLIENT_LIB_ARITHMETIC_H_ + +#include +#include +#include + +#include "xla/client/xla_builder.h" +#include "xla/client/xla_computation.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +using XlaOpGenerator = std::function; + +// Creates a scalar computation based on a lambda and returns it. +XlaComputation CreateScalarComputation(const std::string& name, + PrimitiveType type, XlaBuilder* builder, + XlaOpGenerator generator); + +// Creates a scalar add computation and returns it. +XlaComputation CreateScalarAddComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar multiply computation and returns it. +XlaComputation CreateScalarMultiplyComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar ge computation and returns it. +XlaComputation CreateScalarGeComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar max computation and returns it. +XlaComputation CreateScalarMaxComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar min computation and returns it. +XlaComputation CreateScalarMinComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar logical AND computation and returns it. +XlaComputation CreateScalarAndComputation(PrimitiveType type, + XlaBuilder* builder); + +// Creates a scalar logical OR computation and returns it. +XlaComputation CreateScalarOrComputation(PrimitiveType type, + XlaBuilder* builder); + +// This is to be used for general purpose "identity" like reductions with zero +// for any type (ie. boolean operations for PRED and Add for real numbers). +// As an example, this operation can be used for a situation of: +// x_type = type(x) +// op = CreateScalarIdentityWithZeroComputation(x_type) +// ASSERT_TRUE(op(x, 0) == x) +// +// This functionality is used for operations that are similar to a slice, +// gather, or broadcast, but are created through a reduction. +XlaComputation CreateScalarIdentityWithZeroComputation(PrimitiveType type, + XlaBuilder* builder); + +// Returns whether any predicate in "predicates" is set. +// +// Note: if predicates is zero-sized, Any() vacuously returns false. +XlaOp Any(XlaOp predicates); + +// Returns the argmax of `input` along `axis`. `output_type` is the type to +// use for the output. In case of ties always prefers smaller index. +XlaOp ArgMax(XlaOp input, PrimitiveType output_type, int axis); + +// Returns the argmin of `input` along `axis`. `output_type` is the type to +// use for the output. In case of ties always prefers smaller index. +XlaOp ArgMin(XlaOp input, PrimitiveType output_type, int axis); + +// Dispatch to ArgMin or ArgMax above, depending on bool. +XlaOp ArgMinMax(XlaOp input, PrimitiveType output_type, int axis, bool is_min); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_ARITHMETIC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/broadcast.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/broadcast.h new file mode 100644 index 0000000000000000000000000000000000000000..50a8ab2124f37c911c71068403f4f533e4a982fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/broadcast.h @@ -0,0 +1,32 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_BROADCAST_H_ +#define XLA_CLIENT_LIB_BROADCAST_H_ + +#include "xla/client/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Broadcasts 'input' up to shape 'output_dims', using TensorFlow broadcasting +// rules. Supports broadcasting a dimension of size x to size x*y, i.e., tiling. +StatusOr BroadcastTo(XlaOp input, absl::Span output_dims); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_BROADCAST_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/comparators.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/comparators.h new file mode 100644 index 0000000000000000000000000000000000000000..952a804eddfa31b3b3fcc441182a5f16cf4ea95d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/comparators.h @@ -0,0 +1,59 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_COMPARATORS_H_ +#define XLA_CLIENT_LIB_COMPARATORS_H_ + +#include +#include +#include + +#include "xla/client/xla_builder.h" +#include "xla/client/xla_computation.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Creates a scalar less-than computation and returns it. The created +// computation has 2 * 'operand_types.size()' many parameters, where parameters +// 2 * i and 2 * i + 1 are a scalar with primitive type 'operand_types[i]'. The +// computation compares the first two parameters. For floating point types, a +// total order is created where +// -NaN < -infinity < ... < -0 < 0 < ... < infinity < NaN +XlaComputation CreateScalarLtComputation( + const std::vector& operand_types, XlaBuilder* builder); + +// Creates a scalar greater-than computation and returns it. The created +// computation has 2 * 'operand_types.size()' many parameters, where parameters +// 2 * i and 2 * i + 1 are a scalar with primitive type 'operand_types[i]'. The +// computation compares the first two parameters. For floating point types, a +// total order is created where +// NaN > infinity > ... > 0 > -0 > ... > -infinity > -NaN +XlaComputation CreateScalarGtComputation( + const std::vector& operand_types, XlaBuilder* builder); + +// Creates a scalar comparison computation and returns it. This function takes +// a vector of comparator functions to compare the operands where the function +// isn't nullopt with the specified comparator at that location. +XlaComputation CreateScalarComparisonComputation( + const std::string& name, const std::vector& operand_types, + const std::vector< + std::optional)>>& + generators, + XlaBuilder* builder); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_COMPARATORS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/constants.h new file mode 100644 index 0000000000000000000000000000000000000000..d6c968540eae0bbe07e6989c4d3f6d1afa125a74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/constants.h @@ -0,0 +1,135 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_CONSTANTS_H_ +#define XLA_CLIENT_LIB_CONSTANTS_H_ + +#include + +#include "xla/client/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/float8.h" + +namespace xla { + +// Returns scalar 'value' as a scalar of 'type'. Unlike ConstantR0, 'type' is +// determined at C++ run-time, rather than C++ compile-time. +// If 'value' is floating point but 'type' is not, or if 'value' is complex but +// 'type' is not, an error will be returned. This is to catch accidental +// truncation; in such cases, use an explicit cast. +template +XlaOp ConstantR0WithType(XlaBuilder* builder, PrimitiveType type, T value) { + if (std::is_floating_point::value && + !(primitive_util::IsFloatingPointType(type) || + primitive_util::IsComplexType(type))) { + return builder->ReportError(InvalidArgument( + "Invalid cast from floating point type to %s in ConstantR0WithType.", + PrimitiveType_Name(type))); + } + if (std::is_same::value && + !primitive_util::IsComplexType(type)) { + return builder->ReportError(InvalidArgument( + "Invalid cast from complex type to %s in ConstantR0WithType.", + PrimitiveType_Name(type))); + } + return primitive_util::PrimitiveTypeSwitch( + [&](auto primitive_type_constant) -> XlaOp { + if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { + using NativeT = primitive_util::NativeTypeOf; + return ConstantR0(builder, static_cast(value)); + } + return builder->ReportError( + InvalidArgument("Invalid type for ConstantR0WithType (%s).", + PrimitiveType_Name(type))); + }, + type); +} + +// Returns a scalar containing 'value' cast to the same run-time type as +// 'prototype'. +// If 'value' is floating point but 'prototype' is not, or if 'value' is complex +// 'prototype' is not, an error will be returned. +template +XlaOp ScalarLike(XlaOp prototype, T value) { + XlaBuilder* builder = prototype.builder(); + return builder->ReportErrorOrReturn([&]() -> StatusOr { + TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(prototype)); + return ConstantR0WithType(builder, shape.element_type(), value); + }); +} + +// Returns an array or scalar containing copies of `value` cast to the same +// run-type type as `prototype` and broadcast to the same dimensions as +// `prototype`. +// +// If `prototype` is not a scalar or array, returns an error. +template +XlaOp FullLike(XlaOp prototype, T value) { + XlaBuilder* builder = prototype.builder(); + return builder->ReportErrorOrReturn([&]() -> StatusOr { + TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(prototype)); + if (ShapeUtil::IsScalar(shape) || shape.IsArray()) { + return Broadcast(ScalarLike(prototype, value), shape.dimensions()); + } else { + return InvalidArgument( + "Prototype shape for BroadcastConstantLike must be a scalar or " + "array, but was %s", + shape.ToString()); + } + }); +} + +// Returns a scalar with value '0' of 'type'. +XlaOp Zero(XlaBuilder* builder, PrimitiveType type); + +// Returns a zero-filled tensor with shape `shape`. +XlaOp Zeros(XlaBuilder* builder, const Shape& shape); + +// Returns a zero-filled tensor with the same shape as `prototype`. +XlaOp ZerosLike(XlaOp prototype); + +// Returns a scalar with value '1' of 'type'. +XlaOp One(XlaBuilder* builder, PrimitiveType type); + +// Returns the machine epsilon for floating-point type `type`, i.e., +// the difference between 1.0 and the next representable value. +XlaOp Epsilon(XlaBuilder* builder, PrimitiveType type); + +// Returns the minimum representable finite or infinite value for 'type'. +// Returns '-inf' for floating-point types. +XlaOp MinValue(XlaBuilder* builder, PrimitiveType type); + +// Returns the minimum representable finite value for 'type'. For a floating +// point type, this is equal to -MaxFiniteValue(). +XlaOp MinFiniteValue(XlaBuilder* builder, PrimitiveType type); + +// Returns the minimum positive normal value for floating-point type `type`. +XlaOp MinPositiveNormalValue(XlaBuilder* builder, PrimitiveType type); + +// Returns the maximum representable finite or infinite value for 'type'. +// Returns 'inf' for floating-point types. +XlaOp MaxValue(XlaBuilder* builder, PrimitiveType type); + +// Returns the maximum representable finite value for 'type'. +XlaOp MaxFiniteValue(XlaBuilder* builder, PrimitiveType type); + +// Returns a nan for the given type. Only valid for real-valued fp types. +XlaOp NanValue(XlaBuilder* builder, PrimitiveType type); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/conv_grad_size_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/conv_grad_size_util.h new file mode 100644 index 0000000000000000000000000000000000000000..1de80450492215cb9197380f338d5264061e6a6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/conv_grad_size_util.h @@ -0,0 +1,43 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_CONV_GRAD_SIZE_UTIL_H_ +#define XLA_CLIENT_LIB_CONV_GRAD_SIZE_UTIL_H_ + +#include "xla/client/padding.h" + +namespace xla { + +// Information about a single spatial dimension for a convolution gradients and +// windowed operations. +struct SpatialDimensionOutputSizeAndPadding { + // Effective size of the operation output (potentially expanded). + int64_t output_size; + // Number of padding elements to be added before/after this dimension of + // the input when computing the input gradient. + int64_t pad_before; + int64_t pad_after; +}; + +// Verifies that the dimensions all match, and computes the size and padding of +// a spatial dimension for convolution gradient operations. +StatusOr +ConvGradExtractAndVerifyDimension(int64_t input_size, int64_t filter_size, + int64_t output_size, int64_t dilation, + int64_t stride, Padding padding); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_CONV_GRAD_SIZE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/dynamic_shaped_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/dynamic_shaped_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..969d0ddadf971676773bca111bc18184c079b812 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/dynamic_shaped_ops.h @@ -0,0 +1,56 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_DYNAMIC_SHAPED_OPS_H_ +#define XLA_CLIENT_LIB_DYNAMIC_SHAPED_OPS_H_ + +#include "xla/client/lib/constants.h" +#include "xla/client/value_inference.h" +#include "xla/client/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Similar to static shaped conditional, but allows true_computation and +// false_computation to have different dimension sizes (ranks still have to be +// the same). Fall back to static conditional if dynamism is not presented. +XlaOp DynamicConditional(XlaBuilder* builder, XlaOp predicate, + XlaOp true_operand, + const XlaComputation& true_computation, + XlaOp false_operand, + const XlaComputation& false_computation); + +// Similar to DynamicConditional, but support multiple branches. +XlaOp DynamicConditional( + XlaBuilder* builder, XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + +// Similar to SetDimensionSize, but automatically adjust the bound of output if +// a tighter one can be inferred by `value_inference`. +StatusOr SetDimensionSizeWithRebound(ValueInference* value_inference, + XlaOp operand, XlaOp dimension_size, + int64_t dimension); + +// Take a `operand` tensor and a R1 tensor `size_vector` representing the sizes +// of `operand`, Call SetDimensionSize if for each dimension whose size is +// dynamic. +StatusOr SetAllDimensionSizes(ValueInference* value_inference, + XlaOp operand, XlaOp size_vector); +} // namespace xla + +#endif // XLA_CLIENT_LIB_DYNAMIC_SHAPED_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/loops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/loops.h new file mode 100644 index 0000000000000000000000000000000000000000..6ee295be155ee25f6de320fe60b5a0ec2ffa77c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/loops.h @@ -0,0 +1,72 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_LOOPS_H_ +#define XLA_CLIENT_LIB_LOOPS_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/client/xla_builder.h" +#include "xla/client/xla_computation.h" +#include "xla/statusor.h" + +namespace xla { + +// Function that builds a loop condition. Takes as input a sequence of input +// values, and returns a boolean value representing if the condition succeeds. +typedef std::function(absl::Span, XlaBuilder*)> + WhileLoopHelperConditionFunction; + +// Function that builds a loop body. Takes as input a sequence of input values +// and returns a sequence of output values. +typedef std::function>(absl::Span, + XlaBuilder*)> + WhileLoopHelperBodyFunction; + +// Helper function for building an XLA while loop, where the values carried by +// the loop are a tuple of values, e.g., (a, b, c): +// while( +// condition: (a, b, c) -> bool, +// body: (a, b, c) -> (a, b, c) +// init: (a, b, c) +// ) +// 'name' is a descriptive name for the loop. +StatusOr> WhileLoopHelper( + const WhileLoopHelperConditionFunction& condition_function, + const WhileLoopHelperBodyFunction& body_function, + absl::Span initial_values, absl::string_view name, + XlaBuilder* builder); + +// Builds an XLA loop that repeats a computation `num_iterations` times. +// +// The body function (ForEachIndexBodyFunction) takes as input a pair of +// (current iteration number, loop-carried values), and returns an updated +// vector of the loop-carried values. +typedef std::function>( + XlaOp, absl::Span, XlaBuilder*)> + ForEachIndexBodyFunction; + +StatusOr> ForEachIndex( + int64_t num_iterations, PrimitiveType num_iterations_type, + const ForEachIndexBodyFunction& body_function, + absl::Span initial_values, absl::string_view name, + XlaBuilder* builder); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_LOOPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/math.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/math.h new file mode 100644 index 0000000000000000000000000000000000000000..9ef7a5967d7a099db9aadf0476ab6df01677cbb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/math.h @@ -0,0 +1,130 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_MATH_H_ +#define XLA_CLIENT_LIB_MATH_H_ + +#include "xla/client/xla_builder.h" + +namespace xla { + +// Determines whether operand is +/-inf or nan. +// +// Raises an error if called on integral or complex values. +XlaOp IsPosInf(XlaOp operand); +XlaOp IsNegInf(XlaOp operand); +XlaOp IsInf(XlaOp operand); +XlaOp IsNan(XlaOp operand); + +// Determines whether operand is equal to -0. +// +// Raises an error for integral or complex values. +XlaOp IsNegZero(XlaOp operand); + +// Returns the next number after 'from' in the direction of 'to' the same way +// std::nextafter(from, to) would. +XlaOp NextAfter(XlaOp from, XlaOp to); + +// Computes the square of 'operand'. +XlaOp Square(XlaOp operand); + +// Computes the reciprocal of 'operand'. +XlaOp Reciprocal(XlaOp operand); + +// Computes an approximation of the error function complement (1 - erf(x)). +XlaOp Erfc(XlaOp x); + +// Computes an approximation of the error function. +XlaOp Erf(XlaOp x); + +// Computes an approximation of the inverse of the error function. +XlaOp ErfInv(XlaOp x); + +// Computes an approximation of the lgamma function. +XlaOp Lgamma(XlaOp input); + +// Computes an approximation of the digamma function. +XlaOp Digamma(XlaOp input); + +// Computes an approximation of the incomplete gamma function. +XlaOp Igamma(XlaOp a, XlaOp x); + +// Computes an approximation of the derivative of the incomplete gamma function +// with respect to a. +XlaOp IgammaGradA(XlaOp a, XlaOp x); + +// Computes an approximation of the derivative of a sample `x` from a `Gamma(a, +// 1)` distribution with respect to a. +XlaOp RandomGammaGrad(XlaOp a, XlaOp x); + +// Computes an approximation of the complementary incomplete gamma function. +XlaOp Igammac(XlaOp a, XlaOp x); + +// Computes the Polygamma of two arguments. +XlaOp Polygamma(XlaOp n, XlaOp x); + +// Computes the Riemann zeta function of two arguments. +XlaOp Zeta(XlaOp x, XlaOp q); + +// Rounds the given number to even when the number is equidistant between two +// integers. +XlaOp RoundToEven(XlaOp x); + +// Trigonometric functions + +// Computes the arc cosine of 'x'. +XlaOp Acos(XlaOp x); + +// Computes the arc sine of 'x'. +XlaOp Asin(XlaOp x); + +// Computes the arc tangent of 'x'. +XlaOp Atan(XlaOp x); + +// Hyperbolic trigonometric functions + +// Computes the inverse hyperbolic cosine of 'x'. +XlaOp Acosh(XlaOp x); + +// Computes the inverse hyperbolic sine of 'x'. +XlaOp Asinh(XlaOp x); + +// Computes the inverse hyperbolic tangent of 'x'. +XlaOp Atanh(XlaOp x); + +// Computes the hyperbolic cosine of 'x'. +XlaOp Cosh(XlaOp x); + +// Computes the hyperbolic sine of 'x'. +XlaOp Sinh(XlaOp x); + +// Applies a complex conjugation operation if 'a' is complex and 'conjugate' +// is true, otherwise returns its argument. +xla::XlaOp MaybeConjugate(xla::XlaOp x, bool conjugate); + +// Computes the Modified Bessel function of the first kind of the zeroth order +// at x. +XlaOp BesselI0e(XlaOp x); + +// Computes the Modified Bessel function of the first kind of the first order +// at x. +XlaOp BesselI1e(XlaOp x); + +// Computes the Regularized Incomplete Beta function. +XlaOp RegularizedIncompleteBeta(XlaOp a, XlaOp b, XlaOp x); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_MATH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/matrix.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/matrix.h new file mode 100644 index 0000000000000000000000000000000000000000..bead189147d3b4d353e7b12bf0623ac8490bced5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/matrix.h @@ -0,0 +1,157 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_MATRIX_H_ +#define XLA_CLIENT_LIB_MATRIX_H_ + +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/client/xla_builder.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Returns an m x n matrix with 1s on the diagonal elements, zeros everywhere +// else. +XlaOp IdentityMatrix(XlaBuilder* builder, PrimitiveType type, int64_t m, + int64_t n); + +// Returns a mask where the 'diagonal'-th diagonal is true and everything else +// is false. +XlaOp GetDiagonalMask(XlaOp x, int diagonal = 0); + +// Get the diagonals of the last two dimensions. Use k>0 for diagonals above the +// main diagonal, and k<0 for diagonals below the main diagonal. +// +// If 'x' has shape [..., M, N] +// If k >= 0: then the output has shape [..., min(M, N - k)], containing the +// diagonal elements (i.e., with indices [..., i, i + k]). +// If k < 0: then the output has shape [..., min(M + k, N)], containing the +// diagonal elements (i.e., with indices [..., i - k, i]). +XlaOp GetMatrixDiagonal(XlaOp x, int k = 0); +XlaOp GetMatrixDiagonalViaGather(XlaOp x, int k = 0); + +// Places diag along the kth diagonal of target. +XlaOp SetMatrixDiagonal(XlaOp matrix, XlaOp diag, int k = 0); + +// Returns a lower-triangular mask, i.e., true below and including the +// `diagonal`-th diagonal and false above that diagonal. +XlaOp TriangleMask(XlaOp x, int diagonal); + +// Get the upper or lower triangle part of the last two dimensions +XlaOp Triangle(XlaOp x, bool lower); + +// Get the upper triangle part of the last two dimensions +XlaOp UpperTriangle(XlaOp x); + +// Get the lower triangle part of the last two dimensions +XlaOp LowerTriangle(XlaOp x); + +// If x is an array of shape [..., n, n], symmetrizes the matrix by replacing +// the upper triangle with the transpose of the lower triangle (if lower is +// True, vice-versa otherwise). If the type of `x` is complex, makes the matrix +// Hermitian by taking the conjugate of the complex part and setting the +// complex diagonal to zero. +XlaOp Symmetrize(XlaOp x, bool lower); + +// Multiplies slices of two tensors in batches. + +// Multiplies all slices of `Tensor` `x` and `y` (each slice can be +// viewed as an element of a batch), and arranges the individual results +// in a single output tensor of the same batch size. +// +// The input tensors `x` and `y` are 2-D or higher with shape `[..., r_x, c_x]` +// and `[..., r_y, c_y]`. +// +// The output tensor is 2-D or higher with shape `[..., r_o, c_o]`, where: +// +// r_o = c_x if transpose_x else r_x +// c_o = r_y if transpose_y else c_y +// +// It is computed as: +// +// output[..., :, :] = matrix(x[..., :, :]) * matrix(y[..., :, :]) +xla::XlaOp BatchDot( + xla::XlaOp x, xla::XlaOp y, + xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT, + std::optional preferred_element_type = std::nullopt); +xla::XlaOp BatchDot( + xla::XlaOp x, bool transpose_x, xla::XlaOp y, bool transpose_y, + xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT, + std::optional preferred_element_type = std::nullopt); + +// Parse an einsum string into dimension numbers: +// "ab,cb->ac" +// becomes: +// {{0, 1},{2, 1},{0, 2}} +// +// Each occurrence of ellipsis ("...") occurring in the input is replaced with +// the same numeric dimensions. The number of such dimensions is inferred from +// x_rank and y_rank. For example: +// einsum_config: "...ab,...bcd->...acd" +// x_rank: 4 +// y_rank: 5 +// becomes: +// {{0, 1, 2, 3},{0, 1, 3, 4, 5},{0, 1, 2, 4, 5}} +// +// NOTE: This function is meant for testing, there is no need to call it +// directly. + +StatusOr, 3>> ParseEinsumString( + absl::string_view einsum_config, int64_t x_rank, int64_t y_rank); + +// If an einsum config does not contain an -> one will be added and the output +// config will be the sorted characters with any ellipsis at the beginning. +// Returns an empty string if the einsum string already has an ->. +std::string NormalizeEinsumString(absl::string_view einsum_config); + +// Supports two operand einsum notation like "ab,cb->ac". +xla::XlaOp Einsum( + xla::XlaOp x, xla::XlaOp y, absl::string_view einsum_config, + xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT, + std::optional preferred_element_type = std::nullopt); +xla::XlaOp Einsum( + xla::XlaOp x, absl::string_view einsum_config, + xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT); + + +// Same as above but supporting numeric labels on dimensions. So "ab,cb->ac" +// becomes: +// x_config = {0, 1} +// y_config = {2, 1} +// output_config = {0, 2} +xla::XlaOp Einsum( + xla::XlaOp x, absl::Span x_config, xla::XlaOp y, + absl::Span y_config, absl::Span output_config, + xla::PrecisionConfig::Precision precision = xla::PrecisionConfig::DEFAULT, + std::optional preferred_element_type = std::nullopt); + +// Transposes a stack of matrices `x` by swapping the last two dimensions. +xla::XlaOp TransposeInMinorDims(xla::XlaOp x); + +// Transposes `x` in its minor dimensions if `transpose` is true, otherwise +// returns `x` unchanged. +xla::XlaOp MaybeTransposeInMinorDims(xla::XlaOp x, bool transpose); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_MATRIX_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/pooling.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/pooling.h new file mode 100644 index 0000000000000000000000000000000000000000..d8f0ff0a91654654a082f0676fba3b58657bc32e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/pooling.h @@ -0,0 +1,81 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_POOLING_H_ +#define XLA_CLIENT_LIB_POOLING_H_ + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "xla/client/xla_builder.h" + +namespace xla { + +// Tensor format for reduce window operations. +class TensorFormat { + public: + TensorFormat(int batch_dimension, int feature_dimension, + absl::Span spatial_dimensions) + : batch_dimension_(batch_dimension), + feature_dimension_(feature_dimension), + spatial_dimensions_(spatial_dimensions.begin(), + spatial_dimensions.end()) {} + + int batch_dimension() const { return batch_dimension_; } + + int feature_dimension() const { return feature_dimension_; } + + int spatial_dimension(int dim) const { return spatial_dimensions_[dim]; } + + int num_spatial_dims() const { return spatial_dimensions_.size(); } + + private: + // The number of the dimension that represents the batch. + int batch_dimension_; + // The number of the dimension that represents the features. + int feature_dimension_; + // The dimension numbers for the spatial dimensions. + absl::InlinedVector spatial_dimensions_; +}; + +// Computes the max pool of 'operand'. +XlaOp MaxPool(XlaOp operand, absl::Span kernel_size, + absl::Span stride, Padding padding, + const TensorFormat& data_format); + +// Computes the average pool of 'operand'. +XlaOp AvgPool(XlaOp operand, absl::Span kernel_size, + absl::Span stride, + absl::Span> padding, + const TensorFormat& data_format, bool counts_include_padding); + +// Returns the list of low and high padding elements in each spatial dimension +// for the given 'padding' specification. +std::vector> MakeSpatialPadding( + absl::Span input_size, absl::Span kernel_size, + absl::Span stride, Padding padding, + const TensorFormat& data_format); + +// Computes the average pool gradient. +XlaOp AvgPoolGrad(XlaOp out_backprop, absl::Span gradients_size, + absl::Span kernel_size, + absl::Span stride, + absl::Span> spatial_padding, + const TensorFormat& data_format, bool counts_include_padding); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_POOLING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/prng.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/prng.h new file mode 100644 index 0000000000000000000000000000000000000000..77d931ef074ad62e00d6999a8f1382a57da208a2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/prng.h @@ -0,0 +1,99 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_PRNG_H_ +#define XLA_CLIENT_LIB_PRNG_H_ + +#include +#include +#include + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Records the bits and state generated by a random number generator. +struct RngOutput { + XlaOp value; + XlaOp state; +}; + +// A BitGenerator returns random bits and updated random bit generator state. +// +// key: is a value input to a random number generator that can affect the +// sequence of number it will generate. A random number generator constructs +// its seed using the key and the initial state. The tf2xla bridge passes the +// seed operand of a tensorflow random operation as a key to the random bit +// generator, for example. +// initial_state: initial_state is the initial state of the current random +// number generation. It could be 0 for a stateless random operation, and +// the returned state from a previous execution for a stateful random +// operation. +// shape: the shape of the random bits. +using BitGeneratorTy = std::function; + +// Implements the ThreeFry counter-based PRNG algorithm. +// Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3. +// http://www.thesalmons.org/john/random123/papers/random123sc11.pdf +RngOutput ThreeFryBitGenerator(XlaOp key, XlaOp initial_state, + const xla::Shape& shape); + +// Implements the Philox algorithm to generate random numbers in parallel. +// Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3. +// http://www.thesalmons.org/john/random123/papers/random123sc11.pdf +// +// The paper presents a few variants of the Philox algorithm, we picked the +// 4x32_10 version of the algorithm for the following reasons: +// . 4x32 uses 32-bit multiplication which is fast on GPUs. +// . The authors recommend the 10-round variant, and TensorFlow also uses it. +RngOutput PhiloxBitGenerator(XlaOp key, XlaOp initial_state, + const Shape& shape); +// Returns a scrambled pair of (state, key) from a single key. +std::pair ScramblePhiloxKey(XlaOp key); + +// Uses the given bit generator to generate random bits and then converts the +// random bits to random numbers of uniform distribution in the given range. +// Returns the random numbers and the state of the random number generator. +// This function is for shape with floating point element types. +RngOutput UniformFloatingPointDistribution(XlaOp key, XlaOp initial_state, + BitGeneratorTy bit_generator, + XlaOp minval, XlaOp maxval, + const xla::Shape& shape); + +// Similar to UniformFloatingPointDistribution but for shape with integer +// element types. +RngOutput UniformIntDistribution(XlaOp key, XlaOp initial_state, + BitGeneratorTy bit_generator, XlaOp minval, + XlaOp maxval, const xla::Shape& shape); + +// Uses the given bit generator to generate random bits and then converts the +// random bits to random numbers of normal distribution. +// Returns the random numbers and the state of the random number generator. +RngOutput NormalFloatingPointDistribution(XlaOp key, XlaOp initial_state, + BitGeneratorTy bit_generator, + const xla::Shape& shape); + +// Concatenates scalars into a vector. +xla::XlaOp ConcatScalars(xla::XlaBuilder* builder, + absl::Span scalars); + +// Increases Philox counter (an uint128_t) by a delta (an uint64_t). +xla::XlaOp PhiloxIncreaseCounter(xla::XlaOp counter, xla::XlaOp delta); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_PRNG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/qr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/qr.h new file mode 100644 index 0000000000000000000000000000000000000000..6d8a102b28fc196993969edad6565652cc41fc24 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/qr.h @@ -0,0 +1,52 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_QR_H_ +#define XLA_CLIENT_LIB_QR_H_ + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Computes the QR decompositions of a batch of matrices. That is, +// given a (batched) matrix a, computes an orthonormal matrix Q and an +// upper-triangular matrix R such that a = QR. +// `a` must be a (batched) matrix of size [..., m, n]. +struct QrDecomposition { + // A matrix with the same shape as the input matrix `a`, whose upper triangle + // (inclusive of the diagonal) is the matrix R, and whose lower triangle + // (exclusive of the diagonal) contains the elementary Householder reflectors. + // This is the same output format as used by LAPACK's xGEQRF routine. + XlaOp q_and_r; + // A vector of shape [..., min(m, n)] containing the scalar factors of the + // elementary Householder reflectors. + XlaOp taus; +}; + +QrDecomposition Qr(XlaOp a); + +// Given `a` and `taus` as returned by `QRDecomposition`, compute the product of +// the elementary Householder reflectors (i.e., the matrix Q of the QR +// decomposition). The equivalent LAPACK routine is xORGQR/xUNGQR. +XlaOp ProductOfElementaryHouseholderReflectors(XlaOp a, XlaOp taus); + +// Helper that combines `Qr` and `ProductOfElementaryHouseholderReflectors` to +// compute explicit matrices `q` and `r`. +void QrExplicit(XlaOp a, bool full_matrices, XlaOp& q, XlaOp& r); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_QR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/quantize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/quantize.h new file mode 100644 index 0000000000000000000000000000000000000000..a510651e1e640eb0c07ac6dd02c9d52feb5c1ade --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/quantize.h @@ -0,0 +1,184 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_QUANTIZE_H_ +#define XLA_CLIENT_LIB_QUANTIZE_H_ + +#include +#include +#include +#include + +#include "xla/client/lib/constants.h" +#include "xla/client/xla_builder.h" +#include "xla/types.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/bfloat16.h" + +namespace xla { + +// Represents the range used for quantization +struct QuantizedRange { + QuantizedRange() = default; + QuantizedRange(float min_in, float max_in) : min(min_in), max(max_in) {} + + bool operator==(const QuantizedRange& rhs) const { + return this->min == rhs.min && this->max == rhs.max; + } + + bool operator!=(const QuantizedRange& rhs) const { return !(*this == rhs); } + + tsl::bfloat16 min = tsl::bfloat16(0.0f); + tsl::bfloat16 max = tsl::bfloat16(0.0f); +}; + +template +inline std::vector PackToUint32(absl::Span input) { + const int64_t kElementsPerPack = sizeof(uint32_t) / sizeof(T); + const int64_t input_size = input.size(); + const int64_t output_size = CeilOfRatio(input_size, kElementsPerPack); + + std::vector output_vec; + constexpr int64_t kShiftBits = sizeof(T) / sizeof(uint8_t) * CHAR_BIT; + + for (int64_t i = 0; i < output_size; i++) { + uint32_t result = 0; + for (int64_t p = 0; p < kElementsPerPack; p++) { + int64_t index = i * kElementsPerPack + p; + if (index < input_size) { + int64_t total_shift_bits = kShiftBits * (kElementsPerPack - p - 1); + result |= (input[index] << total_shift_bits); + } + } + output_vec.push_back(result); + } + + return output_vec; +} + +// Dequantize the quantized input of packed uint32_t to bfloat16. +// Only uint8_t or uint16_t is supported for the original unpacked input. +// Returns a tensor of shape [d0,..., dn * unpack_size] if +// input shape is [d0, ..., dn], where unpack_size = sizeof(unit32) / sizeof(T). +// If transpose_output is true, will return a tensor of shape +// [dn * unpack_size, dn-1, ..., d1, d0]. transpose_output is faster when +// input's rank higher than 1. The input needs to be transposed to use +// transpose_output feature. +template +inline XlaOp Dequantize(XlaOp input, const QuantizedRange& range, + absl::string_view mode_string = "MIN_COMBINED", + bool transpose_output = false) { + XlaBuilder* const builder = input.builder(); + return builder->ReportErrorOrReturn([&]() -> StatusOr { + float half_range = + !std::is_signed::value + ? 0.0f + : (static_cast(std::numeric_limits::max()) - + std::numeric_limits::min() + 1) / + 2.0f; + const int64_t unpack_size = sizeof(uint32_t) / sizeof(T); + TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(input)); + + auto element_type = shape.element_type(); + if (element_type != U32) { + return InvalidArgument( + "Only U32 is supported for input type of xla::Dequantize Op."); + } + + // Broadcast the input to [unpack_size, d0, ..., dn] if input size is + // [d0, ..., dn]. + auto broadcast_input = Broadcast(input, {unpack_size}); + + XlaOp iota_r1 = Iota(builder, U32, unpack_size); + // Highest significant bytes needs to shift more bytes than lower + // significant bytes. + XlaOp shift_bytes = + xla::ConstantR0(builder, unpack_size - 1) - iota_r1; + + const int bytes_of_type = sizeof(T) / sizeof(uint8_t); + std::vector shift_vec(unpack_size, CHAR_BIT * bytes_of_type); + XlaOp shift_bits = + shift_bytes * xla::ConstantR1(builder, shift_vec); + + // Make bit_mask for different data type T. + uint32_t bit_mask = 0x00000000; + for (int i = 0; i < bytes_of_type; i++) { + bit_mask <<= CHAR_BIT; + bit_mask |= 0x000000ff; + } + + std::vector shift_transpose_dimensions(shape.dimensions_size()); + std::iota(shift_transpose_dimensions.begin(), + shift_transpose_dimensions.end(), 0); + shift_transpose_dimensions.insert(shift_transpose_dimensions.begin(), 1, + shape.dimensions_size()); + + // Shift the input by sizeof(T) bytes and apply bit_mask to unpack. + XlaOp shifted_input = ShiftRightLogical( + broadcast_input, Transpose(Broadcast(shift_bits, shape.dimensions()), + shift_transpose_dimensions)); + XlaOp unpack_input = + And(shifted_input, xla::ConstantR0(builder, bit_mask)); + + XlaOp result; + + if (mode_string == "MIN_COMBINED") { + const tsl::bfloat16 scale_factor = + (range.max - range.min) / + (static_cast(std::numeric_limits::max() - + std::numeric_limits::min())); + // result = bfloat16(input + half_range) * scale_factor + range.min + XlaOp unpack_input_bf16 = ConvertElementType(unpack_input, BF16); + XlaOp half_range_bf16 = xla::ConstantR0( + builder, static_cast(half_range)); + XlaOp sum = unpack_input_bf16 + half_range_bf16; + + result = sum * xla::ConstantR0(builder, scale_factor) + + xla::ConstantR0(builder, range.min); + } else { + // TODO(wangtao): support other modes. + return InvalidArgument( + "Only MIN_COMBINED mode is supported in xla::Dequantize Op."); + } + + std::vector transpose_dimensions(shape.dimensions_size()); + std::iota(transpose_dimensions.begin(), transpose_dimensions.end(), 1); + std::reverse(transpose_dimensions.begin(), transpose_dimensions.end()); + transpose_dimensions.insert(transpose_dimensions.begin() + 1, 1, 0); + + // Transpose the result to be [dn, unpack_size, dn-1, ..., d1, d0]. + XlaOp transposed_result = Transpose(result, transpose_dimensions); + + // Reshape to be [dn * unpack_size, dn-1, ..., d1, d0]. + XlaOp reshaped_result = Collapse(transposed_result, {0, 1}); + + // Return the transpose result if transpose_output is true. + if (transpose_output) { + return reshaped_result; + } + + // Transpose the result to be [d0, d1, ..., dn-1, dn * unpack_size]. + std::vector result_dimensions(shape.dimensions_size()); + std::iota(result_dimensions.begin(), result_dimensions.end(), 0); + std::reverse(result_dimensions.begin(), result_dimensions.end()); + + return Transpose(reshaped_result, result_dimensions); + }); +} + +} // namespace xla + +#endif // XLA_CLIENT_LIB_QUANTIZE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/self_adjoint_eig.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/self_adjoint_eig.h new file mode 100644 index 0000000000000000000000000000000000000000..c21163dff056b9166e4d24b1c2c79149f4246583 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/self_adjoint_eig.h @@ -0,0 +1,41 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_SELF_ADJOINT_EIG_H_ +#define XLA_CLIENT_LIB_SELF_ADJOINT_EIG_H_ + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// The eigenvalue decomposition of a symmetric matrix, the original matrix is +// recovered by v * w * v_t. +struct SelfAdjointEigResult { + // The i-th column is the normalized eigenvector corresponding to the + // eigenvalue w[i]. Will return a matrix object if a is a matrix object. + XlaOp v; + // The eigenvalues in ascending order, each repeated according to its + // multiplicity. + XlaOp w; +}; + +SelfAdjointEigResult SelfAdjointEig(XlaOp a, bool lower = true, + int64_t max_iter = 15, float tol = 1e-5, + bool sort_eigenvalues = true); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_SELF_ADJOINT_EIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/slicing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/slicing.h new file mode 100644 index 0000000000000000000000000000000000000000..b0b955c0234201feebd6b21d130dc9a0d3f4c6ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/slicing.h @@ -0,0 +1,90 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include + +#include "absl/types/span.h" +#include "xla/client/xla_builder.h" +#include "xla/types.h" + +#ifndef XLA_CLIENT_LIB_SLICING_H_ +#define XLA_CLIENT_LIB_SLICING_H_ + +namespace xla { + +// Slices input starting from the base_indices and within the window_sizes, +// using the supplied strides. This is the equivalent of the Python slicing op +// [base_indices : base_indices+window_sizes : stride]. +XlaOp DynamicStridedSlice(XlaOp input, absl::Span base_indices, + absl::Span window_sizes, + absl::Span strides); + +// Updates a slice of 'x', i.e., +// x[start[0], ..., start[n]] = update +XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span start); + +// Performs a slice in the minor dimensions of a tensor. +// x[..., start[0]:end[0], ..., start[n]:end[n]] +XlaOp SliceInMinorDims(XlaOp x, absl::Span start, + absl::Span end); + +// Updates a slice of 'x', where 'start' contains a list of minor dimensions: +// x[..., start[0]:..., ..., start[n]:...] = update +XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update, + absl::Span start); + +// Performs a dynamic slice in the minor dimensions of a tensor. +XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span starts, + absl::Span sizes); + +XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update, + absl::Span starts); + +// Gathers values along an axis specified by dim. +// +// For a 3-D tensor the output is specified by: +// +// out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 +// out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 +// out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 +// +// If `input` is an n-dimensional tensor with size +// [X0,X1,X2,..XN] and dim = i `index` must be an n-dimensional tensor with size +// [X0,X1,...Y,Xi+1,...,X[N] where y >= 1 and `out` will have the same sizes as +// `index`. +XlaOp TorchGather(XlaOp input, XlaOp index, int64_t dim, bool sparse = true); + +// idx = index[i][j][k] +// output[idx][j][k] = combiner(input[idx][j][k], src[i][j][k]) # if dim == 0 +// output[i][idx][k] = combiner(input[i][idx][k], src[i][j][k]) # if dim == 1 +// output[i][j][idx] = combiner(input[i][j][idx], src[i][j][k]) # if dim == 2 +XlaOp TorchScatterDense(XlaOp input, XlaOp index, XlaOp src, int64_t dim, + const std::function& combiner); + +// Returns a new tensor which indexes the input tensor along dimension dim using +// the entries in index. +// +// The returned tensor has the same number of dimensions as the original tensor +// (input). The dimth dimension has the same size as the length of index; other +// dimensions have the same size as in the original tensor. +// +// This operation supports 0 or more major batch dimensions that act like a +// multidimensional loop over both the input and the index. +XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64_t dim, + int64_t batch_dims = 0); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_SLICING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/sorting.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/sorting.h new file mode 100644 index 0000000000000000000000000000000000000000..03b317037df4888111121b1856a2aabb1a403166 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/sorting.h @@ -0,0 +1,38 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_SORTING_H_ +#define XLA_CLIENT_LIB_SORTING_H_ + +#include "xla/client/xla_builder.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Returns a tuple composed of the top `k` values and corresponding indices in +// `input`. Output values are in descending order, from largest to smallest. +XlaOp TopK(XlaOp input, int64_t k, + PrimitiveType index_type = PrimitiveType::S32); + +// Split sort in TopK into smaller sorts. +// Returns a tuple composed of the top `k` values and corresponding indices in +// `input`. Output values are in descending order, from largest to smallest. +XlaOp TopKWithPartitions(XlaOp input, int64_t k, int64_t num_partitions = 1, + PrimitiveType index_type = PrimitiveType::S32); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_SORTING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/svd.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/svd.h new file mode 100644 index 0000000000000000000000000000000000000000..177d84f3153d867ee0cc0432ffa63dc7c5ccd5d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/svd.h @@ -0,0 +1,49 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_SVD_H_ +#define XLA_CLIENT_LIB_SVD_H_ + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// The singular value decomposition of a given matrix A[..., M, N], the original +// matrix is recovered by u * diag(d) * v_t, where the first dims(A) - 2 +// dimensions are batch dimensions. +struct SVDResult { + // The columns of U are the left-singular vectors, e.g., + // U[..., :, :]_T * U[..., :, :] = I. + XlaOp u; + // Vector(s) with the singular values, within each vector sorted in descending + // order. The first dims(D) - 1 dimensions have the same size as the batch + // dimensions of A. And U[..., :, i] * D[..., i] = A[..., :, :] * V[..., :, + // i]. + XlaOp d; + // The columns of V are the right-singular vectors. e.g., + // V[..., :, :]_T * V[..., :, :] = I. + XlaOp v; +}; + +// TODO(kuny): Add a bool flag that supports SVD with economy (reduced) +// representation, which is more memory efficient, especially in the case of +// tall-skinny matrices. +SVDResult SVD(XlaOp a, int64_t max_iter = 100, float epsilon = 1e-6, + PrecisionConfig::Precision precision = PrecisionConfig::HIGHEST); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_SVD_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tridiagonal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tridiagonal.h new file mode 100644 index 0000000000000000000000000000000000000000..f458a1934711d1764102e6dd9c1efd51649b70c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tridiagonal.h @@ -0,0 +1,40 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_TRIDIAGONAL_H_ +#define XLA_CLIENT_LIB_TRIDIAGONAL_H_ + +#include "xla/client/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace tridiagonal { + +enum SolverAlgorithm { kThomas }; + +StatusOr TridiagonalSolver(SolverAlgorithm algo, XlaOp lower_diagonal, + XlaOp main_diagonal, XlaOp upper_diagonal, + XlaOp rhs); + +StatusOr TridiagonalSolver(SolverAlgorithm algo, XlaOp diagonals, + XlaOp rhs); + +StatusOr TridiagonalMatMul(XlaOp upper_diagonal, XlaOp main_diagonal, + XlaOp lower_diagonal, XlaOp rhs); + +} // namespace tridiagonal +} // namespace xla + +#endif // XLA_CLIENT_LIB_TRIDIAGONAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tuple.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tuple.h new file mode 100644 index 0000000000000000000000000000000000000000..59cbb24f5353b90e4cd9f6b298179de3ae8f0612 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/lib/tuple.h @@ -0,0 +1,36 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LIB_TUPLE_H_ +#define XLA_CLIENT_LIB_TUPLE_H_ + +#include "xla/client/xla_builder.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" + +namespace xla { + +// Returns a ShapeTree where each index is a GetTupleElement instruction for +// that subshape of the tuple. The root index is the original argument. +StatusOr> DisassembleTuple(XlaOp tuple); + +// Assembles a tuple from a ShapeTree that contains the leaves of the tuple. +// Non-leaf elements of the ShapeTree are ignored. DisassembleTuple and +// AssembleTuple are essentially inverse operations. +XlaOp AssembleTuple(XlaBuilder* builder, ShapeTree elements); + +} // namespace xla + +#endif // XLA_CLIENT_LIB_TUPLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/local_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/local_client.h new file mode 100644 index 0000000000000000000000000000000000000000..f14b98581a9fb257a5744c8f255c1106f743410b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/local_client.h @@ -0,0 +1,236 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_LOCAL_CLIENT_H_ +#define XLA_CLIENT_LOCAL_CLIENT_H_ + +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/client/client.h" +#include "xla/client/executable_build_options.h" +#include "xla/client/xla_computation.h" +#include "xla/executable_run_options.h" +#include "xla/service/compiler.h" +#include "xla/service/executable.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/local_service.h" +#include "xla/service/maybe_owning_device_memory.h" +#include "xla/service/shaped_buffer.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +class LocalExecutable { + public: + // Low-level constructor; LocalClient::Compile() is the usual way to create + // executables. + LocalExecutable(std::unique_ptr executable, Backend* backend, + ExecutableBuildOptions build_options); + + // Run the compiled computation with the given arguments and options and + // return the result. + StatusOr Run( + absl::Span arguments, + ExecutableRunOptions run_options); + + // Similar to Run(), but allows for donating argument buffers to the + // executable. + StatusOr Run(std::vector arguments, + ExecutableRunOptions run_options); + + // Similar to Run(), but need not block the host waiting for the computation + // to complete before returning. + StatusOr RunAsync( + absl::Span arguments, + ExecutableRunOptions run_options); + + // Similar to RunAsync(), but allows for donating argument buffers to the + // executable. + StatusOr RunAsync(std::vector arguments, + ExecutableRunOptions run_options); + + // Return the options used to build the executable. + const ExecutableBuildOptions& build_options() const { return build_options_; } + + // Return the built executable. + Executable* executable() const { return executable_.get(); } + + private: + StatusOr RunAsync( + absl::Span argument_host_shapes, + std::vector arguments, ExecutableRunOptions run_options); + + // Validates that the given arguments and options satisfy various constraints + // of the computation. + // + // The given ExecutableRunOptions override any values from TF_XLA_FLAGS + // environment variable. + Status ValidateExecutionOptions(const ExecutableRunOptions& run_options, + const Backend& backend); + + // Returns a literal containing the contents of the given ShapedBuffer. + StatusOr LiteralFromShapedBuffer(const ShapedBuffer& shaped_buffer); + + StatusOr> RunHelper( + absl::Span argument_shapes, + ExecutableRunOptions run_options); + + // The ordinal of the device which this executable was compiled for. The + // executable can run on all equivalent devices (as determined by + // Backend::devices_equivalent). + int build_device_ordinal() const { return build_options_.device_ordinal(); } + + template + StatusOr AsyncCallAndBlockHostUntilDone( + absl::Span argument_shapes, + const ExecutableRunOptions& run_options, + std::function(const ExecutableRunOptions&)> async_callback) { + TF_ASSIGN_OR_RETURN(auto options_and_stream, + RunHelper(argument_shapes, run_options)); + ExecutableRunOptions options = options_and_stream.first.run_options(); + options.set_device_ordinal(-1); + StatusOr result = async_callback(options); + Status block_status = options.stream()->BlockHostUntilDone(); + TF_RETURN_IF_ERROR(result.status()); + TF_RETURN_IF_ERROR(block_status); + return result; + } + + // Compiled computation. + std::unique_ptr executable_; + + // Execution backend. + Backend* backend_ = nullptr; + + // Options used to build the executable. + const ExecutableBuildOptions build_options_; +}; + +// An XLA Client specialization for use when the client and service run in +// the same process. +class LocalClient : public Client { + public: + explicit LocalClient(LocalService* service) + : Client(service), local_service_(service) {} + + LocalClient(const LocalClient&) = delete; + void operator=(const LocalClient&) = delete; + + // Build and return LocalExecutable objects (one per partition, as specified + // by the build options). The executable is compiled using the given + // XlaComputation, argument layouts and options. + // + // The given ExecutableBuildOptions overrides any values from XLA_FLAGS + // environment variable. + StatusOr>> Compile( + const XlaComputation& computation, + absl::Span argument_layouts, + const ExecutableBuildOptions& options); + + // Same as Compile() above, but return AotCompilationResult objects (instead + // of LocalExecutable objects), which can be persisted to later load + // LocalExecutable(s) using the Load() method below. + StatusOr>> + CompileAheadOfTime(const XlaComputation& computation, + absl::Span argument_layouts, + const ExecutableBuildOptions& options); + + // Return a LocalExecutable object loaded from a serialized + // AotCompilationResult. + StatusOr> Load( + const std::string& serialized_aot_result, + const ExecutableBuildOptions& options); + + // Copy the literal data to the device with the given ordinal and return as a + // ScopedShapedBuffer. If non-null the given memory allocator is used for + // device memory allocation. If null, the default memory allocator for the + // device is used. + StatusOr LiteralToShapedBuffer( + const LiteralSlice& literal, int device_ordinal, + se::DeviceMemoryAllocator* allocator = nullptr); + + // Transfer the BorrowingLiteral to the device with the given ordinal. + StatusOr TransferToLocalServer( + const ::xla::BorrowingLiteral& literal, int device_ordinal); + + // Copy the data from the device contained in the given ShapedBuffer and + // return as a Literal. + StatusOr ShapedBufferToLiteral(const ShapedBuffer& shaped_buffer); + + // Converts a GlobalDataHandle into a pointer to a ShapedBuffer that's valid + // as long as the handle is valid. + StatusOr GlobalDataToShapedBuffer( + const GlobalDataHandle& data, int replica_number); + + // Transfer the given literal to the infeed queue of the given device. + // TODO(b/69670845): Remove the 'Local' from the name when LocalClient does + // not inherit from Client and there is no possibility of confusion with + // Client::TransferToInfeed. + Status TransferToInfeedLocal(const LiteralSlice& literal, int device_ordinal); + + // Transfer and return a value from the outfeed of the given device. The + // shape of the object to transfer is determined by `literal`'s shape. + // TODO(b/69670845): Remove the 'Local' from the name when LocalClient does + // not inherit from Client and there is no possibility of confusion with + // Client::TransferFromOutfeed. + Status TransferFromOutfeedLocal(int device_ordinal, + MutableBorrowingLiteral literal); + + // Returns the device ordinal that corresponds to the given replica number. + // + // This returns an error if there is not a one-to-one correspondence of + // replicas to device ordinals, but is useful as a short term mechanism for + // the "easy" case where a single replica is a single device. + StatusOr ReplicaNumberToDeviceOrdinal(int replica_number); + + // Returns the platform that the underlying service targets. + se::Platform* platform() const; + + // Returns the number of devices on the system of the service platform + // type. Not all devices may be supported by the service (see + // device_ordinal_supported method). + int device_count() const; + + // Returns the default device ordinal that the service will run computations + // on if no device ordinal is specified in execute options. + int default_device_ordinal() const; + + // Returns whether the device with the given ordinal can be used by the + // service to execute computations. Not all devices of a particular platform + // may be usable by the service (eg, a GPU with insufficient CUDA compute + // capability). + bool device_ordinal_supported(int device_ordinal) const; + + // Returns the backend used to execute computations. + const Backend& backend() const; + Backend* mutable_backend(); + + LocalService* local_service() { return local_service_; } + + private: + LocalService* local_service_; +}; + +} // namespace xla + +#endif // XLA_CLIENT_LOCAL_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/padding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/padding.h new file mode 100644 index 0000000000000000000000000000000000000000..38a55c3a5816deaa3210da9979d7166dc94a800a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/padding.h @@ -0,0 +1,66 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_PADDING_H_ +#define XLA_CLIENT_PADDING_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { + +// Describes the padding applied for a windowed operation like +// convolution, where a window is placed inside a base area. +enum class Padding { + // Make the output have the same dimensions as the base area. For + // example, for a 3x3 base area and a 2x2 window, the output will be + // 3x3, so that requires padding the 3x3 base area to 4x4. + kSame, + + // Use no padding. For example, for a 4x4 base area and a 2x2 + // window, the output will be 3x3. + kValid, +}; + +// Validates that the slices are acceptable for determining padding -- this can +// be used to check the preconditions of MakePadding below to produce an error +// message that can be returned to the user. +Status ValidatePaddingValues(absl::Span input_dimensions, + absl::Span window_dimensions, + absl::Span window_strides); + +// Returns the padding needed for the base area, given the base area dimensions, +// window dimensions, strides, and the type of padding. +// +// If v is the returned vector, then for each dimension number i, +// v[i].first is the padding to the left (i.e. in the direction of +// lower indices) and v[i].second is the padding to the right (i.e. in +// the direction of higher indices). +// +// Precondition: The number of dimensions (i.e., rank) in input_dimensions, +// window_dimensions, and strides must match, which is equal to the number +// of elements in the result vector. +std::vector> MakePadding( + absl::Span input_dimensions, + absl::Span window_dimensions, + absl::Span window_strides, Padding padding); + +} // namespace xla + +#endif // XLA_CLIENT_PADDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/sharding_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/sharding_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..b4f2424458df52c01239a145e4777e3e43440aec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/sharding_builder.h @@ -0,0 +1,62 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_SHARDING_BUILDER_H_ +#define XLA_CLIENT_SHARDING_BUILDER_H_ + +#include + +#include "xla/array.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace sharding_builder { +// A shaped array used to describe the assignment of tiles to devices. +using TileAssignment = Array; + +// Creates a replicated sharding - replicate a tensor on every device. +OpSharding Replicate(); + +// Creates a manual sharding - the partitioner will not change the shape. +OpSharding Manual(); + +// Creates a sharding that assigns a tensor to just one device. +OpSharding AssignDevice(int device); + +// Creates a tiled sharding with the given tile shape and assignment of tiles +// to devices. +// +// If tile_shape is not evenly divisible by the number of devices in +// tile_assignment, operations behave as if implicit padding had been inserted. +// The value of this padding is undefined. +OpSharding Tile(const Shape& tile_shape, const TileAssignment& tile_assignment); + +// Creates a sharding in one dimension, with the given tile shape which must +// be rank 1 and using devices [0..num_tiles). +// +// This is simply a convenience wrapper for Tile(). +OpSharding Tile1D(const Shape& tile_shape, int64_t num_tiles); + +// Creates a tuple sharding from the given ShapeTree of element shardings. +OpSharding Tuple(const ShapeTree& shardings); + +} // namespace sharding_builder +} // namespace xla + +#endif // XLA_CLIENT_SHARDING_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/value_inference.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/value_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..47f9f7129ed9f47bda8cf9540be19e44a73bfd76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/value_inference.h @@ -0,0 +1,112 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_CLIENT_VALUE_INFERENCE_H_ +#define XLA_CLIENT_VALUE_INFERENCE_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/client/xla_builder.h" +#include "xla/hlo/evaluator/hlo_evaluator.h" +#include "xla/hlo/ir/dfs_hlo_visitor.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" + +namespace xla { +// OptionalLiteral is an augmented literal class which returns optional +// values for each index (the value can be either valid or invalid). The +// implementation keeps two literals, a value literal, holding both the valid +// and garabage value, and a masking literal representing if a value is valid or +// garbage. +class OptionalLiteral { + public: + explicit OptionalLiteral(Literal value, Literal mask) + : value_(std::move(value)), mask_(std::move(mask)) {} + + template + std::optional Get(absl::Span element_index, + ShapeIndex shape_index = {}) const { + if (mask_.Get(element_index, shape_index)) { + return std::nullopt; + } else { + return value_.Get(element_index, shape_index); + } + } + + // Returns true if all values in this literal slice are value. + bool AllValid() { return mask_.IsAll(0); } + + // Get value out of this slice if all values are valid. Otherwise returns + // nullopt. + std::optional GetValue() { + if (!AllValid()) { + return std::nullopt; + } + return LiteralSlice(value_); + } + + private: + Literal value_; + Literal mask_; +}; + +enum ValueInferenceMode { + // Inference the constant value itself. + kValue = 0, + // Inference upper-bound and lower-bound of the value. Bounds are inclusive. + kUpperBound, + kLowerBound, +}; + +class ValueInference { + public: + // ValueInference analyzes values in XlaOp answers following questions: + // - What's the upper-bound of each value in a tensor. + // - What's the lower-bound of each value in a tensor. + // - What's the constant value of each tensor. + // - Whether or not each value in a tensor is dynamic. + explicit ValueInference(XlaBuilder* builder) : builder_(builder) { + CHECK(builder_); + } + StatusOr AnalyzeIsDynamic(XlaOp op); + // Returns an OptionalLiteral. Each individual value of the literal is + // the concrete constant value if it can be inferred, otherwise a nullopt. + StatusOr AnalyzeConstant(XlaOp op, ValueInferenceMode mode); + + // Returns underlying xla builder. + XlaBuilder* builder() { return builder_; } + + private: + // Given an op handle, returns a simplified version of the handle inside a + // int64_t Literal. If the a -1 value for the handle means invalid + // simplification and the result shouldn't be used. + StatusOr SimplifyOp(int64_t handle); + + // Perform CSE on a given handle, and return an equivalent handle if seen + // before. Otherwise, returns nullopt. + StatusOr> CseOpHandle(int64_t handle); + XlaBuilder* builder_; + HloEvaluator evaluator_; + // A map from instruction_hash to handle that helps perform CSE. + absl::flat_hash_map cse_map_; +}; +} // namespace xla + +#endif // XLA_CLIENT_VALUE_INFERENCE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..00e288c6ca1ce3a1f33ce5f3426c8b25e85732d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_builder.h @@ -0,0 +1,2932 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_XLA_BUILDER_H_ +#define XLA_CLIENT_XLA_BUILDER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/client/padding.h" +#include "xla/client/xla_computation.h" +#include "xla/comparison_util.h" +#include "xla/hlo/ir/dynamic_parameter_binding.h" +#include "xla/hlo/ir/hlo_input_output_alias_config.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/stacktrace.h" + +namespace xla { + +class XlaBuilder; +class XlaOp; +class HloInstruction; + +namespace internal { + +struct XlaBuilderFriend { + static XlaOp BuildAddDependency(XlaBuilder* builder, XlaOp operand, + XlaOp token, const Shape& shape); + + static std::pair BuildAsyncStart( + XlaBuilder* builder, absl::Span operands, + std::string execution_thread, int64_t group_id, + const XlaComputation& called_computation, const Shape& shape); + static std::pair BuildAsyncStart( + XlaBuilder* builder, absl::Span operands, + std::string execution_thread, const XlaComputation& called_computation, + const Shape& shape); + static XlaOp BuildAsyncUpdate(XlaBuilder* builder, XlaOp operands, + std::string execution_thread, int64_t group_id, + int64_t called_computation, const Shape& shape); + static XlaOp BuildAsyncUpdate(XlaBuilder* builder, XlaOp operands, + std::string execution_thread, + int64_t called_computation, const Shape& shape); + static XlaOp BuildAsyncDone(XlaBuilder* builder, XlaOp operands, + std::string execution_thread, int64_t group_id, + int64_t called_computation, const Shape& shape); + static XlaOp BuildAsyncDone(XlaBuilder* builder, XlaOp operands, + std::string execution_thread, + int64_t called_computation, const Shape& shape); + + static XlaOp BuildAllGatherStart( + XlaBuilder* builder, XlaOp operand, int64_t all_gather_dimension, + int64_t shard_count, absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + static XlaOp BuildAllGatherDone(XlaBuilder* builder, XlaOp operands, + const Shape& shape); + + static XlaOp BuildAllReduceStart( + XlaBuilder* builder, XlaOp operand, const XlaComputation& computation, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + static XlaOp BuildAllReduceDone(XlaBuilder* builder, XlaOp operands, + const Shape& shape); + + static XlaOp BuildCollectivePermuteStart( + XlaBuilder* builder, XlaOp operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id = std::nullopt); + static XlaOp BuildCollectivePermuteDone(XlaBuilder* builder, XlaOp operands, + const Shape& shape); + + static XlaOp BuildCopyStart( + XlaBuilder* builder, XlaOp operand, + std::optional cross_program_prefetch_index = std::nullopt); + static XlaOp BuildCopyDone(XlaBuilder* builder, XlaOp operand, + const Shape& shape); + + static XlaOp BuildFusion( + XlaBuilder* builder, absl::Span operands, + absl::string_view fusion_kind, const XlaComputation& fused_computation, + absl::Span>> + output_operand_aliasing = {}); + + static XlaOp BuildBitcast(XlaBuilder* builder, XlaOp operand, + const Shape& shape); + + static XlaOp BuildPartitionId(XlaBuilder* builder, const Shape& shape); + + static XlaOp BuildSend(XlaBuilder* builder, XlaOp operand, XlaOp token, + const ChannelHandle& handle, bool is_host_transfer); + static XlaOp BuildSendDone(XlaBuilder* builder, XlaOp operand, + const ChannelHandle& handle, + bool is_host_transfer); + + static XlaOp BuildRecv(XlaBuilder* builder, XlaOp token, const Shape& shape, + const ChannelHandle& handle, bool is_host_transfer); + static XlaOp BuildRecvDone(XlaBuilder* builder, XlaOp token, + const Shape& shape, const ChannelHandle& handle, + bool is_host_transfer); + + static XlaOp BuildDomain(XlaBuilder* builder, XlaOp operand, OpSharding entry, + OpSharding exit, const Shape& shape); + + static XlaOp BuildRngGetAndUpdateState(XlaBuilder* builder, int64_t delta, + const Shape& shape); + + static HloInstructionProto* GetInstruction(XlaOp op); + static HloInstructionProto* GetInstructionByHandle(XlaBuilder* builder, + int64_t handle); +}; + +} // namespace internal + +// This represents an instruction that has been enqueued using the XlaBuilder. +// This is used to pass to subsequent computations that depends upon the +// instruction as an operand. +class XlaOp { + public: + XlaOp() : handle_(-1), builder_(nullptr) { + static_assert(std::is_trivially_destructible::value, + "XlaOp should be trivially destructible"); + } + ~XlaOp() = default; + + XlaOp(const XlaOp& other) = default; + XlaOp& operator=(const XlaOp& other) = default; + + // Precondition: !IsUninitialized(). + // + // It's very common to do foo.builder()->bar(). Without this precondition, if + // foo.builder() is null, the call to bar will segfault at some point possibly + // deep in the callstack when we finally dereference `this`. The precondition + // lets us avoid this tricky-to-debug problem. + XlaBuilder* builder() const { + CHECK(builder_ != nullptr); + return builder_; + } + + // Returns true if the XlaOp represents valid, non-erroneous value. + bool valid() const { return handle_ >= 0; } + + // Returns true if the XlaOp was created by the XlaOp() constructor and + // not returned by a builder. + bool IsUninitialized() const { return builder_ == nullptr; } + + bool IsIdenticalTo(XlaOp rhs) const { + return handle_ == rhs.handle_ && builder_ == rhs.builder_; + } + + friend std::ostream& operator<<(std::ostream& out, XlaOp op) { + out << op.handle(); + return out; + } + + private: + explicit XlaOp(XlaBuilder* builder) : handle_(-1), builder_(builder) {} + XlaOp(int64_t handle, XlaBuilder* builder) + : handle_(handle), builder_(builder) {} + + int64_t handle() const { return handle_; } + + friend class XlaBuilder; + friend class ValueInference; + friend struct internal::XlaBuilderFriend; + + // < 0 means "invalid handle". + int64_t handle_; + + // Not owned. Non-null for any handle returned by XlaBuilder, even if the + // handle is invalid. + XlaBuilder* builder_; +}; + +// Arithmetic operator overloads for the XlaOp type. +XlaOp operator-(XlaOp x); +XlaOp operator+(XlaOp x, XlaOp y); +XlaOp operator-(XlaOp x, XlaOp y); +XlaOp operator*(XlaOp x, XlaOp y); +XlaOp operator/(XlaOp x, XlaOp y); +XlaOp operator%(XlaOp x, XlaOp y); + +// Bitwise operator overloads for the XlaOp type. +XlaOp operator~(XlaOp x); +XlaOp operator&(XlaOp x, XlaOp y); +XlaOp operator|(XlaOp x, XlaOp y); +XlaOp operator^(XlaOp x, XlaOp y); +XlaOp operator<<(XlaOp x, XlaOp y); +// Performs a right arithmetic shift if 'x' is a signed type, otherwise performs +// a right logical shift. +XlaOp operator>>(XlaOp x, XlaOp y); + +// We don't overload the relational operators (==, !=, <, <=, >, >=) because the +// semantics might be surprising since their result types are usually 'bool'. +// Further programmers may expect == to be a structural equality. +// We also choose not to overload any of the mutating operators (e.g., +=, -=) +// because the semantics might be misleading — XLA computations are immutable. + +// A convenient interface for building up computations. +// +// Thread-compatible. +class XlaBuilder { + public: + // computation_name: name to use for the built computation. + explicit XlaBuilder(const std::string& computation_name); + + XlaBuilder(const XlaBuilder&) = delete; + XlaBuilder& operator=(const XlaBuilder&) = delete; + + virtual ~XlaBuilder(); + + // Returns the computation name. + const std::string& name() const { return name_; } + + // Sets OpMetadata that will be added to all instructions until cleared. + // + // OpMetadata is often applied to a series of XLA HLO instructions. As a + // result, OpMetadata is set on the computation builder. All subsequent + // instructions generated via this computation builder will have the same + // OpMetadata attached until a call to ClearOpMetadata. + void SetOpMetadata(OpMetadata metadata) { metadata_ = std::move(metadata); } + + // Swaps the passed op metadata with the ones currently set. + // + // Returns the old op metadata. + OpMetadata SwapOpMetadata(OpMetadata metadata) { + OpMetadata old_metadata = std::move(metadata_); + metadata_ = std::move(metadata); + return old_metadata; + } + + // Similar to SetOpMetadata, but only set the metadata for the next op. + void SetOneShotOpMetadata(OpMetadata metadata) { + one_shot_metadata_ = std::move(metadata); + } + + // Clears the HloMetadata state. + void ClearOpMetadata() { metadata_.Clear(); } + + // Sets an OpSharding that will be attached to all instructions until cleared. + void SetSharding(const OpSharding& sharding) { sharding_ = sharding; } + + // Sets the FrontendAttributes that will be added to all instructions until + // cleared. + // + // FrontendAttributes are often applied to a series of XLA HLO instructions. + // As a result they are set on the computation builder and all the + // instructions generated via the computation builder will have the same + // frontend attributes attached to them. + virtual void SetFrontendAttributes( + const FrontendAttributes& frontend_attributes) { + frontend_attributes_ = frontend_attributes; + } + + // Swap the passed FrontendAttributes with the ones currently set. + // + // Return the old attributes. + FrontendAttributes SwapFrontendAttributes( + const FrontendAttributes& frontend_attributes) { + FrontendAttributes old_attributes = std::move(frontend_attributes_); + frontend_attributes_ = frontend_attributes; + return old_attributes; + } + + // Returns the FrontendAttributes that will be attached to all instructions. + const FrontendAttributes& frontend_attributes() const { + return frontend_attributes_; + } + + // Clears all the frontend attributes. + void ClearFrontendAttributes() { frontend_attributes_.Clear(); } + + // Clears the sharding. Ops will be sharded according to the default placement + // policy. + void ClearSharding() { sharding_ = std::nullopt; } + + // Returns the OpSharding that will be attached to all instructions. + const std::optional& sharding() const { return sharding_; } + + // Sets the builder to a mode where it will die immediately when an error is + // encountered, rather than producing it in a deferred fashion when Build() is + // called (which is the default). + void set_die_immediately_on_error(bool enabled) { + die_immediately_on_error_ = enabled; + } + + // Default dimension numbers used for a 2D convolution. + static constexpr int64_t kConvBatchDimension = 0; + static constexpr int64_t kConvFeatureDimension = 1; + static constexpr int64_t kConvFirstSpatialDimension = 2; + static constexpr int64_t kConvSecondSpatialDimension = 3; + static constexpr int64_t kConvKernelOutputDimension = 0; + static constexpr int64_t kConvKernelInputDimension = 1; + static constexpr int64_t kConvKernelFirstSpatialDimension = 2; + static constexpr int64_t kConvKernelSecondSpatialDimension = 3; + + // Creates a default ConvolutionDimensionNumbers. For a 2D convolution, for + // the input operand {batch, feature, height, width} = {0, 1, 2, 3} and for + // the kernel operand + // {output_feature, input_feature, height, width} = {0, 1, 2, 3}. + static ConvolutionDimensionNumbers CreateDefaultConvDimensionNumbers( + int num_spatial_dims = 2); + + // Returns an error if the convolution dimension numbers have conflicts. + static Status Validate(const ConvolutionDimensionNumbers& dnum); + + // Returns a new XlaBuilder whose resultant Computation is used only by this + // XlaBuilder. The sub-XlaBuilder has the same die_immediately_on_error + // behavior as the parent. + std::unique_ptr CreateSubBuilder( + const std::string& computation_name); + + // Builds the computation with the requested operations, or returns a non-ok + // status. Note that all ops that have been enqueued will be moved to the + // computation being returned. The root of the computation will be the last + // added operation. + // + // `remove_dynamic_dimensions` tells the builder whether to remove the + // dynamic dimensions information in all ops. + // + // TODO(b/121223198): Delete `remove_dynamic_dimensions` and keeps the + // dynamic dimensions information when XLA backend can handle dynamic + // dimensions. + StatusOr Build(bool remove_dynamic_dimensions = false); + + // Overload of Build which specifies a particular root instruction for the + // computation. + StatusOr Build(XlaOp root, + bool remove_dynamic_dimensions = false); + + // Builds the computation with the requested operations, or notes an error in + // the parent XlaBuilder and returns an empty computation if building failed. + // This function is intended to be used where the returned XlaComputation is + // only used by the parent XlaBuilder and hence further operation on the + // returned XlaComputation will simply be error'ed out if an error occurred + // while building this computation. If the built computation is to be used by + // a XlaBuilder other than the parent XlaBuilder then Build() should be used + // instead. + XlaComputation BuildAndNoteError(); + + // Returns a subgraph that roots on the given root. If the root is not a + // compile-time constant (see `IsConstant`), returns an error. + // + // This will copy the needed ops/computations to the subgraph. + StatusOr BuildConstantSubGraph( + XlaOp root_op, bool dynamic_dimension_is_minus_one = false); + + // Returns the first error that was encountered while building the + // computation. When an error is encountered, by default we return a vacuous + // XlaOp and inform the user of the error that occurred while + // building the computation when they make a final call to Build(). + // + // See also set_die_immediately_on_error(). + Status first_error() const { return first_error_; } + + // Returns the current status of the builder, complete with the stack trace + // information. + Status GetCurrentStatus() const; + + // Returns the shape of the given op. + StatusOr GetShape(XlaOp op) const; + + // Returns the shape of the given op. + virtual StatusOr GetShapePtr(XlaOp op) const; + + // Returns the (inferred) result for the current computation's shape. This + // assumes the root instruction is the last added instruction. + StatusOr GetProgramShape() const; + + // Returns the (inferred) result for the current computation's shape using the + // given operation as the root. + StatusOr GetProgramShape(XlaOp root) const; + + // Reports an error to the builder, by + // * storing it internally and capturing a backtrace if it's the first error + // (this deferred value will be produced on the call to + // Build()/GetShape()/...) + // * dying if die_immediately_on_error_ is true. + // Returns an XlaOp with an invalid handle but a valid builder. This value can + // be returned in place of a value in APIs that return an XlaOp. + XlaOp ReportError(const Status& error); + + // A helper function that converts a StatusOr into an XlaOp. + // If the Status was an error, reports the error to builder and returns an + // invalid XlaOp handle. + XlaOp ReportErrorOrReturn(const StatusOr& op); + + // A helper function that runs a function that returns a StatusOr and + // returns an XlaOp. + XlaOp ReportErrorOrReturn(absl::FunctionRef()> op_creator); + + // Returns true if 'operand' is a compile-time constant. A compile-time + // constant does not depend on any parameters, or on stateful operators such + // as `RngNormal` or `Infeed`. + // + // This tests whether a computation is a compile-time constant without + // evaluating the computation. + StatusOr IsConstant(XlaOp operand) const; + + // Adds a new input/output alias. Since the input/output shape information are + // not available until the computation is built, any eventual error in the + // arguments of this API will be detected only at computation Build() time. + // + // Note: Except when 'must-alias' is true, alias is assumed to be 'may-alias' + // and only donated buffer at runtime will be aliased with output. If a buffer + // is not donated at runtime, a copy will be inserted by XLA to prevent buffer + // clobbering. + void SetUpAlias(const ShapeIndex& output_index, int64_t param_number, + const ShapeIndex& param_index, + HloInputOutputAliasConfig::AliasKind kind = + HloInputOutputAliasConfig::AliasKind::kMayAlias) { + input_output_aliases_.push_back( + {output_index, param_number, param_index, kind}); + } + + // Describes an input/output alias as inserted by the SetUpAlias() API. + struct InputOutputAlias { + // Specifies the index of the aliased buffer in the result tuple. + ShapeIndex output_index; + // Specifies the parameter containing the buffer to be aliased. + int64_t param_number; + // Specifies the index of the aliased buffer in the parameter. + ShapeIndex param_index; + // Specifies if the alias is a must alias or may alias. + HloInputOutputAliasConfig::AliasKind kind; + }; + + // Adds a new buffer donor. The donated buffer may be paired with any valid + // output. On the contrary, the buffer aliasing bonds the input output pair. + // The input can only donate the buffer to the paired output. + void AddBufferDonor(int64_t param_number, const ShapeIndex& param_index) { + buffer_donors_.insert({param_number, param_index}); + } + + // Looks up the HloInstruction and sets the frontend attribute "attribute" to + // "value". + // + // If the attribute already existed then its value is updated. + // + // Note: the attribute is only added to the HloInstruction, not to the + // builder. + Status SetInstructionFrontendAttribute(XlaOp op, std::string attribute, + std::string value); + + // Returns shapes for the operands. + StatusOr> GetOperandShapes( + absl::Span operands) const; + + // Converts the op to string for the ease of debugging. + std::string OpToString(XlaOp op) const; + + private: + void ToStringHelper(std::string* out, int ident, int64_t op_handle) const; + + // Build helper which takes the id of the root operation.. + StatusOr Build(int64_t root_id, + bool remove_dynamic_dimensions); + + // Description for the methods below can be found in the corresponding public + // functions section in this file. + + XlaOp Parameter(int64_t parameter_number, const Shape& shape, + const std::string& name, + const std::vector& replicated_at_leaf_buffers); + XlaOp Parameter(int64_t parameter_number, const Shape& shape, + const std::string& name) { + std::vector empty_bools; + return Parameter(parameter_number, shape, name, empty_bools); + } + + virtual XlaOp ConstantLiteral(const LiteralSlice& literal); + + XlaOp Broadcast(XlaOp operand, absl::Span broadcast_sizes); + + XlaOp BroadcastInDim(XlaOp operand, absl::Span out_dim_size, + absl::Span broadcast_dimensions); + + XlaOp Pad(XlaOp operand, XlaOp padding_value, + const PaddingConfig& padding_config); + XlaOp PadInDim(XlaOp operand, XlaOp padding_value, int64_t dimno, + int64_t pad_lo, int64_t pad_hi); + + virtual StatusOr PadInternal(const Shape& shape, XlaOp operand, + XlaOp padding_value, + const PaddingConfig& padding_config); + + XlaOp Reshape(XlaOp operand, absl::Span dimensions, + absl::Span new_sizes, + int64_t inferred_dimension = -1); + + XlaOp Reshape(XlaOp operand, absl::Span new_sizes, + int64_t inferred_dimension = -1); + + XlaOp Reshape(const Shape& shape, XlaOp operand, + int64_t inferred_dimension = -1); + + XlaOp DynamicReshape(XlaOp operand, absl::Span dim_sizes, + absl::Span new_size_bounds, + const std::vector& dims_are_dynamic); + + XlaOp Collapse(XlaOp operand, absl::Span dimensions); + + XlaOp Slice(XlaOp operand, absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + virtual StatusOr SliceInternal(const Shape& shape, XlaOp operand, + absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + virtual XlaOp SliceInDim(XlaOp operand, int64_t start_index, + int64_t limit_index, int64_t stride, int64_t dimno); + + XlaOp DynamicSlice(XlaOp operand, absl::Span start_indices, + absl::Span slice_sizes); + virtual StatusOr DynamicSliceInternal( + const Shape& shape, XlaOp operand, absl::Span start_indices, + absl::Span slice_sizes); + + XlaOp DynamicUpdateSlice(XlaOp operand, XlaOp update, + absl::Span start_indices); + virtual StatusOr DynamicUpdateSliceInternal( + const Shape& shape, XlaOp operand, XlaOp update, + absl::Span start_indices); + + XlaOp ConcatInDim(absl::Span operands, int64_t dimension); + virtual StatusOr ConcatInDimInternal(const Shape& shape, + absl::Span operands, + int64_t dimension); + + XlaOp Select(XlaOp pred, XlaOp on_true, XlaOp on_false); + + XlaOp Tuple(absl::Span elements); + virtual StatusOr TupleInternal(const Shape& shape, + absl::Span elements); + + XlaOp GetTupleElement(XlaOp tuple_data, int64_t index); + virtual StatusOr GetTupleElementInternal(const Shape& shape, + XlaOp tuple_data, + int64_t index); + + XlaOp Dot(XlaOp lhs, XlaOp rhs, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp DotGeneral( + XlaOp lhs, XlaOp rhs, const DotDimensionNumbers& dimension_numbers, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp Conv( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + Padding padding, int64_t feature_group_count = 1, + int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp ConvWithGeneralPadding( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp ConvWithGeneralDimensions( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + Padding padding, const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp ConvGeneral( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + + XlaOp ConvGeneralDilated( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt, + std::optional> window_reversal = std::nullopt); + + XlaOp DynamicConvForward( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + + XlaOp DynamicConvInputGrad( + XlaOp input_sizes, XlaOp lhs, XlaOp rhs, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + + XlaOp DynamicConvKernelGrad( + XlaOp activations, XlaOp gradients, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + + StatusOr DynamicConvInstruction( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + + virtual StatusOr ConvGeneralDilatedInternal( + const Shape& shape, XlaOp lhs, XlaOp rhs, const Window& window, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config); + + XlaOp Fft(XlaOp operand, FftType fft_type, + absl::Span fft_length); + virtual StatusOr FftInternal(const Shape& shape, XlaOp operand, + FftType fft_type, + absl::Span fft_length); + + virtual StatusOr TriangularSolveInternal( + const Shape& shape, XlaOp a, XlaOp b, TriangularSolveOptions options); + + virtual StatusOr CholeskyInternal(const Shape& shape, XlaOp a, + bool lower); + + XlaOp Infeed(const Shape& shape, const std::string& config = ""); + XlaOp InfeedWithToken(XlaOp token, const Shape& shape, + const std::string& config); + virtual StatusOr InfeedWithTokenInternal( + const Shape& infeed_instruction_shape, XlaOp token, + const std::string& config); + + void Outfeed(XlaOp operand, const Shape& shape_with_layout, + const std::string& outfeed_config); + XlaOp OutfeedWithToken(XlaOp operand, XlaOp token, + const Shape& shape_with_layout, + const std::string& outfeed_config); + virtual StatusOr OutfeedWithTokenInternal( + XlaOp operand, XlaOp token, const Shape& shape_with_layout, + const std::string& outfeed_config); + XlaOp Call(const XlaComputation& computation, + absl::Span operands); + + XlaOp CustomCall( + const std::string& call_target_name, absl::Span operands, + const Shape& shape_with_layout, const std::string& opaque, + std::optional> operand_shapes_with_layout, + bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, std::optional window, + std::optional dnums, + CustomCallSchedule schedule, CustomCallApiVersion api_version); + + // Internal version of CustomCall without computation that doesn't do op + // specific error handling and expects arguments to be legal. CustomCall + // method above calls this method after error handling. + virtual StatusOr CustomCallInternal( + const std::string& call_target_name, absl::Span operands, + const XlaComputation* computation, const Shape& shape_with_layout, + const std::string& opaque, + std::optional> operand_shapes_with_layout, + bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, std::optional window, + std::optional dnums, + CustomCallSchedule schedule, CustomCallApiVersion api_version); + + // TODO(b/239474321) Remove this overload as it has simply led to code + // duplication. + XlaOp CustomCall( + const std::string& call_target_name, absl::Span operands, + const XlaComputation& computation, const Shape& shape_with_layout, + const std::string& opaque, + std::optional> operand_shapes_with_layout, + bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, CustomCallSchedule schedule, + CustomCallApiVersion api_version); + + XlaOp OptimizationBarrier(XlaOp operand); + + XlaOp Reduce(XlaOp operand, XlaOp init_value, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + + XlaOp Reduce(absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + + virtual StatusOr ReduceInternal( + const Shape& shape, absl::Span all_operands, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + + XlaOp ReduceAll(XlaOp operand, XlaOp init_value, + const XlaComputation& computation); + + XlaOp ReduceWindow(XlaOp operand, XlaOp init_value, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, Padding padding); + + XlaOp ReduceWindow(absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, Padding padding); + + XlaOp ReduceWindowWithGeneralPadding( + absl::Span operands, absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); + StatusOr ReduceWindowInternal( + absl::Span operands, absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); + virtual StatusOr ReduceWindowInternal( + const Shape& shape, XlaOp operand, XlaOp init_value, + const XlaComputation& computation, Window window); + XlaOp CrossReplicaSum(XlaOp operand, + absl::Span replica_groups = {}); + + XlaOp AllGather(XlaOp operand, int64_t all_gather_dimension, + int64_t shard_count, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + + XlaOp AllReduce(XlaOp operand, const XlaComputation& computation, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& shape_with_layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + + XlaOp ReduceScatter( + XlaOp operand, const XlaComputation& computation, + int64_t scatter_dimension, int64_t shard_count, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + + XlaOp AllToAll(XlaOp operand, int64_t split_dimension, + int64_t concat_dimension, int64_t split_count, + absl::Span replica_groups, + const std::optional& layout = std::nullopt, + const std::optional& channel_id = std::nullopt); + + XlaOp AllToAllTuple( + absl::Span operands, + absl::Span replica_groups, + const std::optional& layout, + const std::optional& channel_id = std::nullopt); + + XlaOp AllToAllTuple( + XlaOp operand, int64_t split_dimension, int64_t concat_dimension, + int64_t split_count, absl::Span replica_groups, + const std::optional& layout, + const std::optional& channel_id = std::nullopt); + + XlaOp CollectivePermute( + XlaOp operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id = std::nullopt); + + XlaOp ReplicaId(); + + XlaOp SelectAndScatter(XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + Padding padding, XlaOp source, XlaOp init_value, + const XlaComputation& scatter); + + XlaOp SelectAndScatterWithGeneralPadding( + XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span> padding, XlaOp source, + XlaOp init_value, const XlaComputation& scatter); + + StatusOr SelectAndScatterInternal( + XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span> padding, XlaOp source, + XlaOp init_value, const XlaComputation& scatter); + + virtual XlaOp Iota(const Shape& shape, int64_t iota_dimension); + + XlaOp Iota(PrimitiveType type, int64_t size); + + XlaOp ConvertElementType(XlaOp operand, PrimitiveType new_element_type); + + XlaOp BitcastConvertType(XlaOp operand, PrimitiveType new_element_type); + virtual StatusOr BitcastConvertTypeInternal(const Shape& shape, + XlaOp operand); + + XlaOp StochasticConvertType(XlaOp operand, XlaOp random, + PrimitiveType new_element_type); + + XlaOp Transpose(XlaOp operand, absl::Span permutation); + virtual StatusOr TransposeInternal( + const Shape& shape, XlaOp operand, absl::Span permutation); + + XlaOp Rev(XlaOp operand, absl::Span dimensions); + virtual StatusOr RevInternal(const Shape& shape, XlaOp operand, + absl::Span dimensions); + + XlaOp Sort(absl::Span operands, const XlaComputation& comparator, + int64_t dimension = -1, bool is_stable = false); + virtual StatusOr SortInternal(const Shape& shape, + absl::Span operands, + const XlaComputation& comparator, + int64_t dimension, bool is_stable); + + XlaOp Clamp(XlaOp min, XlaOp operand, XlaOp max); + + XlaOp Map(absl::Span operands, const XlaComputation& computation, + absl::Span dimensions, + absl::Span static_operands = {}); + + XlaOp RngNormal(XlaOp mu, XlaOp sigma, const Shape& shape); + + XlaOp RngUniform(XlaOp a, XlaOp b, const Shape& shape); + + XlaOp RngBitGenerator(RandomAlgorithm algorithm, XlaOp initial_state, + const Shape& shape); + // Internal variant for the op with the full result shape containing both data + // and state shape as a tuple. + virtual StatusOr RngBitGeneratorInternal( + const Shape& full_result_shape, RandomAlgorithm algorithm, + XlaOp initial_state); + + XlaOp While(const XlaComputation& condition, const XlaComputation& body, + XlaOp init); + virtual StatusOr WhileInternal(const Shape& shape, + const XlaComputation& condition, + const XlaComputation& body, XlaOp init); + + XlaOp Conditional(XlaOp predicate, XlaOp true_operand, + const XlaComputation& true_computation, XlaOp false_operand, + const XlaComputation& false_computation); + + XlaOp Conditional(XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + + XlaOp ReducePrecision(XlaOp operand, int exponent_bits, int mantissa_bits); + virtual StatusOr ReducePrecisionInternal(const Shape& shape, + XlaOp operand, + int exponent_bits, + int mantissa_bits); + + XlaOp Gather(XlaOp input, XlaOp start_indices, + const GatherDimensionNumbers& dimension_numbers, + absl::Span slice_sizes, + bool indices_are_sorted = false); + + virtual StatusOr GatherInternal( + const Shape& shape, XlaOp input, XlaOp start_indices, + const GatherDimensionNumbers& dimension_numbers, + absl::Span slice_sizes, bool indices_are_sorted); + + XlaOp Scatter(XlaOp input, XlaOp scatter_indices, XlaOp updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted = false, bool unique_indices = false); + XlaOp Scatter(absl::Span inputs, XlaOp scatter_indices, + absl::Span updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted = false, bool unique_indices = false); + + virtual StatusOr ScatterInternal( + const Shape& shape, absl::Span inputs, XlaOp scatter_indices, + absl::Span updates, const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, bool indices_are_sorted, + bool unique_indices); + + void Send(XlaOp operand, const ChannelHandle& handle); + XlaOp SendWithToken(XlaOp operand, XlaOp token, const ChannelHandle& handle); + + XlaOp SendToHost(XlaOp operand, XlaOp token, const Shape& shape_with_layout, + const ChannelHandle& handle); + + XlaOp RecvFromHost(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + + virtual XlaOp CreateToken(); + + XlaOp AfterAll(absl::Span tokens); + + XlaOp Recv(const Shape& shape, const ChannelHandle& handle); + XlaOp RecvWithToken(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + + XlaOp BatchNormTraining(XlaOp operand, XlaOp scale, XlaOp offset, + float epsilon, int64_t feature_index); + + XlaOp BatchNormInference(XlaOp operand, XlaOp scale, XlaOp offset, XlaOp mean, + XlaOp variance, float epsilon, + int64_t feature_index); + + XlaOp BatchNormGrad(XlaOp operand, XlaOp scale, XlaOp batch_mean, + XlaOp batch_var, XlaOp grad_output, float epsilon, + int64_t feature_index); + + XlaOp GetDimensionSize(XlaOp operand, int64_t dimension); + + XlaOp SetDimensionSize(XlaOp operand, XlaOp val, int64_t dimension); + + virtual StatusOr SetDimensionSizeInternal(const Shape& shape, + XlaOp operand, XlaOp val, + int64_t dimension); + + XlaOp RemoveDynamicDimension(XlaOp operand, int64_t dimension); + + virtual StatusOr AddInstruction(HloInstructionProto&& instr, + HloOpcode opcode, + absl::Span operands); + StatusOr AddInstruction(HloInstructionProto&& instr, + HloOpcode opcode) { + return AddInstruction(std::move(instr), opcode, /*operands=*/{}); + } + + void AddCalledComputation(const XlaComputation& computation, + HloInstructionProto* instr); + + StatusOr LookUpInstruction(XlaOp op) const; + StatusOr LookUpInstructionByHandle( + int64_t handle) const; + StatusOr LookUpMutableInstruction(XlaOp op); + StatusOr LookUpMutableInstructionByHandle( + int64_t handle); + + // Internal helper method that does the building for an arbitrary unary op. + virtual XlaOp UnaryOp(HloOpcode unop, XlaOp operand); + + // Internal helper method that does the building for an arbitrary binary op. + // broadcast_dimensions specifies which dimensions to use for broadcasting + // when the operation is between tensors of different ranks. The direction is + // only used if opcode is kCompare. + XlaOp BinaryOp(HloOpcode binop, XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions, + std::optional direction = std::nullopt, + std::optional type = std::nullopt); + + StatusOr Compare(const Shape& shape, XlaOp lhs, XlaOp rhs, + ComparisonDirection direction); + + // Internal helper method for binary op compare without broadcast dimensions. + virtual StatusOr Compare(const Shape& shape, XlaOp lhs, XlaOp rhs, + ComparisonDirection direction, + Comparison::Type type); + + // Internal helper method that does the building for an arbitrary binary op + // with same ranked operands that doesn't broadcast. + virtual XlaOp BinaryOpNoBroadcast(HloOpcode binop, const Shape& shape, + XlaOp lhs, XlaOp rhs); + + // Internal helper method that does the building for an arbitrary ternary op. + XlaOp TernaryOp(HloOpcode triop, XlaOp lhs, XlaOp rhs, XlaOp ehs); + + XlaOp RngOp(RandomDistribution distribution, + absl::Span parameters, const Shape& shape); + + virtual StatusOr RngOpInternal(RandomDistribution distribution, + absl::Span parameters, + const Shape& shape); + + virtual StatusOr InDimBroadcast( + const Shape& shape, XlaOp operand, + absl::Span broadcast_dimensions); + + // Internal helper method that creates a sequence of instructions that + // performs an explicit broadcast of the operand to the target shape. + StatusOr AddBroadcastSequence(const Shape& output_shape, + XlaOp operand); + + // Internal helper method for creating a Reshape op with the already inferred + // shape. + virtual StatusOr ReshapeInternal(const Shape& shape, XlaOp operand, + int64_t inferred_dimension); + + // Returns the (inferred) result for the program shape using the given root. + StatusOr GetProgramShape(int64_t root_id) const; + + // A visitor which checks whether an operation is a compile-time constant, + // meaning that it doesn't depend on any parameters, or on any stateful + // operation such as `RngNormal` or `Infeed`. The visitor walks the + // computation starting at a given operation and sets is_constant to false iff + // a parameter or stateful operation is encountered. + void IsConstantVisitor(int64_t op_handle, int depth, + absl::flat_hash_set* visited, + bool* is_constant) const; + + // Checks bounds for convolution parameters. + Status VerifyConvolution( + const Shape& lhs_shape, const Shape& rhs_shape, + const ConvolutionDimensionNumbers& dimension_numbers) const; + + int64_t GetNextId() { return ++next_id_; } + + // Populates the module with the input/output alias information stored within + // the input_output_aliases vector. + static Status PopulateInputOutputAliasAndBufferDonor( + HloModuleProto* module, const ProgramShape& program_shape, + const std::vector& input_output_aliases, + const absl::flat_hash_set& + buffer_donors); + + std::string name_; // Name to use for the built computation. + + // The next sequential ID for every instruction/computation contained within + // this computation. + int64_t next_id_ = 0; + + // The first error encountered while building the computation. + // This is OK until the first error is encountered. + Status first_error_; + + // The saved stack trace from the point at which the first error occurred. + tsl::SavedStackTrace first_error_backtrace_; + + // The instructions of this computation. + // Use a deque so pointers into this are stable, for example the return + // value of LookUpInstructionByHandle(). + std::deque instructions_; + // A cache for the HloInstructionProto shapes, to avoid recreating Shape + // objects from protos and to support the GetShapePtr() API. + std::vector> instruction_shapes_; + + // Dynamic parameter configuration of this computation. + DynamicParameterBinding dynamic_parameter_binding_; + + // Holds the input/output alias information populated by the SetUpAlias() API. + std::vector input_output_aliases_; + + // Holds the buffer donor information populated by the AddBufferDonor() API. + absl::flat_hash_set buffer_donors_; + + // A map from XlaOp::Handle to the index in the instructions_ vector where the + // instruction is held. + absl::flat_hash_map handle_to_index_; + + // Track imported instructions by their computation id and the position in + // their computation's instruction list. + struct ImportedInstruction { + int64_t computation_id; + int64_t instruction_index; + }; + + absl::flat_hash_map handle_to_imported_index_; + + // The embedded computations used by this computation. Each computation was + // the entry computation of some XlaComputation, the key is the unique id of + // that XlaComputation. + std::map embedded_; + + // The unique parameter numbers. + absl::flat_hash_set parameter_numbers_; + + // The metadata to attach to each op. This is structured as a "modal"-like + // operation, in order to simplify client code (and not sprinkle this metadata + // throughout the TensorFlow op kernel implementations). + OpMetadata metadata_; + + // A temporary metadata that will only be applied to the next op created. + std::optional one_shot_metadata_; + + // Sharding for this operator. This is structured as a "model"-like operation, + // in order to simplify client code, similar to metadata_. + std::optional sharding_; + + // Mode bit that indicates whether to die when a first error is encountered. + bool die_immediately_on_error_ = false; + + XlaBuilder* parent_builder_{nullptr}; + + FrontendAttributes frontend_attributes_; + + friend XlaOp Parameter(XlaBuilder* builder, int64_t parameter_number, + const Shape& shape, const std::string& name, + const std::vector& replicated_at_leaf_buffers); + friend XlaOp ConstantLiteral(XlaBuilder* builder, + const LiteralSlice& literal); + + friend XlaOp Broadcast(XlaOp operand, + absl::Span broadcast_sizes); + + friend XlaOp BroadcastInDim(XlaOp operand, + absl::Span out_dim_size, + absl::Span broadcast_dimensions); + + friend XlaOp Copy(XlaOp operand); + + friend XlaOp Pad(XlaOp operand, XlaOp padding_value, + const PaddingConfig& padding_config); + + friend XlaOp PadInDim(XlaOp operand, XlaOp padding_value, int64_t dimno, + int64_t pad_lo, int64_t pad_hi); + + friend XlaOp Reshape(XlaOp operand, absl::Span dimensions, + absl::Span new_sizes); + + friend XlaOp Reshape(XlaOp operand, absl::Span new_sizes); + + friend XlaOp Reshape(const Shape& shape, XlaOp operand); + + friend XlaOp DynamicReshape(XlaOp operand, absl::Span dim_sizes, + absl::Span new_size_bounds, + const std::vector& dims_are_dynamic); + + friend XlaOp ReshapeWithInferredDimension(XlaOp operand, + absl::Span new_sizes, + int64_t inferred_dimension); + + friend XlaOp Collapse(XlaOp operand, absl::Span dimensions); + + friend XlaOp Slice(XlaOp operand, absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + + friend XlaOp SliceInDim(XlaOp operand, int64_t start_index, + int64_t limit_index, int64_t stride, int64_t dimno); + + friend XlaOp DynamicSlice(XlaOp operand, + absl::Span start_indices, + absl::Span slice_sizes); + + friend XlaOp DynamicUpdateSlice(XlaOp operand, XlaOp update, + absl::Span start_indices); + + friend XlaOp ConcatInDim(XlaBuilder* builder, + absl::Span operands, int64_t dimension); + + friend XlaOp Select(XlaOp pred, XlaOp on_true, XlaOp on_false); + friend XlaOp Tuple(XlaBuilder* builder, absl::Span elements); + friend XlaOp GetTupleElement(XlaOp tuple_data, int64_t index); + friend XlaOp Compare(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions, + ComparisonDirection direction); + friend XlaOp Compare(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions, + ComparisonDirection direction, + Comparison::Type compare_type); + friend XlaOp Dot(XlaOp lhs, XlaOp rhs, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + friend XlaOp DotGeneral(XlaOp lhs, XlaOp rhs, + const DotDimensionNumbers& dimension_number, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + virtual StatusOr DotGeneralInternal( + const Shape& shape, XlaOp lhs, XlaOp rhs, + const DotDimensionNumbers& dimension_number, + const PrecisionConfig* precision_config); + friend XlaOp Conv(XlaOp lhs, XlaOp rhs, + absl::Span window_strides, Padding padding, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + friend XlaOp ConvWithGeneralPadding( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + friend XlaOp ConvWithGeneralDimensions( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + Padding padding, const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + friend XlaOp ConvGeneral( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + friend XlaOp DynamicConvForward( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type); + friend XlaOp DynamicConvKernelGrad( + XlaOp activations, XlaOp gradients, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type); + friend XlaOp DynamicConvInputGrad( + XlaOp input_sizes, XlaOp lhs, XlaOp rhs, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type); + + friend XlaOp ConvKernelGrad( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type); + + friend XlaOp ConvGeneralDilated( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, + std::optional preferred_element_type, + std::optional> window_reversal); + + friend XlaOp Fft(XlaOp operand, FftType fft_type, + absl::Span fft_length); + friend XlaOp TriangularSolve(XlaOp a, XlaOp b, bool left_side, bool lower, + bool unit_diagonal, + TriangularSolveOptions::Transpose transpose_a); + friend XlaOp Cholesky(XlaOp a, bool lower); + friend XlaOp Infeed(XlaBuilder* builder, const Shape& shape, + const std::string& config); + friend void Outfeed(XlaOp operand, const Shape& shape_with_layout, + const std::string& outfeed_config); + friend XlaOp Call(XlaBuilder* builder, const XlaComputation& computation, + absl::Span operands); + friend XlaOp CustomCall( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape, + const std::string& opaque, bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, CustomCallSchedule schedule, + CustomCallApiVersion api_version); + friend XlaOp CustomCallWithComputation( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const XlaComputation& computation, + const Shape& shape, const std::string& opaque, bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, CustomCallSchedule schedule, + CustomCallApiVersion api_version); + friend XlaOp CustomCallWithLayout( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape_with_layout, + absl::Span operand_shapes_with_layout, + const std::string& opaque, bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, CustomCallSchedule schedule, + CustomCallApiVersion api_version); + friend XlaOp CustomCallWithConvDnums( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape, + absl::Span operand_shapes_with_layout, + const std::string& opaque, bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, Window window, ConvolutionDimensionNumbers dnums, + CustomCallSchedule schedule, CustomCallApiVersion api_version); + friend XlaOp OptimizationBarrier(XlaOp operand); + friend XlaOp Complex(XlaOp real, XlaOp imag, + absl::Span broadcast_dimensions); + friend XlaOp Conj(XlaOp operand); + friend XlaOp Add(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Sub(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Mul(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Div(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Rem(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Max(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Min(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp And(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Or(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Xor(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp Not(XlaOp operand); + friend XlaOp PopulationCount(XlaOp operand); + friend XlaOp ShiftLeft(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp ShiftRightArithmetic( + XlaOp lhs, XlaOp rhs, absl::Span broadcast_dimensions); + friend XlaOp ShiftRightLogical( + XlaOp lhs, XlaOp rhs, absl::Span broadcast_dimensions); + friend XlaOp Reduce(XlaOp operand, XlaOp init_value, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + friend XlaOp Reduce(XlaBuilder* builder, absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + friend XlaOp ReduceAll(XlaOp operand, XlaOp init_value, + const XlaComputation& computation); + friend XlaOp ReduceWindow(XlaOp operand, XlaOp init_value, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + Padding padding); + friend XlaOp ReduceWindow(absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + Padding padding); + friend XlaOp ReduceWindowWithGeneralPadding( + XlaOp operand, XlaOp init_value, const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); + friend XlaOp ReduceWindowWithGeneralPadding( + absl::Span operands, absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); + + friend XlaOp CrossReplicaSum(XlaOp operand, + absl::Span replica_groups); + friend XlaOp AllGather(XlaOp operand, int64_t all_gather_dimension, + int64_t shard_count, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& layout, + std::optional use_global_device_ids); + friend XlaOp AllReduce(XlaOp operand, const XlaComputation& computation, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& shape_with_layout, + std::optional use_global_device_ids); + friend XlaOp AllReduceTuple(absl::Span operand, + const XlaComputation& computation, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& shape_with_layout, + std::optional use_global_device_ids); + friend XlaOp ReduceScatter(XlaOp operand, const XlaComputation& computation, + int64_t scatter_dimension, int64_t shard_count, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& layout, + std::optional use_global_device_ids); + + friend XlaOp AllToAll(XlaOp operand, int64_t split_dimension, + int64_t concat_dimension, int64_t split_count, + absl::Span replica_groups, + const std::optional& layout, + const std::optional& channel_id); + friend XlaOp AllToAllTuple(absl::Span operands, + absl::Span replica_groups, + const std::optional& layout, + const std::optional& channel_id); + friend XlaOp AllToAllTuple(XlaOp operand, int64_t split_dimension, + int64_t concat_dimension, int64_t split_count, + absl::Span replica_groups, + const std::optional& layout, + const std::optional& channel_id); + friend XlaOp CollectivePermute( + XlaOp operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id); + friend XlaOp ReplicaId(XlaBuilder* builder); + friend XlaOp SelectAndScatter(XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + Padding padding, XlaOp source, XlaOp init_value, + const XlaComputation& scatter); + friend XlaOp SelectAndScatterWithGeneralPadding( + XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span> padding, XlaOp source, + XlaOp init_value, const XlaComputation& scatter); + friend XlaOp Abs(XlaOp operand); + friend XlaOp Atan2(XlaOp y, XlaOp x, + absl::Span broadcast_dimensions); + friend XlaOp Exp(XlaOp operand); + friend XlaOp Expm1(XlaOp operand); + friend XlaOp Floor(XlaOp operand); + friend XlaOp Ceil(XlaOp operand); + friend XlaOp Round(XlaOp operand); + friend XlaOp RoundNearestEven(XlaOp operand); + friend XlaOp Log(XlaOp operand); + friend XlaOp Log1p(XlaOp operand); + friend XlaOp Logistic(XlaOp operand); + friend XlaOp Sign(XlaOp operand); + friend XlaOp Clz(XlaOp operand); + friend XlaOp Cos(XlaOp operand); + friend XlaOp Sin(XlaOp operand); + friend XlaOp Tan(XlaOp operand); + friend XlaOp Tanh(XlaOp operand); + friend XlaOp Real(XlaOp operand); + friend XlaOp Imag(XlaOp operand); + friend XlaOp Sqrt(XlaOp operand); + friend XlaOp Rsqrt(XlaOp operand); + friend XlaOp Cbrt(XlaOp operand); + friend XlaOp Pow(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions); + friend XlaOp IsFinite(XlaOp operand); + friend XlaOp Iota(XlaBuilder* builder, const Shape& shape, + int64_t iota_dimension); + friend XlaOp Iota(XlaBuilder* builder, PrimitiveType type, int64_t size); + friend XlaOp ConvertElementType(XlaOp operand, + PrimitiveType new_element_type); + friend XlaOp BitcastConvertType(XlaOp operand, + PrimitiveType new_element_type); + friend XlaOp StochasticConvertType(XlaOp operand, XlaOp random, + PrimitiveType new_element_type); + friend XlaOp Neg(XlaOp operand); + friend XlaOp Transpose(XlaOp operand, absl::Span permutation); + friend XlaOp Rev(XlaOp operand, absl::Span dimensions); + friend XlaOp Sort(absl::Span operands, + const XlaComputation& comparator, int64_t dimension, + bool is_stable); + friend XlaOp Clamp(XlaOp min, XlaOp operand, XlaOp max); + friend XlaOp Map(XlaBuilder* builder, absl::Span operands, + const XlaComputation& computation, + absl::Span dimensions, + absl::Span static_operands); + friend XlaOp RngNormal(XlaOp mu, XlaOp sigma, const Shape& shape); + friend XlaOp RngUniform(XlaOp a, XlaOp b, const Shape& shape); + friend XlaOp RngBitGenerator(RandomAlgorithm algorithm, XlaOp initial_state, + const Shape& shape); + friend XlaOp While(const XlaComputation& condition, + const XlaComputation& body, XlaOp init); + friend XlaOp Conditional(XlaOp predicate, XlaOp true_operand, + const XlaComputation& true_computation, + XlaOp false_operand, + const XlaComputation& false_computation); + friend XlaOp Conditional( + XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + friend XlaOp ConditionalImpl( + XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + friend XlaOp ReducePrecision(XlaOp operand, int exponent_bits, + int mantissa_bits); + friend XlaOp Gather(XlaOp input, XlaOp start_indices, + const GatherDimensionNumbers& dimension_numbers, + absl::Span slice_sizes, + bool indices_are_sorted); + friend XlaOp Scatter(XlaOp input, XlaOp scatter_indices, XlaOp updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted, bool unique_indices); + friend XlaOp Scatter(absl::Span inputs, XlaOp scatter_indices, + absl::Span updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted, bool unique_indices); + friend void Send(XlaOp operand, const ChannelHandle& handle); + friend XlaOp Recv(XlaBuilder* builder, const Shape& shape, + const ChannelHandle& handle); + friend XlaOp BatchNormTraining(XlaOp operand, XlaOp scale, XlaOp offset, + float epsilon, int64_t feature_index); + friend XlaOp BatchNormInference(XlaOp operand, XlaOp scale, XlaOp offset, + XlaOp mean, XlaOp variance, float epsilon, + int64_t feature_index); + friend XlaOp BatchNormGrad(XlaOp operand, XlaOp scale, XlaOp batch_mean, + XlaOp batch_var, XlaOp grad_output, float epsilon, + int64_t feature_index); + friend XlaOp SendWithToken(XlaOp operand, XlaOp token, + const ChannelHandle& handle); + friend XlaOp RecvWithToken(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + friend XlaOp SendToHost(XlaOp operand, XlaOp token, + const Shape& shape_with_layout, + const ChannelHandle& handle); + friend XlaOp RecvFromHost(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + friend XlaOp InfeedWithToken(XlaOp token, const Shape& shape, + const std::string& config); + friend XlaOp OutfeedWithToken(XlaOp operand, XlaOp token, + const Shape& shape_with_layout, + const std::string& outfeed_config); + friend XlaOp CreateToken(XlaBuilder* builder); + friend XlaOp AfterAll(XlaBuilder* builder, absl::Span tokens); + + friend XlaOp GetDimensionSize(XlaOp operand, int64_t dimension); + friend XlaOp SetDimensionSize(XlaOp operand, XlaOp val, int64_t dimension); + friend XlaOp RemoveDynamicDimension(XlaOp operand, int64_t dimension); + + protected: + // Returns OK status if the given op was built using this builder. Otherwise, + // returns an error. + Status CheckOpBuilder(XlaOp op) const; + + private: + XlaOp AllGatherImpl(XlaOp operand, int64_t all_gather_dimension, + int64_t shard_count, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& layout, + std::optional use_global_device_ids, bool async); + + XlaOp AllReduceImpl(XlaOp operand, const XlaComputation& computation, + absl::Span replica_groups, + const std::optional& channel_id, + const std::optional& layout, + std::optional use_global_device_ids, bool async); + + XlaOp CollectivePermuteImpl( + XlaOp operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id, bool async); + + XlaOp ConditionalImpl( + XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + + XlaOp AllToAllArray( + XlaOp operand, int64_t split_dimension, int64_t concat_dimension, + int64_t split_count, absl::Span replica_groups, + const std::optional& channel_id = std::nullopt); + + // Creates an op with the given opcode and the output shape. + virtual StatusOr AddOpWithShape(HloOpcode opcode, const Shape& shape, + absl::Span operands); + + // Here, InstructionType is either const HloInstructionProto* or non-const + // HloInstructionProto*. + template + StatusOr LookUpInstructionByHandleInternal( + int64_t handle) const { + auto it = handle_to_index_.find(handle); + if (it == handle_to_index_.end()) { + // Try look for the instruction in the imported instructions. + auto imported_it = handle_to_imported_index_.find(handle); + if (imported_it != handle_to_imported_index_.end()) { + ImportedInstruction imported = imported_it->second; + return const_cast( + &embedded_.at(imported.computation_id) + .instructions(imported.instruction_index)); + } + return InvalidArgument("No XlaOp with handle %d", handle); + } + return const_cast(&instructions_.at(it->second)); + } + + // Here, InstructionType is either const HloInstructionProto* or non-const + // HloInstructionProto*. + // + // TODO(hinsu): Return const pointer within StatusOr and use + // absl::implicit_cast at callsites. This requires implicit_cast support in + // xla::StatusOr similar to absl::StatusOr. + template + StatusOr LookUpInstructionInternal(XlaOp op) const { + TF_RETURN_IF_ERROR(CheckOpBuilder(op)); + return LookUpInstructionByHandleInternal(op.handle()); + } + + friend struct internal::XlaBuilderFriend; + + friend class ValueInference; +}; + +// RAII-style object: sets the current sharding assignment in builder on +// construction, and sets back to the previous assignment on destruction. +class XlaScopedShardingAssignment { + public: + XlaScopedShardingAssignment(xla::XlaBuilder* builder, + std::optional sharding) + : builder_(builder), prev_sharding_(builder->sharding()) { + SetSharding(sharding); + } + + XlaScopedShardingAssignment(const XlaScopedShardingAssignment&) = delete; + XlaScopedShardingAssignment& operator=(const XlaScopedShardingAssignment&) = + delete; + + ~XlaScopedShardingAssignment() { SetSharding(prev_sharding_); } + + private: + void SetSharding(const std::optional& sharding) { + if (sharding.has_value()) { + builder_->SetSharding(sharding.value()); + } else { + builder_->ClearSharding(); + } + } + + xla::XlaBuilder* const builder_; + std::optional prev_sharding_; +}; + +// RAII-style object: save the current builder's frontend attributes, and merge +// them with the new ones on construction. +// Restore the original attributes on destruction. +class XlaScopedFrontendAttributesAssignment { + public: + XlaScopedFrontendAttributesAssignment(xla::XlaBuilder* builder, + FrontendAttributes attributes) + : builder_(builder) { + saved_ = builder_->SwapFrontendAttributes(attributes); + } + + ~XlaScopedFrontendAttributesAssignment() { + builder_->SetFrontendAttributes(saved_); + } + + private: + xla::XlaBuilder* const builder_; + FrontendAttributes saved_; + + XlaScopedFrontendAttributesAssignment( + const XlaScopedFrontendAttributesAssignment&) = delete; + XlaScopedFrontendAttributesAssignment& operator=( + const XlaScopedFrontendAttributesAssignment&) = delete; +}; + +// RAII-style object: sets the current op metadata in builder on construction, +// and sets back to the previous assignment on destruction. +class XlaScopedOpMetadataAssignment { + public: + XlaScopedOpMetadataAssignment(xla::XlaBuilder* builder, OpMetadata metadata) + : builder_(builder) { + saved_ = builder_->SwapOpMetadata(metadata); + } + + ~XlaScopedOpMetadataAssignment() { builder_->SwapOpMetadata(saved_); } + + private: + xla::XlaBuilder* const builder_; + OpMetadata saved_; + + XlaScopedOpMetadataAssignment(const XlaScopedOpMetadataAssignment&) = delete; + XlaScopedOpMetadataAssignment& operator=( + const XlaScopedOpMetadataAssignment&) = delete; +}; + +// Free functions for building XlaOps. The intention is that these will +// become the public API for building XlaOps rather than calling methods on +// XlaBuilder directly. +// + +// Enqueues a "retrieve parameter value" instruction for a parameter that was +// passed to the computation. +XlaOp Parameter(XlaBuilder* builder, int64_t parameter_number, + const Shape& shape, const std::string& name); + +// Same as above, but with leaf buffer replication annotation. +XlaOp Parameter(XlaBuilder* builder, int64_t parameter_number, + const Shape& shape, const std::string& name, + const std::vector& replicated_at_leaf_buffers); + +// Enqueues a constant with the value of the given literal onto the +// computation. +XlaOp ConstantLiteral(XlaBuilder* builder, const LiteralSlice& literal); + +// Enqueues a constant onto the computation. Methods are templated on the +// native host type (NativeT) which corresponds to a specific XLA +// PrimitiveType as given in the following table: +// +// Native Type PrimitiveType +// ----------------------------- +// bool PRED +// int32_t S32 +// int64_t S64 +// uint32_t U32 +// uint64_t U64 +// float F32 +// double F64 +// +// Note: not all primitive types defined in xla_data.proto have a +// corresponding native type yet. +template +XlaOp ConstantR0(XlaBuilder* builder, NativeT value); +template +XlaOp ConstantR1(XlaBuilder* builder, absl::Span values); +XlaOp ConstantR1(XlaBuilder* builder, const tsl::core::Bitmap& values); +template +XlaOp ConstantR2(XlaBuilder* builder, + std::initializer_list> values); +template +XlaOp ConstantFromArrayWithLayout(XlaBuilder* builder, + const Array& values, + const Layout& layout); +template +XlaOp ConstantFromArray(XlaBuilder* builder, const Array& values); +template +XlaOp ConstantR2FromArray2DWithLayout(XlaBuilder* builder, + const Array2D& values, + const Layout& layout); +template +XlaOp ConstantR2FromArray2D(XlaBuilder* builder, + const Array2D& values); +template +XlaOp ConstantR3FromArray3DWithLayout(XlaBuilder* builder, + const Array3D& values, + const Layout& layout); +template +XlaOp ConstantR3FromArray3D(XlaBuilder* builder, + const Array3D& values); +template +XlaOp ConstantR4FromArray4DWithLayout(XlaBuilder* builder, + const Array4D& values, + const Layout& layout); +template +XlaOp ConstantR4FromArray4D(XlaBuilder* builder, + const Array4D& values); + +// Enqueues a rank one constant (XlaBuilder* builder, vector) onto the +// computation. The vector has size 'length' and every element has the value +// 'value'. +template +XlaOp ConstantR1(XlaBuilder* builder, int64_t length, NativeT value); + +// Adds dimensions to an array by duplicating the data in the array. +// +// The new dimensions are inserted on the left, i.e. if +// broadcast_sizes has values {a0, ..., aN} and the operand shape +// has dimensions {b0, ..., bM} then the shape of the output has +// dimensions {a0, ..., aN, b0, ..., bM}. +// +// The new dimensions index into copies of the operand, i.e. +// +// output[i0, ..., iN, j0, ..., jM] = operand[j0, ..., jM] +XlaOp Broadcast(XlaOp operand, absl::Span broadcast_sizes); + +// This op broadcasts the `operand` to an output with the given `shape`. +// `broadcast_dimensions` are the dimensions to be broadcasting into, i.e., the +// i'th dimension of the operand is mapped to the broadcast_dimensions[i]'th +// dimension of the output. This also requires that the i'th input dimension is +// either 1 or is the same as the output dimension it's broadcasting into. +// +// For example, say operand = {1, 2}, i.e., a 1D tensor in shape s32[2]; the +// output shape is s32[2,2]: +// - Specifying {1} as broadcast_dimension will generate output +// {{1, 2}, +// {1, 2}} +// - On the other hand, specifying {0} as broadcast_dimension +// will generate output +// {{1 , 1}, +// {2 , 2}} +XlaOp BroadcastInDim(XlaOp operand, absl::Span out_dim_size, + absl::Span broadcast_dimensions); + +// Copies the input operand to the output. This operation is for internal +// purpose and is only used by the compiler for optimization purposes or to +// ensure correctness. The XLA client should never have to generate this +// instruction. +// +// Copy has two potential use cases: +// +// * Create a copy of the operand with a new layout. +// +// * Create a copy of the operand in a separately allocated buffer. This is +// necessary for some backends if the operand is a parameter or constant and +// the operand is returned within a tuple. In this case, the lifetime of the +// operand buffer must be the same as the lifetime of the output result. +// However, the lifetimes of parameters and constants are managed separately +// from the lifetime of the output result. Creating a separate copy of the +// parameter or constant buffer resolves this issue. +XlaOp Copy(XlaOp operand); + +// Enqueues a pad operation onto the computation that pads the given value on +// the edges as well as between the elements of the input. padding_config +// specifies the padding amount for each dimension. +XlaOp Pad(XlaOp operand, XlaOp padding_value, + const PaddingConfig& padding_config); + +// Enqueues a pad operation in a given dimension, taking all other +// dimensions as they are. +XlaOp PadInDim(XlaOp operand, XlaOp padding_value, int64_t dimno, + int64_t pad_lo, int64_t pad_hi); + +// Enqueues an operation onto the computation that flattens the operand based +// on the dimension order (major/slowest-varying to minor/fastest-varying) +// given, followed by reshaping it into the shape with the given dimension +// sizes (also major to minor). Conceptually, this is a limited form of +// "shape casting". +XlaOp Reshape(XlaOp operand, absl::Span dimensions, + absl::Span new_sizes); + +// Enqueues a dynamic reshape operation. The dynamic reshape takes additional +// XlaOps as sizes for the result dimension. The result dim i is a dynamic +// dimension dimension if dims_are_dynamic[i] is true. +XlaOp DynamicReshape(XlaOp operand, absl::Span dim_sizes, + absl::Span new_size_bounds, + const std::vector& dims_are_dynamic); + +// Enqueues an operation onto the computation that collapses the operand, +// from first to last dimension (C order), then reshapes it to the given +// dimension sizes. Conceptually, this is a limited form of "shape casting". +XlaOp Reshape(XlaOp operand, absl::Span new_sizes); + +// Enqueues a Reshape op that uses an explicit target shape. +XlaOp Reshape(const Shape& shape, XlaOp operand); + +// `inferred_dimension` represents the output dimension that's inferred by +// upper-level framework by dividing the input element count by the known +// output element count. While an inferred_dimension can be static, if there +// is a dynamic dimension in the output, it must be the inferred dimension. +XlaOp ReshapeWithInferredDimension(XlaOp operand, + absl::Span new_sizes, + int64_t inferred_dimension); + +// Wrapper for Reshape. +// Enqueues an operation to collapse the provided dimensions; e.g. an +// operand with dimensions {x=256, y=2, z=2, p=32} can be collapsed to +// {x=1024, y=32} by collapsing dims {0, 1, 2}. Collapsing dimensions must +// be a consecutive, in-order subsequence of the operand dimensions. +// +// Note that collapsing a single dimension does nothing: +// +// {256} collapsing {0} => {256} +// {1} collapsing {0} => {1} +// +// Collapsing multiple dimensions produces a single result dimension: +// +// {256, 2} collapsing {0,1} => {512} +// {256, 2, 3} collapsing {0,1} => {512, 3} +// +// This could potentially cause data to be moved -- it provides a more +// structured form of reshaping than an arbitrary Reshape operation. +XlaOp Collapse(XlaOp operand, absl::Span dimensions); + +// Enqueues a slice operation onto the computation that slices the operand +// from the start indices to the limit indices; e.g. +// +// x +// [ 0 1 2 3 ] +// y [ 4 5 6 7 ] => slice(start={1, 1}, limit={2, 3}) => [ 5 6 ] +// [ 8 9 a b ] +// +// Note that "limit" means up-to-but-not-including; i.e. [start, limit) in 1D +// range notation. +// The strides parameter determines the stride over the slice +XlaOp Slice(XlaOp operand, absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + +// Enqueues a slice operation in a given dimension, taking all other +// dimensions as they are; e.g. if dimno is 1 from start_index 2 to +// limit_index 4 by 1, and the shape is f32[7,8,9], this call is short-hand +// for: +// +// array[:, 2:4:1, :] +XlaOp SliceInDim(XlaOp operand, int64_t start_index, int64_t limit_index, + int64_t stride, int64_t dimno); + +// Enqueues a slice operation onto the computation that slices the 'operand' +// from dynamic start indices which are passed in 'start_indices'. +// The size of the slice in each dimension is passed in 'slice_sizes', +// which specify the end point of exclusive slice intervals in each +// dimension [start, start + size). +// The shape of each element of 'start_indices' must be scalar, with the span +// size equal to the rank of the 'operand'. All elements of 'start_indices' must +// have the same shape. +// Slice index calculations are computed modulo input dimension sizes to +// prevent dynamic start indices from generating out-of-bound array accesses. +XlaOp DynamicSlice(XlaOp operand, absl::Span start_indices, + absl::Span slice_sizes); + +// Enqueues a dynamic update slice operation onto the computation, which +// updates a slice of 'operand' with 'update' at dynamic 'start_indices'. +// The shape of 'update' determines the shape of the slice of 'operand' +// which is updated. +// The indices specified in 'start_indices' specify the offset of the slice +// of 'operand' which is updated. +// +// update = {10, 11} // calculated at runtime. +// [1 2 3] start = {1, 1} // calculated at runtime. [1 2 3 ] +// [4 5 6] => DynamicUpdateslice(data, update, start) => [4 10 11] +// [7 8 9] [7 8 9 ] +// +// The shape of each element of 'start_indices' must be scalar, with the span +// size equal to the rank of the 'operand'. All elements of 'start_indices' must +// have the same shape. +// Slice index calculations are computed modulo update dimension sizes to +// prevent dynamic start indices from generating out-of-bound array accesses. +XlaOp DynamicUpdateSlice(XlaOp operand, XlaOp update, + absl::Span start_indices); + +// Enqueues a concatenate instruction onto the computation. 'operands' must +// have >= 1 entry. +XlaOp ConcatInDim(XlaBuilder* builder, absl::Span operands, + int64_t dimension); + +// Enqueues a conditional-move-like select operation onto the computation; +// predicated on pred, selects between on_true and on_false. +XlaOp Select(XlaOp pred, XlaOp on_true, XlaOp on_false); + +// Enqueues a tuple-creation instruction onto the computation. +XlaOp Tuple(XlaBuilder* builder, absl::Span elements); + +// Enqueues a tuple-element-get instruction onto the computation. +XlaOp GetTupleElement(XlaOp tuple_data, int64_t index); + +// Enqueues an equal-to comparison instruction onto the computation. +XlaOp Eq(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp EqTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a not-equal comparison instruction onto the computation. +XlaOp Ne(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp NeTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a greater-or-equal comparison instruction onto the computation. +XlaOp Ge(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp GeTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a greater-than comparison instruction onto the computation. +XlaOp Gt(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp GtTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a less-than comparison instruction onto the computation. +XlaOp Lt(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp LtTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a less-or-equal comparison instruction onto the computation. +XlaOp Le(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp LeTotalOrder(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a comparison instruction onto the computation (optionally without +// broadcast_dimensions for consistency with others). +XlaOp Compare(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions, + ComparisonDirection direction, Comparison::Type compare_type); +XlaOp Compare(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions, + ComparisonDirection direction); +XlaOp Compare(XlaOp lhs, XlaOp rhs, ComparisonDirection direction); + +// Enqueues a dot instruction onto the computation. +XlaOp Dot(XlaOp lhs, XlaOp rhs, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a general dot instruction onto the computation. +XlaOp DotGeneral( + XlaOp lhs, XlaOp rhs, const DotDimensionNumbers& dimension_numbers, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a convolution instruction onto the computation, which uses the +// default convolution dimension numbers. +XlaOp Conv(XlaOp lhs, XlaOp rhs, absl::Span window_strides, + Padding padding, int64_t feature_group_count = 1, + int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a convolution instruction onto the computation, with the caller +// provided padding configuration in the format returned by MakePadding(). +XlaOp ConvWithGeneralPadding( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a convolution instruction onto the computation, with the caller +// provided dimension numbers configuration. +XlaOp ConvWithGeneralDimensions( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + Padding padding, const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a convolution instruction onto the computation, with the caller +// provided padding configuration as well as the dimension numbers. +XlaOp ConvGeneral( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt); + +// Enqueues a convolution instruction onto the computation, with the caller +// provided padding configuration, dilation factors and dimension numbers. +XlaOp ConvGeneralDilated( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count = 1, int64_t batch_group_count = 1, + const PrecisionConfig* precision_config = nullptr, + std::optional preferred_element_type = std::nullopt, + std::optional> window_reversal = std::nullopt); + +XlaOp DynamicConvForward( + XlaOp lhs, XlaOp rhs, absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + +XlaOp DynamicConvInputGrad( + XlaOp input_sizes, XlaOp lhs, XlaOp rhs, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + +XlaOp DynamicConvKernelGrad( + XlaOp activations, XlaOp gradients, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + const ConvolutionDimensionNumbers& dimension_numbers, + int64_t feature_group_count, int64_t batch_group_count, + const PrecisionConfig* precision_config, PaddingType padding_type, + std::optional preferred_element_type = std::nullopt); + +// Enqueues an FFT instruction onto the computation, of the given type and +// with the given FFT length. +XlaOp Fft(XlaOp operand, FftType fft_type, + absl::Span fft_length); + +// Solves systems of linear equations with lower or upper triangular coefficient +// matrices by forward- or back-substitution. Broadcasting along leading +// dimensions, this routine solves for x in one of the matrix systems +// `op(a) * x = b`, or `x * op(a) = b`, +// for the variable `x` given `a` and `b`, where `op(a)` is either +// `op(a) = a`, or `op(a) = transpose(a)`, or `op(a) = conj(transpose(a))`. +// +// * `a` is a tensor of shape `[..., M, M]` whose innermost 2 dimensions form +// square matrices. If `lower` is true (false), then the strictly upper +// (lower) triangular part of each innermost matrix in `a` is assumed to be +// zero and is not accessed. +// * `b` is a tensor of shape `[..., M, K]` if `left_side` is true, otherwise a +// tensor of shape `[..., K, M]`. +// * `left_side` is a boolean, indicating whether to solve a system of the form +// op(a) * x = b (true) or x * op(a) = b (false). +// * `lower` is a boolean, indicating whether the argument `a` is +// lower-triangular (true) or upper-triangular (false). +// * If `unit_diagonal` is true, the diagonal elements of `a` are assumed to be +// 1 and not accessed. +// * `transpose_a` indicates which function `op` we use to transform the tensor +// `a`: the identity function, transpose(a), or conjugate(transpose(a)) +XlaOp TriangularSolve(XlaOp a, XlaOp b, bool left_side, bool lower, + bool unit_diagonal, + TriangularSolveOptions::Transpose transpose_a); + +// Computes the Cholesky decompositions of a batch of symmetric (Hermitian) +// positive definite matrices. +// `a` must be a (batched) square matrix; i.e., it must have rank >= 2 with the +// two minor dimensions equal. +// If `lower` is true, the data from the lower triangle is used; if false, the +// upper triangle is used. The input data in the other triangle of the input +// does not affect the output. Returns the output in the same lower/upper +// triangle. The data returned in the other output triangle is arbitrary and +// implementation-defined. +// +// If `a` is not Hermitian positive definite, returns an array full of NaNs. +XlaOp Cholesky(XlaOp a, bool lower); + +// Enqueues an infeed instruction onto the computation, which writes data of +// the given shape to the infeed buffer of the device. +XlaOp Infeed(XlaBuilder* builder, const Shape& shape, + const std::string& config = ""); + +// Variant of Infeed which takes a token-shaped operand and produces a +// two-element tuple containing the data value and a token-shaped value. +// Tokens are used for ordering side-effecting operations. +// TODO(b/110532604): Replace all uses of the non-token form with this variant. +XlaOp InfeedWithToken(XlaOp token, const Shape& shape, + const std::string& config = ""); + +// Enqueues an outfeed instruction onto the computation. This instruction +// generates outgoing data transfers for the given data. +// +// shape_with_layout communicates the laid out shape that we want to outfeed +// -- if !ShapeUtil::Compatible(GetShape(operand), shape_with_layout) an error +// will occur. +void Outfeed(XlaOp operand, const Shape& shape_with_layout, + const std::string& outfeed_config); + +// Variant of Outfeed which takes a token-shaped operand and produces a +// token-shaped value. Tokens are used for ordering side-effecting operations. +// TODO(b/110532604): Replace all uses of the non-token form with this variant. +XlaOp OutfeedWithToken(XlaOp operand, XlaOp token, + const Shape& shape_with_layout, + const std::string& outfeed_config); + +// Enqueues a call instruction onto the computation. +XlaOp Call(XlaBuilder* builder, const XlaComputation& computation, + absl::Span operands); + +// Enqueues a custom call instruction onto the computation. A custom call +// invokes code external to XLA. The |operands| are passed to the external code, +// and the external code is expected to produce a result of the given +// |shape|. The exact mechanism is backend-specific. For example, in the CPU +// backend, a call instruction is emitted which targets a symbol with the name +// |call_target_name|. |call_target_name| and |opaque| can arbitrary strings, +// but |call_target_name| should be short as it may be used in labels. |opaque| +// can encode arbitrarily large amounts of information. |has_side_effect| +// specifies whether the instruction can have side effects. +// |output_operand_aliasing| specifies a list of output/operand buffer pairs +// that alias each other, where the output buffer is represented as a +// ShapeIndex, and the operand buffer is represented as the operand index and +// the ShapeIndex. +XlaOp CustomCall( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape, + const std::string& opaque = "", bool has_side_effect = false, + absl::Span>> + output_operand_aliasing = {}, + const Literal* literal = nullptr, + CustomCallSchedule schedule = CustomCallSchedule::SCHEDULE_NONE, + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + +// Overload which constructs a custom call that applies an Xla computation. +XlaOp CustomCallWithComputation( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const XlaComputation& computation, + const Shape& shape, const std::string& opaque = "", + bool has_side_effect = false, + absl::Span>> + output_operand_aliasing = {}, + const Literal* literal = nullptr, + CustomCallSchedule schedule = CustomCallSchedule::SCHEDULE_NONE, + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + +// Overload which constructs a custom call with fixed layouts. The operands will +// have the layouts specified by |operand_shapes_with_layout| when provided to +// external code, and the external code is expected to produce a result with the +// layout specified by |shape_with_layout|. All shapes in |shape_with_layout| +// and |operand_shapes_with_layout| must have layouts. +XlaOp CustomCallWithLayout( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape_with_layout, + absl::Span operand_shapes_with_layout, + const std::string& opaque = "", bool has_side_effect = false, + absl::Span>> + output_operand_aliasing = {}, + const Literal* literal = nullptr, + CustomCallSchedule schedule = CustomCallSchedule::SCHEDULE_NONE, + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + +// Overload which annotates a custom call with the given Window and +// ConvolutionDimensionNumbers. Useful for custom-calls which represent +// convolutions. +// +// This sets the layout of its operands if operand_shapes_with_layout is +// nonempty, and it sets the layout of its result if `shape` has a layout. +XlaOp CustomCallWithConvDnums( + XlaBuilder* builder, const std::string& call_target_name, + absl::Span operands, const Shape& shape, + absl::Span operand_shapes_with_layout, + const std::string& opaque, bool has_side_effect, + absl::Span>> + output_operand_aliasing, + const Literal* literal, Window window, ConvolutionDimensionNumbers dnums, + CustomCallSchedule schedule = CustomCallSchedule::SCHEDULE_NONE, + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + +// Enqueues an optimization barrier onto the computation. +XlaOp OptimizationBarrier(XlaOp operand); + +// The following methods enqueue element-wise binary arithmetic operations +// onto the computation. The shapes of the operands have to match unless one +// of the operands is a scalar, or an explicit broadcast dimension is given +// (see g3doc for more details). + +// Enqueues a complex compose instruction onto the computation. +XlaOp Complex(XlaOp real, XlaOp imag, + absl::Span broadcast_dimensions = {}); + +// Enqueues a complex conjugate instruction onto the computation. +XlaOp Conj(XlaOp operand); + +// Enqueues an add instruction onto the computation. +XlaOp Add(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a subtract instruction onto the computation. +XlaOp Sub(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a multiply instruction onto the computation. +XlaOp Mul(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a divide instruction onto the computation. +XlaOp Div(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a remainder instruction onto the computation. +XlaOp Rem(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a max instruction onto the computation. +XlaOp Max(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues a min instruction onto the computation. +XlaOp Min(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Element-wise logical operators +XlaOp And(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Overload to call And with 3 or more operands. We need the following somewhat +// convoluted overload set to disambiguate with the overload that takes the +// `broadcast_dimensions` optional param. +inline XlaOp And(XlaOp op1, XlaOp op2, XlaOp op3) { + return And(op1, And(op2, op3)); +} +template +XlaOp And(XlaOp op1, XlaOp op2, XlaOp op3, const XlaOpTs&... operands) { + return And(op1, And(op2, And(op3, operands...))); +} + +XlaOp Or(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Overload to call Or with 3 or more operands. As with `And`, we need the +// following complicated overload set to handle the default arg in the `Or` +// overload above. +inline XlaOp Or(XlaOp op1, XlaOp op2, XlaOp op3) { + return Or(op1, Or(op2, op3)); +} +template +XlaOp Or(XlaOp op1, XlaOp op2, XlaOp op3, const XlaOpTs&... operands) { + return Or(op1, Or(op2, Or(op3, operands...))); +} + +XlaOp Xor(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +XlaOp Not(XlaOp operand); + +XlaOp PopulationCount(XlaOp operand); + +XlaOp ShiftLeft(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp ShiftRightArithmetic(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +XlaOp ShiftRightLogical(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); +// Reduces an array among the provided dimensions, given "computation" as a +// reduction operator. +XlaOp Reduce(XlaOp operand, XlaOp init_value, const XlaComputation& computation, + absl::Span dimensions_to_reduce); + +// Reduces several arrays simultaneously among the provided dimensions, given +// "computation" as a reduction operator. +XlaOp Reduce(XlaBuilder* builder, absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span dimensions_to_reduce); + +// Convenience wrapper around the above that reduces all the dimensions in the +// operand shape. +XlaOp ReduceAll(XlaOp operand, XlaOp init_value, + const XlaComputation& computation); + +// Enqueues a windowed reduce instruction onto the computation. +XlaOp ReduceWindow(XlaOp operand, XlaOp init_value, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, Padding padding); + +XlaOp ReduceWindow(absl::Span operands, + absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, Padding padding); + +// As ReduceWindow(), but the padding is given in the format +// returned by MakePadding(). +XlaOp ReduceWindowWithGeneralPadding( + XlaOp operand, XlaOp init_value, const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); +XlaOp ReduceWindowWithGeneralPadding( + absl::Span operands, absl::Span init_values, + const XlaComputation& computation, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span base_dilations, + absl::Span window_dilations, + absl::Span> padding); + +// Returns the sum of the operand value within each subgroup of replicas. All +// replicas supply one input to the sum and all replicas receive the resulting +// sum for each subgroup. +XlaOp CrossReplicaSum(XlaOp operand, + absl::Span replica_groups = {}); + +XlaOp AllGather(XlaOp operand, int64_t all_gather_dimension, + int64_t shard_count, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + +// Enqueues an operation that do an AllReduce of the operand cross cores. Here +// AllReduce means doing a reduction on the input operand cross cores and then +// broadcasting the reduction result to those cores. The reduction function is +// defined by `computation`, which should be a commutative computation on +// scalars, e.g., add, min, or max. The way that AllReduce is applied is +// configured by: +// +// - `replica_groups`: each ReplicaGroup contains a list of replica id. If +// empty, all replicas belong to one group. Allreduce will be applied within +// subgroups. For example, we have 4 replicas, then replica_groups={{0,2},{1,3}} +// means, replica 0 and 2 are in subgroup 0, replica 1 and 3 are in subgroup 1. +// +// - `channel_id`: for Allreduce nodes from different modules, if they have the +// same channel_id, they will be 'AllReduce'd. If empty, AllReduce will not be +// applied cross modules. +// +// - `shape_with_layout`: forces the layout of the AllReduce to the given +// layout. This is used to guarantee the same layout for a group of AllReduce +// ops compiled separately. +XlaOp AllReduce(XlaOp operand, const XlaComputation& computation, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& shape_with_layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + +XlaOp AllReduceTuple( + absl::Span operand, const XlaComputation& computation, + absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& shape_with_layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + +XlaOp ReduceScatter( + XlaOp operand, const XlaComputation& computation, int64_t scatter_dimension, + int64_t shard_count, absl::Span replica_groups = {}, + const std::optional& channel_id = std::nullopt, + const std::optional& layout = std::nullopt, + std::optional use_global_device_ids = std::nullopt); + +// Enqueues an operation that do an Alltoall of the operand cross cores. +// An optional `layout` can be specified to force the layout of the instruction. +// This is used to guarantee the same layout for a group of AllToAll ops +// compiled separately. +XlaOp AllToAll(XlaOp operand, int64_t split_dimension, int64_t concat_dimension, + int64_t split_count, + absl::Span replica_groups = {}, + const std::optional& layout = std::nullopt, + const std::optional& channel_id = std::nullopt); + +XlaOp AllToAllTuple( + absl::Span operand, + absl::Span replica_groups = {}, + const std::optional& layout = std::nullopt, + const std::optional& channel_id = std::nullopt); + +XlaOp AllToAllTuple( + XlaOp operand, int64_t split_dimension, int64_t concat_dimension, + int64_t split_count, absl::Span replica_groups = {}, + const std::optional& layout = std::nullopt, + const std::optional& channel_id = std::nullopt); + +// Enqueues an collective operation that sends and receives data cross replicas. +// +// - `source_target_pair`: a list of (source_replica_id, target_replica_id) +// pairs. For each pair, the operand is sent from source replica to target +// replica. Note that, 1) any two pairs should not have the same target replica +// id, and they should not have the same source replica id; 2) if a replica id +// is not a target in any pair, then the output on that replica is a tensor +// consists of 0(s) with the same shape as the input. +XlaOp CollectivePermute( + XlaOp operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id = std::nullopt); + +// Enqueues an operation that returns the replica ID. +XlaOp ReplicaId(XlaBuilder* builder); + +// Enqueues an operation that scatters the `source` array to the selected +// indices of each window. +XlaOp SelectAndScatter(XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + Padding padding, XlaOp source, XlaOp init_value, + const XlaComputation& scatter); + +// As SelectAndScatter(), but the padding is given in the format +// returned by MakePadding(). +XlaOp SelectAndScatterWithGeneralPadding( + XlaOp operand, const XlaComputation& select, + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span> padding, XlaOp source, + XlaOp init_value, const XlaComputation& scatter); + +// Enqueues an abs instruction onto the computation. +XlaOp Abs(XlaOp operand); + +// Enqueues a atan2 instruction onto the computation. +XlaOp Atan2(XlaOp y, XlaOp x, + absl::Span broadcast_dimensions = {}); + +// Enqueues an exp instruction onto the computation. +XlaOp Exp(XlaOp operand); + +// Enqueues an expm1 instruction onto the computation. +XlaOp Expm1(XlaOp operand); + +// Enqueues a floor instruction onto the computation. +XlaOp Floor(XlaOp operand); + +// Enqueues a ceil instruction onto the computation. +XlaOp Ceil(XlaOp operand); + +// Enqueues a round instruction onto the computation, +// with half-way cases rounding away from zero. +XlaOp Round(XlaOp operand); + +// Enqueues a round instruction onto the computation, rounding to nearest even +XlaOp RoundNearestEven(XlaOp operand); + +// Enqueues an log instruction (natural logarithm) onto the computation. +XlaOp Log(XlaOp operand); + +// Enqueues an log1p instruction (log(x+1)) onto the computation. +XlaOp Log1p(XlaOp operand); + +// Enqueues a logistic instruction onto the computation. +XlaOp Logistic(XlaOp operand); + +// Enqueues a sign instruction onto the computation. +XlaOp Sign(XlaOp operand); + +// Enqueues a count leading zeros instruction onto the computation. +XlaOp Clz(XlaOp operand); + +// Enqueues a cosine instruction onto the computation. +XlaOp Cos(XlaOp operand); + +// Enqueues a sine instruction onto the computation. +XlaOp Sin(XlaOp operand); + +// Enqueues a tan instruction onto the computation. +XlaOp Tan(XlaOp operand); + +// Enqueues a tanh instruction onto the computation. +XlaOp Tanh(XlaOp operand); + +// Enqueues a real-part instruction onto the computation. +XlaOp Real(XlaOp operand); + +// Enqueues an imaginary-part instruction onto the computation. +XlaOp Imag(XlaOp operand); + +// Enqueues a sqrt computation onto the computation. +XlaOp Sqrt(XlaOp operand); + +// Enqueues a cbrt computation onto the computation. +XlaOp Cbrt(XlaOp operand); + +// Enqueues a rsqrt computation onto the computation. +XlaOp Rsqrt(XlaOp operand); + +// Enqueues a lhs^rhs computation onto the computation. +XlaOp Pow(XlaOp lhs, XlaOp rhs, + absl::Span broadcast_dimensions = {}); + +// Enqueues an operator that tests if the operand's values are finite, i.e., not +// +/-Inf or NaN. Returns an array of booleans with the same shape where +// entries are true iff the corresponding entry was not infinite or NaN. +// +// Defined only for real-valued (i.e. not complex) floating-point types; raises +// an error for other types. +// +// See also IsInf, IsPosInf, IsNegInf, and IsNan in lib/math.h. +XlaOp IsFinite(XlaOp operand); + +// Enqueues an iota operation onto the computation. +XlaOp Iota(XlaBuilder* builder, const Shape& shape, int64_t iota_dimension); + +// Enqueues a rank-1 iota operation onto the computation. +XlaOp Iota(XlaBuilder* builder, PrimitiveType type, int64_t size); + +// Enqueues a convert instruction onto the computation that changes the +// element type of the operand array to primitive_type. +XlaOp ConvertElementType(XlaOp operand, PrimitiveType new_element_type); + +// Enqueues a no-op instruction onto the computation that changes +// the element type of the operand array to primitive_type. The +// bit-widths of the source and destination element types must be +// identical. +XlaOp BitcastConvertType(XlaOp operand, PrimitiveType new_element_type); + +// Enqueues a stochastic convert instruction onto the computation that changes +// the element type of the operand array with stochastic rounding to +// primitive_type. +XlaOp StochasticConvertType(XlaOp operand, XlaOp random, + PrimitiveType new_element_type); + +// Enqueues a negate instruction onto the computation. +XlaOp Neg(XlaOp operand); + +// Enqueues a transpose instruction onto the computation. +XlaOp Transpose(XlaOp operand, absl::Span permutation); + +// Enqueues a reverse instruction onto the computation. The order of the +// elements in the given dimensions is reversed (i.e., the element at index i +// is moved to index dimension_size - 1 - i). +XlaOp Rev(XlaOp operand, absl::Span dimensions); + +// Enqueues a sort instruction onto the computation, using 'comparator' for +// comparisons. 'comparator' needs to define a strict weak order. 'is_stable' +// determines whether the stable sorting should be used. +// If only one operand is provided: +// * If the operand is a rank-1 tensor (an array), the result is a sorted array. +// The resulting sorting order has the property that for all index positions +// i, j with i < j, either +// comparator(value[i], value[j]) = comparator(value[j], value[i]) = false or +// comparator(value[i], value[j]) = true. +// * If the operand has higher rank, the operand is sorted along the provided +// dimension. For example, for a rank-2 tensor (a matrix), a dimension value +// of 0 will independently sort every column, and a dimension value of 1 will +// independently sort each row. If no dimension number is provided, then the +// last dimension is chosen by default. For the dimension which is sorted, the +// same sorting order applies as in the rank-1 case. +// +// If more than one operand is provided: +// * All operands must be tensors with the same dimensions. The element types of +// the tensors may be different. +// * The result is a tuple that consists of the operands in sorted order (along +// the provided dimension, as above). The same permutation as implied by the +// comparison computation is applied to all operand tensors. When comparing +// two index positions, 'comparator' is called with 2 * n scalar parameters, +// where parameter 2 * i and 2 * i + 1 correspond to the value of operand i at +// two index positions. +// Default comparator computations can be found in lib/comparators.h +XlaOp Sort(absl::Span operands, const XlaComputation& comparator, + int64_t dimension = -1, bool is_stable = false); + +// Enqueues a clamp instruction onto the computation. +XlaOp Clamp(XlaOp min, XlaOp operand, XlaOp max); + +// Enqueues a map instruction onto the computation. +XlaOp Map(XlaBuilder* builder, absl::Span operands, + const XlaComputation& computation, + absl::Span dimensions, + absl::Span static_operands = {}); + +// Enqueues a N(mu, sigma) random number generation instruction onto the +// computation. +XlaOp RngNormal(XlaOp mu, XlaOp sigma, const Shape& shape); + +// Enqueues a U(a, b) random number generation instruction onto the +// computation. Returns values in the semi-open interval [a, b). +XlaOp RngUniform(XlaOp a, XlaOp b, const Shape& shape); + +// Enqueues a B(initial_state) random bit generation instruction onto the +// computation. Returns the new key and random bits with the specified shape. +XlaOp RngBitGenerator(RandomAlgorithm algorithm, XlaOp initial_state, + const Shape& shape); + +// Enqueues a while node onto the computation. +XlaOp While(const XlaComputation& condition, const XlaComputation& body, + XlaOp init); + +// Enqueues a conditional node onto the computation. +XlaOp Conditional(XlaOp predicate, XlaOp true_operand, + const XlaComputation& true_computation, XlaOp false_operand, + const XlaComputation& false_computation); + +// Enqueues either a predicated (if/else) or indexed (switch/case/default) +// conditional node onto the computation. N >= 1 branch_computations and +// branch_operands are matched by index. branch_index selects the branch that +// will be executed. Out of range branch_index uses the N-1'th +// branch_computation as default. +XlaOp Conditional(XlaOp branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + +// Enqueues a ReducePrecision node onto the computation. +XlaOp ReducePrecision(XlaOp operand, int exponent_bits, int mantissa_bits); + +// Enqueues a Gather node onto the computation. +XlaOp Gather(XlaOp input, XlaOp start_indices, + const GatherDimensionNumbers& dimension_numbers, + absl::Span slice_sizes, + bool indices_are_sorted = false); + +// Enqueues a Scatter node onto the computation. +XlaOp Scatter(XlaOp input, XlaOp scatter_indices, XlaOp updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted = false, bool unique_indices = false); +XlaOp Scatter(absl::Span inputs, XlaOp scatter_indices, + absl::Span updates, + const XlaComputation& update_computation, + const ScatterDimensionNumbers& dimension_numbers, + bool indices_are_sorted = false, bool unique_indices = false); + +// Enqueues a Send node onto the computation for device-to-device +// communication. This operation sends the given operand to +// a Recv instruction in a different computation that shares the same channel +// handle. +void Send(XlaOp operand, const ChannelHandle& handle); + +// Variant of Send which takes a token-shaped operand and produces a +// token-shaped value. Tokens are used for ordering side-effecting operations. +// TODO(b/110532604): Replace all uses of the non-token form with this variant. +XlaOp SendWithToken(XlaOp operand, XlaOp token, const ChannelHandle& handle); + +// Enqueues a Recv node onto the computation for device-to-device +// communication. The data comes from a Send instruction in a different +// computation that shares the same channel handle and its shape must be the +// same as the given shape. +XlaOp Recv(XlaBuilder* builder, const Shape& shape, + const ChannelHandle& handle); + +// Variant of Recv which takes a token-shaped operand and produces a two-element +// tuple containing the data value and a token-shaped value. Tokens are used +// for ordering side-effecting operations. +// TODO(b/110532604): Replace all uses of the non-token form with this variant. +XlaOp RecvWithToken(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + +// Enqueues a Send node which transfers data from the device to the host. The +// 'shape_with_layout' argument defines the layout of the data transferred; its +// shape must be compatible with the shape of the operand. The operand must be +// array-shaped. +// TODO(b/111544877): Support tuple shapes. +XlaOp SendToHost(XlaOp operand, XlaOp token, const Shape& shape_with_layout, + const ChannelHandle& handle); + +// Enqueues a Recv node which transfers data from the host to the device. The +// given shape must contain a layout and must be an array. +// TODO(b/111544877): Support tuple shapes. +XlaOp RecvFromHost(XlaOp token, const Shape& shape, + const ChannelHandle& handle); + +// Enqueues an operation (AfterAll) with no operands that produces a +// token-shaped value. Tokens are used for ordering side-effecting operations. +// This is a separate method from AfterAll to facility the removal of +// operand-less AfterAll instructions. +// TODO(b/110532604): Remove this function when all tokens are derived from a +// single token generated or passed into the entry computation. +XlaOp CreateToken(XlaBuilder* builder); + +// Enqueues an AfterAll instruction which produces a token-shaped value and +// takes a variadic number of token-shaped operands. The number of operands must +// be greater than zero. Used for joining tokens. +XlaOp AfterAll(XlaBuilder* builder, absl::Span tokens); + +// Normalizes operand across spatial and batch dimensions for each feature. +// +// Returns a tuple (normalized, batch_mean, batch_var) where `normalized` +// is the normalized result and batch_mean and batch_var are the mean and +// variance, respectively, across batch for the operand. +XlaOp BatchNormTraining(XlaOp operand, XlaOp scale, XlaOp offset, float epsilon, + int64_t feature_index); + +// Normalizes operand across spatial and batch dimensions for each feature. +// +// `BatchNormInference` is equivalent to calling `BatchNormTraining` without +// computing `mean` and `variance` for each batch inside the operation. It +// uses the input `mean` and `variance` instead as estimated values. The +// purpose of this op is to reduce latency in inference, hence the name +// `BatchNormInference`. +// +// The output has the same shape as `operand`, and contains the normalized +// values for each batch. +XlaOp BatchNormInference(XlaOp operand, XlaOp scale, XlaOp offset, XlaOp mean, + XlaOp variance, float epsilon, int64_t feature_index); + +// Calculates the gradients of a batch norm op. +// +// The inputs `batch_mean` and `batch_var` represent the mean and variance +// across the batch. +// +// Returns a tuple of three elements: +// - grad_operand: Gradient with respect to input `operand` +// - grad_offset: Gradient with respect to input `offset` +// - grad_scale: Gradient with respect to input `scale` +XlaOp BatchNormGrad(XlaOp operand, XlaOp scale, XlaOp batch_mean, + XlaOp batch_var, XlaOp grad_output, float epsilon, + int64_t feature_index); + +// Returns the size of the given dimension of the operand. The operand must be +// array shaped. +XlaOp GetDimensionSize(XlaOp operand, int64_t dimension); + +// Sets the size of the given dimension of the operand. The operand must be +// array shaped. The result will have the same shape as the operand, but the +// given dimension will be dynamic (if not already). +XlaOp SetDimensionSize(XlaOp operand, XlaOp val, int64_t dimension); + +// Returns the same op but with dynamic dimension removed. +XlaOp RemoveDynamicDimension(XlaOp operand, int64_t dimension); + +// Implementation details below this point. +// + +// Free function template implementations. + +template +XlaOp ConstantR0(XlaBuilder* builder, NativeT value) { + return ConstantLiteral(builder, LiteralUtil::CreateR0(value)); +} + +template +XlaOp ConstantR1(XlaBuilder* builder, absl::Span values) { + BorrowingLiteral literal( + reinterpret_cast(values.begin()), + ShapeUtil::MakeShape(primitive_util::NativeToPrimitiveType(), + {static_cast(values.size())})); + return ConstantLiteral(builder, literal); +} + +template +XlaOp ConstantR1(XlaBuilder* builder, int64_t length, NativeT value) { + Literal literal(ShapeUtil::MakeShape( + primitive_util::NativeToPrimitiveType(), {length})); + literal.PopulateWithValue(value); + return ConstantLiteral(builder, literal); +} + +inline XlaOp ConstantR1(XlaBuilder* builder, const tsl::core::Bitmap& values) { + return ConstantLiteral(builder, LiteralUtil::CreateR1(values)); +} + +template +XlaOp ConstantR2(XlaBuilder* builder, + std::initializer_list> values) { + return ConstantLiteral(builder, LiteralUtil::CreateR2(values)); +} + +template +XlaOp ConstantFromArrayWithLayout(XlaBuilder* builder, + const Array& values, + const Layout& layout) { + return ConstantLiteral( + builder, LiteralUtil::CreateFromArrayWithLayout(values, layout)); +} + +template +XlaOp ConstantFromArray(XlaBuilder* builder, const Array& values) { + return ConstantLiteral(builder, + LiteralUtil::CreateFromArray(values)); +} + +template +XlaOp ConstantR2FromArray2DWithLayout(XlaBuilder* builder, + const Array2D& values, + const Layout& layout) { + return ConstantLiteral( + builder, LiteralUtil::CreateFromArrayWithLayout(values, layout)); +} + +template +XlaOp ConstantR2FromArray2D(XlaBuilder* builder, + const Array2D& values) { + return ConstantLiteral(builder, + LiteralUtil::CreateR2FromArray2D(values)); +} + +template +XlaOp ConstantR3FromArray3DWithLayout(XlaBuilder* builder, + const Array3D& values, + const Layout& layout) { + return ConstantLiteral( + builder, + LiteralUtil::CreateR3FromArray3DWithLayout(values, layout)); +} + +template +XlaOp ConstantR3FromArray3D(XlaBuilder* builder, + const Array3D& values) { + return ConstantFromArray(builder, values); +} + +template +XlaOp ConstantR4FromArray4DWithLayout(XlaBuilder* builder, + const Array4D& values, + const Layout& layout) { + return ConstantFromArrayWithLayout(builder, values, layout); +} + +template +XlaOp ConstantR4FromArray4D(XlaBuilder* builder, + const Array4D& values) { + return ConstantFromArray(builder, values); +} + +// Switches from automatic SPMD partitioning to manual partitioning. Converts a +// full-shaped tensor (to be automatically partitioned by SPMD partitioner) to a +// shard-shaped tensor to be consumed by manually partitioned ops. +StatusOr ConvertSpmdFullToShardShape( + xla::XlaBuilder* builder, xla::XlaOp input, int single_dim, + const xla::OpSharding& manual_sharding, + absl::Span unspecified_dims); + +// Switches from manual partitioning to automatic SPMD partitioning. Converts a +// shard-shaped tensor (manually partitioned in SPMD-style) to a full-shaped +// tensor to be partitioned automatically by the SPMD partitioner. +StatusOr ConvertSpmdShardToFullShape( + xla::XlaBuilder* builder, xla::XlaOp input, const xla::Shape& output_shape, + int single_dim, const xla::OpSharding& manual_sharding, + absl::Span unspecified_dims); + +} // namespace xla + +#endif // XLA_CLIENT_XLA_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_computation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_computation.h new file mode 100644 index 0000000000000000000000000000000000000000..4f70662d79c6d9c12e2d6c625c2360bea001ea66 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/client/xla_computation.h @@ -0,0 +1,72 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CLIENT_XLA_COMPUTATION_H_ +#define XLA_CLIENT_XLA_COMPUTATION_H_ + +#include +#include +#include + +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/status_macros.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// The computation graph that the user builds up with the XlaBuilder. +class XlaComputation { + public: + XlaComputation() : unique_id_(-1) {} + XlaComputation(HloModuleProto proto) + : unique_id_(proto.id()), proto_(std::move(proto)) {} + + ~XlaComputation() = default; + + XlaComputation(const XlaComputation&) = delete; + XlaComputation& operator=(const XlaComputation&) = delete; + + XlaComputation(XlaComputation&& from) = default; + + XlaComputation& operator=(XlaComputation&& from) = default; + + // Returns the "program shape" (parameter and return shapes) for this + // computation. + StatusOr GetProgramShape() const; + + const std::string& name() const { return proto().name(); } + + const HloModuleProto& proto() const { return proto_; } + HloModuleProto* mutable_proto() { return &proto_; } + + // Requests that we snapshot the computation into a serializable protocol + // buffer form. + StatusOr> Snapshot() const; + + // Returns true if this object is a null Computation. + bool IsNull() const { return unique_id_ == -1; } + + private: + XlaComputation(const int64_t unique_id) : unique_id_(unique_id) {} + friend class XlaBuilder; + + int64_t unique_id_; + HloModuleProto proto_; +}; + +} // namespace xla + +#endif // XLA_CLIENT_XLA_COMPUTATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/comparison_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/comparison_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0c11edf302d464640432c43c1df2c41b80d079eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/comparison_util.h @@ -0,0 +1,259 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_COMPARISON_UTIL_H_ +#define XLA_COMPARISON_UTIL_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/primitive_util.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +namespace xla { + +// A utility class for primitive comparisons. A comparison includes three +// components: the type of the elements being compared (F32, S16, etc), whether +// it is a partial or total order comparison, and the actual comparison operator +// (==, <=, >, etc). +// +// Note that integer comparisons are always total order. Float comparisons can +// be either total or partial order. +// +// Some examples: +// +// Comparison a( +// Comparison::Direction::kLt, +// xla::PrimitiveType::BF16, +// Comparison::Order::kTotal +// ); +// a.ToString(); /* ".LT.BF16.TOTALORDER" */ +// +// Comparison b(Comparison::Direction::kEq, xla::PrimitiveType::U32); +// b.IsTotalOrder(); /* true */ +class Comparison { + public: + // Represents the ordering of the comparison. + enum class Order : uint8_t { + // https://en.wikipedia.org/wiki/Total_order + kTotal, + // https://en.wikipedia.org/wiki/Partially_ordered_set + kPartial, + }; + + // Represents different comparison operations. + enum class Direction : uint8_t { + kEq, + kNe, + kGe, + kGt, + kLe, + kLt, + }; + + // (DEPRECATED) Represents the type of comparison. Prefer xla::PrimitiveType + // and Comparison::Order, since there are multiple floating point + // representations that support total ordering. + enum class [[deprecated("Use PrimitiveType and Order")]] Type : uint8_t{ + kFloat, + kFloatTotalOrder, + kSigned, + kUnsigned, + }; + + Comparison() = delete; + + // This will default to the expected behavior for Comparison::Order: integers + // will use total ordering, and floats will use partial ordering. + explicit Comparison(Direction dir, PrimitiveType type); + + // Pass in a Comparison::Order to specify a non-default ordering, e.g., some + // targets may support total order floating point type comparisons. + explicit Comparison(Direction dir, PrimitiveType type, Order order); + + // Returns a comparison with a primitive type matching the Comparison::Type + // and using a default bit width of 32. For example, + // Comparison(Direction::kLt, Type::kFloat).PrimitiveType() /* F32 */ + [[deprecated( + "Use Comparison(Comparison::Direction, " + "PrimitiveType)")]] explicit Comparison(Direction dir, Type type); + + inline Direction GetDirection() const { return dir_; } + inline PrimitiveType GetPrimitiveType() const { return primitive_type_; } + inline Order GetOrder() const { return order_; } + + [[deprecated("Use GetPrimitiveType() and GetOrder()")]] inline Type GetType() + const { + return type_; + } + + inline bool IsEq() const { return dir_ == Direction::kEq; } + inline bool IsNe() const { return dir_ == Direction::kNe; } + inline bool IsGe() const { return dir_ == Direction::kGe; } + inline bool IsGt() const { return dir_ == Direction::kGt; } + inline bool IsLt() const { return dir_ == Direction::kLt; } + inline bool IsTotalOrder() const { return order_ == Order::kTotal; } + inline bool IsPartialOrder() const { return order_ == Order::kPartial; } + + // Returns whether this is a floating point total order comparison. + inline bool IsF32TotalOrder() const { + return primitive_type_ == PrimitiveType::F32 && IsTotalOrder(); + } + inline bool IsBf16TotalOrder() const { + return primitive_type_ == PrimitiveType::BF16 && IsTotalOrder(); + } + + // Returns whether this is a standard comparison, i.e., what you would expect + // as the industry standard on most architectures. + inline bool IsStandardF32() const { + return primitive_type_ == PrimitiveType::F32 && IsPartialOrder(); + } + inline bool IsStandardBf16() const { + return primitive_type_ == PrimitiveType::BF16 && IsPartialOrder(); + } + inline bool IsStandardS32() const { + return primitive_type_ == PrimitiveType::S32 && IsTotalOrder(); + } + inline bool IsStandardU32() const { + return primitive_type_ == PrimitiveType::U32 && IsTotalOrder(); + } + + inline bool IsIntegralPrimitiveType() const { + return primitive_util::IsIntegralType(primitive_type_); + } + inline bool IsFloatingPointPrimitiveType() const { + return primitive_util::IsFloatingPointType(primitive_type_); + } + + // Returns whether (a dir a) is always true for this comparison. + bool IsReflexive() const; + + // Returns whether (a dir a) is always false for this comparison. + bool IsAntireflexive() const; + + // Gets the converse of the given comparison direction (e.g. >= turns to <=). + // Useful when commuting operands to get constants into immediate-accepting + // positions in the ISA. + Comparison Converse() const; + + // Gets the inverse of the given comparison if it exists (e.g. >= turns to <). + // Returns optional value because not all inversions may be supported. + std::optional Inverse() const; + + // Returns a string version of this comparison, e.g., ".GT.F32.TOTALORDER" + std::string ToString(std::string prefix1 = ".", std::string prefix2 = ".", + std::string prefix3 = ".") const; + + // Returns a comparison operator: (T, T) -> bool for this Comparison's + // Direction. + template + inline std::function GetComparator() const { + switch (GetDirection()) { + case Direction::kEq: + return std::equal_to(); + case Direction::kNe: + return std::not_equal_to(); + case Direction::kGe: + return std::greater_equal(); + case Direction::kGt: + return std::greater(); + case Direction::kLe: + return std::less_equal(); + case Direction::kLt: + return std::less(); + } + } + + template + inline bool Compare(const T a, const T b) const { + DCHECK(primitive_util::IsCanonicalRepresentation(primitive_type_)); + if constexpr (is_specialized_floating_point_v) { + if (IsTotalOrder()) { + // -NaN < -Inf < -Finite < -0 < +0 < +Finite < +Inf < +NaN + // Reference: + // https://www.tensorflow.org/xla/operation_semantics#element-wise_comparison_operations + using R = SignedIntegerTypeForSizeType; + return GetComparator()(ToSignMagnitude(a), ToSignMagnitude(b)); + } + } + // Applies the comparison from this Comparison's direction and ordering. + return GetComparator()(a, b); + } + + // Returns the Comparison::Type for the given primitive type. This assumes + // that each numerical representation follows the standard behavior, e.g., + // integers are total order and floats are partial order. + [[deprecated("Use PrimitiveType and Order")]] static Comparison::Type + DefaultComparisonType(PrimitiveType type); + + private: + // The direction of the Comparison, e.g., GT. + const Direction dir_; + // The primitive type of the Comparison operands, e.g., F32. + const PrimitiveType primitive_type_; + // The ordering of the Comparison, e.g., kPartial. + const Order order_; + // The Type of the Comparison. This tries to mesh together the ordering and + // the numerical data classification. + [[deprecated]] const Type type_; +}; + +using ComparisonDirection = Comparison::Direction; +using ComparisonOrder = Comparison::Order; + +inline std::ostream& operator<<(std::ostream& os, const Comparison& cmp) { + return os << cmp.ToString(); +} + +std::string ComparisonDirectionToString(Comparison::Direction direction); +std::string ComparisonTypeToString(Comparison::Type type); +absl::string_view ComparisonPrimitiveTypeToString(PrimitiveType type); +absl::string_view ComparisonOrderToString(Comparison::Order order); + +StatusOr StringToComparisonDirection( + absl::string_view direction); +StatusOr StringToComparisonType(absl::string_view comparison); +StatusOr StringToComparisonOrder(absl::string_view order); + +// Returns a comparison function using the provided key function on each value, +// i.e. `key_fn(a) < key_fn(b)`. +template +auto LessThanByKey(KeyFn&& key_fn) { + return [=](const auto& a, const auto& b) { return key_fn(a) < key_fn(b); }; +} + +// Two comparisons are equivalent iff they have the same direction, precision, +// and ordering. +inline bool operator==(const Comparison& a, const Comparison& b) { + return a.GetDirection() == b.GetDirection() && + a.GetPrimitiveType() == b.GetPrimitiveType() && + a.GetOrder() == b.GetOrder(); +} + +inline bool operator!=(const Comparison& a, const Comparison& b) { + return !(a == b); +} + +} // namespace xla + +#endif // XLA_COMPARISON_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/cpu_function_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/cpu_function_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..99e0eaa1c578c70d0a086f64c89a3b2111cab511 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/cpu_function_runtime.h @@ -0,0 +1,224 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_CPU_FUNCTION_RUNTIME_H_ +#define XLA_CPU_FUNCTION_RUNTIME_H_ + +#include + +#include +#include + +namespace xla { +namespace cpu_function_runtime { + +struct EncodedBufferInfo { + uint64_t packed_kind_and_size = 0; + uint32_t entry_param_number = -1; + uint32_t result_param_number = -1; +}; + +// Stores information about one buffer used by an XLA:CPU compiled function. +// These buffers are used for holding inputs to the computation, outputs from +// the computation and as temporary scratch space. +class BufferInfo { + public: + // Creates a BufferInfo from a serialized encoding generated by `Encode`. + explicit constexpr BufferInfo(const EncodedBufferInfo& encoded) + : kind_(UnpackKind(encoded.packed_kind_and_size)), + size_(UnpackSize(encoded.packed_kind_and_size)), + entry_param_number_(encoded.entry_param_number), + result_param_number_(encoded.result_param_number) {} + + // Returns true if this buffer stores a constant. These never need to be + // allocated by the runtime. + bool is_constant() const { return kind() == Kind::kConstant; } + + // Returns true if this buffer stores an entry parameter. These may or may + // not need to be allocated by the runtime, depending on + // XlaCompiledCpuFunction::AllocMode. + bool is_entry_parameter() const { + return kind() == Kind::kParameter && entry_param_number_ >= 0; + } + + // Returns the entry parameter number of this buffer. + uint32_t entry_parameter_number() const { + assert(is_entry_parameter()); + return entry_param_number_; + } + + void set_result_parameter_number(uint32_t param_number) { + result_param_number_ = param_number; + } + + bool is_result_parameter() const { + // Note: the kind is not unique, e.g. could be a kTempBuffer, or a + // kParameter if it is an in-out argument. + return result_param_number_ >= 0; + } + + uint32_t result_parameter_number() const { + assert(is_result_parameter()); + return result_param_number_; + } + + // Returns true if this buffer is temporary scratch space required by the XLA + // computations. These are always allocated by the runtime. + bool is_temp_buffer() const { return kind() == Kind::kTempBuffer; } + + // Returns true if this buffer is allocated on the C stack or into registers. + // These buffers are never allocated by the runtime. + bool is_on_stack_buffer() const { return kind() == Kind::kOnStackBuffer; } + + // Returns the size for this buffer. + uint64_t size() const { return size_; } + + // Encodes this BufferInfo into two 64 bit integers that can be used to + // reconstruct the BufferInfo later using the constructor. We need this + // because we use BufferInfo in places where using protocol buffers would + // negatively impact binary size. + EncodedBufferInfo Encode() const { + static_assert(sizeof(*this) == 16, ""); + EncodedBufferInfo ret; + ret.packed_kind_and_size = Pack(kind(), size_); + ret.entry_param_number = entry_param_number_; + ret.result_param_number = result_param_number_; + return ret; + } + + bool operator==(const BufferInfo& buffer_info) const { + if (kind() != buffer_info.kind() || size() != buffer_info.size()) { + return false; + } + return !is_entry_parameter() || + entry_parameter_number() == buffer_info.entry_parameter_number(); + } + + // Factory methods: + + static BufferInfo MakeTempBuffer(uint64_t size) { + return BufferInfo(Kind::kTempBuffer, size); + } + static BufferInfo MakeConstant(uint64_t size) { + return BufferInfo(Kind::kConstant, size); + } + // Note: in-out parameters are possible by first creating an entry parameter + // and then calling set_result_parameter_number(). + static BufferInfo MakeEntryParameter(uint64_t size, + uint32_t entry_param_number) { + return BufferInfo(Kind::kParameter, size, entry_param_number); + } + // Only used in tests. Here we use kTempBuffer but it is unimportant. + static BufferInfo MakeResultParameter(uint64_t size, + uint32_t result_param_number) { + // Here we + return BufferInfo(Kind::kTempBuffer, size, /*entry_param_number=*/-1, + result_param_number); + } + static BufferInfo MakeOnStackBuffer(uint64_t size) { + return BufferInfo(Kind::kOnStackBuffer, size); + } + + private: + BufferInfo() = default; + + enum class Kind : uint64_t { + kConstant, + kTempBuffer, + kParameter, + kOnStackBuffer + }; + + Kind kind() const { return static_cast(kind_); } + + explicit BufferInfo(Kind kind, uint64_t size) + : BufferInfo(kind, size, + /*entry_param_number=*/-1, + /*result_param_number=*/-1) {} + explicit BufferInfo(Kind kind, uint64_t size, uint32_t entry_param_number) + : BufferInfo(kind, size, entry_param_number, + /*result_param_number=*/-1) {} + explicit BufferInfo(Kind kind, uint64_t size, uint32_t entry_param_number, + uint32_t result_param_number) + : kind_(kind), + size_(size), + entry_param_number_(entry_param_number), + result_param_number_(result_param_number) {} + + static uint64_t Pack(Kind kind, uint64_t size) { + return (static_cast(size) << 2) | static_cast(kind); + } + + static inline constexpr Kind UnpackKind(uint64_t packed) { + return static_cast((packed << 62) >> 62); + } + + static inline constexpr uint64_t UnpackSize(uint64_t packed) { + return packed >> 2; + } + + Kind kind_ : 2; + uint64_t size_ : 62; + int32_t entry_param_number_ = -1; + int32_t result_param_number_ = -1; +}; + +// Align to 64-bytes, to mimic tsl::Allocator::kAllocatorAlignment. +inline constexpr size_t Align() { return 64; } + +// The minimum alignment of buffers passed to XLA:CPU. +inline constexpr size_t MinAlign() { return 16; } + +// When declaring variables that will be passed to an XLA instance as input via +// set_arg_data(), be it a regular input or a resource variable in the graph, +// the C++ variables must be aligned. +// +// Example usage: +// XLA_ALIGN std::array arg_x; +// XLA_ALIGN float arg_y; +// xla_instance.set_arg_data(0, arg_x.date()); +// xla_instance.set_arg_data(0, &arg_y); +#define XLA_ALIGN alignas(xla::cpu_function_runtime::Align()) + +// AlignedBufferBytes returns the sum of the size of each buffer in +// `buffer_infos`, skipping constants, on-stack buffers and, if +// allocate_entry_params is false, entry parameters. There are `n` entries in +// `buffer_infos`. Each buffer is aligned to Align() byte boundaries. +size_t AlignedBufferBytes(const BufferInfo* buffer_infos, size_t n, + bool allocate_entry_params); + +// MallocContiguousBuffers allocates buffers for use by the entry point +// generated by tfcompile. There are `n` entries in `buffer_infos`. If +// `annotate_initialized` is set, the allocated memory will be annotated as +// having been initialized - this is useful when allocating temporary buffers. +// If allocate_entry_params is true then allocates temp buffers and entry +// parameters, otherwise allocated only temp buffers. Slots in `bufs` +// corresponding to unallocated buffers are set to nullptr. +// +// A single contiguous block of memory is allocated, and portions of it are +// parceled out into `bufs`, which must have space for `n` entries. Returns +// the head of the allocated contiguous block, which should be passed to +// FreeContiguous when the buffers are no longer in use. +void* MallocContiguousBuffers(const BufferInfo* buffer_infos, size_t n, + bool allocate_entry_params, void** bufs, + bool annotate_initialized); + +// FreeContiguous frees the contiguous block of memory allocated by +// MallocContiguousBuffers. +void FreeContiguous(void* contiguous); +} // namespace cpu_function_runtime +} // namespace xla + +#endif // XLA_CPU_FUNCTION_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_flags.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_flags.h new file mode 100644 index 0000000000000000000000000000000000000000..6ec89d7746e058a811c1b42b8ac3d3a33052eead --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_flags.h @@ -0,0 +1,108 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_DEBUG_OPTIONS_FLAGS_H_ +#define XLA_DEBUG_OPTIONS_FLAGS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/xla.pb.h" +#include "tsl/platform/logging.h" +#include "tsl/util/command_line_flags.h" + +namespace xla { + +// Construct flags which write to the debug_options proto when parsed. Existing +// contents of debug_options is used as the default. Can be called multiple +// times. +void MakeDebugOptionsFlags(std::vector* flag_list, + DebugOptions* debug_options); + +// Appends flag definitions for debug options to flag_list. Existing +// contents of debug_options is used as the default. If debug_options is null, +// uses global defaults. Modifies global state on first call. +void AppendDebugOptionsFlags(std::vector* flag_list, + DebugOptions* debug_options = nullptr); + +// Fetches a DebugOptions proto message from flags provided to the program. +// Flags must be registered with the flags parser using AppendDebugOptionsFlags +// first. +DebugOptions GetDebugOptionsFromFlags(); + +// Gets a DebugOptions proto that reflects the defaults as if no flags were set. +DebugOptions DefaultDebugOptionsIgnoringFlags(); + +// Consumes a unit of "compiler fuel" for the given pass, and returns false if +// we're out of fuel for that pass. +// +// Compiler fuel is a debugging tool useful for bisecting compiler passes. Each +// time a pass "does something", it consumes a unit of fuel, and once it's out +// of fuel, it stops doing any transformations. This way if you suspect a pass +// has a bug, you can bisect the amount of fuel it gets and find exactly which +// change causes the problem. +// +// The very first time a pass runs out of fuel, `just_ran_out` is set to true. +// This lets you take action (e.g. log a message). But see also the convenience +// overload below. +// +// By default all passes have infinite fuel. You can restrict how much fuel a +// pass has by specifying XLA_FLAGS=--xla_fuel=PASS1=NUM1,PASS2=NUM2,... +// +// If a user specifies --xla_fuel=PASS=NUM but ConsumeFuel(PASS) is not called +// before the program exits, we'll print a warning. +// +// We recommend as a convention you use a pass's name for the `pass` argument, +// but any value is accepted. +bool ConsumeFuel(absl::string_view pass, bool* just_ran_out = nullptr); + +// Overload of ConsumeFuel that lets you pass in a functor which generates a log +// message when we first run out of fuel for a pass. This is useful because +// you're usually interested in what *would have* happened right when we ran out +// of fuel. +// +// Example usage: +// +// if (ConsumeFuel("pass-name", [&] { return "Not fooing bar."; })) { +// return; +// } +// +template +bool ConsumeFuel(absl::string_view pass, + const MsgGenerator& ran_out_of_fuel_msg) { + bool just_ran_out = false; + bool ret = ConsumeFuel(pass, &just_ran_out); + if (just_ran_out) { + LOG(ERROR) << "Out of fuel for \"" << pass + << "\": " << ran_out_of_fuel_msg(); + } + return ret; +} + +// By default compiler fuel is global; if you run two compiler threads, they +// will consume from the same fuel pool. +// +// Calling this function changes the behavior of fuel for the current thread: +// From this point onward, it will use a private fuel pool. The thread-local +// fuel pool is initialized to the values the global fuel pool had at process +// startup. +// +// You may call this function twice in the same thread to reset its fuel pool +// back to the initial state. +void ResetThreadLocalFuel(); + +} // namespace xla + +#endif // XLA_DEBUG_OPTIONS_FLAGS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_parsers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_parsers.h new file mode 100644 index 0000000000000000000000000000000000000000..0350acccff3f34af05fee1db32b1c0f797d39c37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/debug_options_parsers.h @@ -0,0 +1,52 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_DEBUG_OPTIONS_PARSERS_H_ +#define XLA_DEBUG_OPTIONS_PARSERS_H_ + +#include +#include + +#include "absl/strings/numbers.h" +#include "absl/strings/str_split.h" +#include "xla/xla.pb.h" + +namespace xla { + +template +void parse_xla_backend_extra_options(T* extra_options_map, + std::string comma_separated_values) { + std::vector extra_options_parts = + absl::StrSplit(comma_separated_values, ','); + + // The flag contains a comma-separated list of options; some options + // have arguments following "=", some don't. + for (const auto& part : extra_options_parts) { + size_t eq_pos = part.find_first_of('='); + if (eq_pos == std::string::npos) { + (*extra_options_map)[part] = ""; + } else { + std::string value = ""; + if (eq_pos + 1 < part.size()) { + value = part.substr(eq_pos + 1); + } + (*extra_options_map)[part.substr(0, eq_pos)] = value; + } + } +} + +} // namespace xla + +#endif // XLA_DEBUG_OPTIONS_PARSERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/error_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/error_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..cde904940ecec08388ad48e93a6ef101ea74e99d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/error_spec.h @@ -0,0 +1,54 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ERROR_SPEC_H_ +#define XLA_ERROR_SPEC_H_ + +namespace xla { + +// Structure describing permissible absolute and relative error bounds. +struct ErrorSpec { + explicit ErrorSpec(float aabs, float arel = 0, bool relaxed_nans = false) + : abs(aabs), rel(arel), relaxed_nans(relaxed_nans) {} + + float abs; // Absolute error bound. + float rel; // Relative error bound. + + // If relaxed_nans is true then any result is valid if we are expecting NaNs. + // In effect, this allows the tested operation to produce incorrect results + // for inputs outside its mathematical domain. + bool relaxed_nans; + + // If true, then we don't check for bitwise equality of NaNs. All NaNs are + // considered equivalent. + bool all_nans_are_equivalent = true; + + // If this is true, then we treat each +/-inf in the actual result as + // equivalent to our choice of either +/-inf or the min/max floating-point + // value. + // + // If the expected result is +/-inf, the actual result must still be +/-inf. + // + // In effect, this allows the tested operation to overflow, so long as it's + // overflowing on "large" values. + // + // (We could have a symmetric more_infs_ok flag if necessary; right now it + // appears not to be.) + bool fewer_infs_ok = false; +}; + +} // namespace xla + +#endif // XLA_ERROR_SPEC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/executable_run_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/executable_run_options.h new file mode 100644 index 0000000000000000000000000000000000000000..31ba23bf3b7a141aa85e540dd84b70f1c5e77627 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/executable_run_options.h @@ -0,0 +1,239 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_EXECUTABLE_RUN_OPTIONS_H_ +#define XLA_EXECUTABLE_RUN_OPTIONS_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/status/statusor.h" + +// These classes are forward declared so that ExecutableRunOptions can be linked +// into an XLA-compiled binary without having to link all of the pointed-to +// objects (e.g., for an ahead-of-time compiled CPU binary, the gpu tools don't +// need to be linked). +namespace stream_executor { +class Stream; +class Event; +class Platform; +class DeviceMemoryAllocator; +class DeviceMemoryBase; +} // namespace stream_executor + +namespace Eigen { +struct ThreadPoolDevice; +} // namespace Eigen + +namespace tsl { +template +class AsyncValueRef; +} // namespace tsl + +namespace xla { + +class DeviceAssignment; +class ExecutionProfile; +class Shape; + +namespace gpu { +class GpuExecutableRunOptions; +} // namespace gpu + +// A unique identifier for a particular "logical execution" of an XLA model. +// +// A logical execution might encompass multiple executions of one or more +// HloModules. Runs that are part of the same logical execution can +// communicate via collective ops (e.g. kAllToAll), whereas runs that are part +// of different logical executions are isolated. +class RunId { + public: + // Creates a new, unique RunId. + RunId(); + explicit RunId(int64_t value) : data_(value) {} + + RunId(const RunId&) = default; + RunId& operator=(const RunId&) = default; + friend bool operator==(const RunId& a, const RunId& b); + std::string ToString() const; + int64_t ToInt() const; + + template + friend H AbslHashValue(H h, const RunId& id) { + return H::combine(std::move(h), id.data_); + } + + private: + int64_t data_; +}; + +// Callback used by the GPU backend only. This is an "one-sided" version of +// ThenDoHostCallback that enqueues a callback onto a stream. The difference +// with ThenDoHostCallback is that the device does not block waiting for the +// callback to complete; instead the callback is scheduled by the runtime. +// This functionality must be provided by the caller, and hence is provided in +// callback form. +using ThenExecuteFunction = + std::function)>; + +// Callback for sending device buffer to a channel. Returned event will be +// recorded on a `stream` once the send operation is completed and data was +// copied from the `src` memory. `frontend_attrs` contains frontend specific +// attributes for the send. +using SendDeviceMemoryFunction = + std::function>( + int64_t channel_id, stream_executor::Stream* stream, const Shape& shape, + const stream_executor::DeviceMemoryBase& src, + const absl::flat_hash_map& frontend_attrs)>; + +// Callback for receiving device buffer from a channel. Returned event will be +// recorded on a `stream` once the recv operation is completed and data was +// copied into the `dst` memory. `frontend_attrs` contains frontend specific +// attributes for the receive. +using RecvDeviceMemoryFunction = + std::function>( + int64_t channel_id, stream_executor::Stream* stream, const Shape& shape, + stream_executor::DeviceMemoryBase* dst, + const absl::flat_hash_map& frontend_attrs)>; + +// Class containing options for running a LocalExecutable. +class ExecutableRunOptions { + public: + // Specifies the allocator to use during execution. + ExecutableRunOptions& set_allocator( + stream_executor::DeviceMemoryAllocator* allocator); + stream_executor::DeviceMemoryAllocator* allocator() const; + + // If set, this is the device to run the computation on. Valid device_ordinal + // values are: 0 to # of devices - 1. These values are identical to the device + // ordinal values used by StreamExecutor. The device must be of the same type + // as the executable was compiled for. A value of -1 indicates this option has + // not been set. + ExecutableRunOptions& set_device_ordinal(int device_ordinal); + int device_ordinal() const; + + // If set, this is the stream to run the computation on. The platform of the + // stream must match the platform the executable was built for. A value of + // nullptr indicates the option has not been set. + ExecutableRunOptions& set_stream(stream_executor::Stream* stream); + stream_executor::Stream* stream() const; + + // If set, this is the stream to perform host to device transfers on (e.g. any + // pre-computation transfers). The platform of the stream must match the + // platform the executable was built for. A value of nullptr indicates the + // option has not been set. + ExecutableRunOptions& set_host_to_device_stream( + stream_executor::Stream* stream); + stream_executor::Stream* host_to_device_stream() const; + + // If set, this is the stream to perform device to host transfers on. + // The platform of the stream must match the platform the executable was + // built for. A value of nullptr indicates the option has not been set. + ExecutableRunOptions& set_device_to_host_stream( + stream_executor::Stream* stream); + stream_executor::Stream* device_to_host_stream() const; + + // Sets the thread pool device on which to run Eigen subcomputations. + // + // This field must be set for XLA:CPU models that call Eigen routines, but may + // be null otherwise. Routines that use this field should always CHECK (or + // TF_RET_CHECK) that it's not null before dereferencing it, so that users get + // a clean crash rather than a segfault. + // + // Does not take ownership. + ExecutableRunOptions& set_intra_op_thread_pool( + const Eigen::ThreadPoolDevice* intra_op_thread_pool); + const Eigen::ThreadPoolDevice* intra_op_thread_pool() const; + + // If set, profiling information is written to 'profile'. + ExecutionProfile* execution_profile() const; + ExecutableRunOptions& set_execution_profile(ExecutionProfile* profile); + + ExecutableRunOptions& set_device_assignment( + const DeviceAssignment* device_assignment); + const DeviceAssignment* device_assignment() const; + + ExecutableRunOptions& set_rng_seed(int rng_seed); + int rng_seed() const; + + ExecutableRunOptions& set_launch_id(int32_t launch_id) { + launch_id_ = launch_id; + return *this; + } + + int32_t launch_id() const { return launch_id_; } + + ExecutableRunOptions& set_run_id(RunId id); + RunId run_id() const; + + // See documentation on ThenExecuteFunction. + ExecutableRunOptions& set_then_execute_function(ThenExecuteFunction* f) { + then_execute_function_ = f; + return *this; + } + ThenExecuteFunction* then_execute_function() const { + return then_execute_function_; + } + + // See documentation on SendDeviceMemoryFunction. + ExecutableRunOptions& set_send_device_memory_function( + SendDeviceMemoryFunction* f) { + send_device_memory_function_ = f; + return *this; + } + SendDeviceMemoryFunction* send_device_memory_function() const { + return send_device_memory_function_; + } + + // See documentation on RecvDeviceMemoryFunction. + ExecutableRunOptions& set_recv_device_memory_function( + RecvDeviceMemoryFunction* f) { + recv_device_memory_function_ = f; + return *this; + } + RecvDeviceMemoryFunction* recv_device_memory_function() const { + return recv_device_memory_function_; + } + + // GPU-backend specific options. These are kept out-of-line to avoid bloating + // the size of this dependency for CPU-only AOT builds. + ExecutableRunOptions& set_gpu_executable_run_options( + const gpu::GpuExecutableRunOptions* gpu_executable_run_options); + const gpu::GpuExecutableRunOptions* gpu_executable_run_options() const; + + private: + stream_executor::DeviceMemoryAllocator* allocator_ = nullptr; + int device_ordinal_ = -1; + const DeviceAssignment* device_assignment_ = nullptr; + stream_executor::Stream* stream_ = nullptr; + const Eigen::ThreadPoolDevice* intra_op_thread_pool_ = nullptr; + ExecutionProfile* execution_profile_ = nullptr; + int rng_seed_ = 0; + int32_t launch_id_ = 0; + stream_executor::Stream* device_to_host_stream_ = nullptr; + stream_executor::Stream* host_to_device_stream_ = nullptr; + ThenExecuteFunction* then_execute_function_ = nullptr; + SendDeviceMemoryFunction* send_device_memory_function_ = nullptr; + RecvDeviceMemoryFunction* recv_device_memory_function_ = nullptr; + RunId run_id_; + const gpu::GpuExecutableRunOptions* gpu_executable_run_options_ = nullptr; +}; + +} // namespace xla + +#endif // XLA_EXECUTABLE_RUN_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/execution_options_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/execution_options_util.h new file mode 100644 index 0000000000000000000000000000000000000000..2a69fa2aab2ec5d7f51876bcd433e98c9e2e879e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/execution_options_util.h @@ -0,0 +1,29 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_EXECUTION_OPTIONS_UTIL_H_ +#define XLA_EXECUTION_OPTIONS_UTIL_H_ + +#include "xla/xla.pb.h" + +namespace xla { + +// Create a default ExecutionOptions proto; this proto has its debug options +// populated to the default values taken from flags. +ExecutionOptions CreateDefaultExecutionOptions(); + +} // namespace xla + +#endif // XLA_EXECUTION_OPTIONS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/frontend_attributes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/frontend_attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..de2643beeebb514b5bbaddb9c7d25951c0d6a0c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/frontend_attributes.h @@ -0,0 +1,38 @@ +#ifndef XLA_FRONTEND_ATTRIBUTES_H_ +#define XLA_FRONTEND_ATTRIBUTES_H_ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include + +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { + +// Attribute which indicates that an in-place instruction has disjoint read +// and write regions w.r.t aliased input/output buffers. +inline constexpr char kXlaDisjointReadWriteRegions[] = + "_xla_disjoint_read_write_regions"; + +// Set frontend attribute on 'instruction' which indices that in-place +// 'instruction' has disjoint read/write buffer regions. +void SetDisjointReadWriteRegionsAttr(HloInstruction* instruction); + +// Returns 'true' if in-place 'instruction' has the kXlaDisjointReadWriteRegions +// frontend attribute set (returns false otherwise). +bool HasDisjointReadWriteRegionsAttr(HloInstruction* instruction); + +} // namespace xla + +#endif // XLA_FRONTEND_ATTRIBUTES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator.h new file mode 100644 index 0000000000000000000000000000000000000000..f2095fa1d756c1a87be0140e7d8d5f9d9f8ef5d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator.h @@ -0,0 +1,485 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_EVALUATOR_HLO_EVALUATOR_H_ +#define XLA_HLO_EVALUATOR_HLO_EVALUATOR_H_ + +#define _USE_MATH_DEFINES + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/node_hash_map.h" +#include "absl/types/span.h" +#include "xla/array2d.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/service/call_graph.h" +#include "xla/service/dynamic_dimension_inference.h" +#include "xla/service/shape_inference.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Represents a parsed static while loop. We normalize the loop representation +// so that it starts from the induction_var_init_value and increments by +// step_size until it exceeds or goes below loop_bound. +struct ParsedStaticWhileLoop { + // The number of iterations to be executed. + int64_t trip_count = -1; + // The tuple index of the induction variable in the while argument tuple. + int64_t induction_var_index = -1; + // The induction variable's initial value. + int64_t induction_var_init_value = -1; + // The induction variable is incremented by this number (could be negative) + // in each iteration. + int64_t step_size = -1; + int64_t loop_bound = -1; +}; + +// Indicates whether a parsed while loop is static or dynamic. If the loop is +// static, it contains a value for StaticLoopInfo; otherwise the loop is +// dynamic. We consider a loop dynamic if its induction variable's initial +// value or the loop bound's value depends on the while's parent computation's +// parameter. +struct ParsedWhileLoop { + std::optional static_while_loop; + bool is_dynamic() const { return !static_while_loop.has_value(); } +}; +constexpr ParsedWhileLoop kParsedDynamicWhileLoop = ParsedWhileLoop(); + +// Tries to parse a while loop using a set of predefined patterns. +// Returns the parsing result. +std::optional PatternMatchParseWhileLoop( + const HloInstruction* while_op); + +// Responsible for evaluating HLO and obtain literal as the evaluation results. +// +// This class is not thread-safe. +class HloEvaluator : public ConstDfsHloVisitorWithDefault { + public: + // Only evaluate up to max_loop_iterations per while-loop execution if + // specified. + explicit HloEvaluator(int64_t max_loop_iterations = -1); + + // Called by the evaluator to create an embedded evaluator to execute a + // sub-region of control flow. Subclasses should override this to return an + // instance of the subclass instead. + virtual std::unique_ptr CreateEmbedded( + int64_t max_loop_iterations) { + return std::make_unique(max_loop_iterations); + } + + // Enables subclasses to be notified when a new computation is being + // evaluated. + virtual void OnEvaluateComputation(const HloComputation& computation) {} + + // Evaluates an HLO module and an array of pointers to literals. Returns the + // evaluated result as a literal if successful. + // + // Precondition: The indices of arg_literals correspond to the parameter + // numbers of the HLO parameters in the computation. See comment below for an + // example. + // + // (Dummy template arg is to reduce the overloading priority of one overload + // so that Evaluate(module, {}) resolves unambiguously.) + StatusOr Evaluate(const HloModule& module, + absl::Span arg_literals) { + return Evaluate(*module.entry_computation(), arg_literals); + } + template + StatusOr Evaluate(const HloModule& module, + absl::Span arg_literals) { + return Evaluate(*module.entry_computation(), arg_literals); + } + + // Evaluates an HLO computation and an array of pointers to literals. + // Returns the evaluated result as a literal if successful. + // Precondition: The indices of arg_literals correspond to the parameter + // numbers of the HLO parameters in the computation. For e.g., consider the + // following graph: + // + // * + // / \ + // + Parameter1 + // / \ + // / \ + // Parameter0 Constant + // + // where Parameter0 has parameter_number 0 and Parameter1 has parameter_number + // 1 in this computation. The input literals array will then have its first + // literal map to Parameter0 and the second map to Parameter1. + // + // (Dummy template arg is to reduce the overloading priority of one overload + // so that Evaluate(module, {}) resolves unambiguously.) + StatusOr Evaluate(const HloComputation& computation, + absl::Span arg_literals); + template + StatusOr Evaluate(const HloComputation& computation, + absl::Span arg_literals) { + std::vector arg_literal_ptrs; + for (const auto& l : arg_literals) { + arg_literal_ptrs.push_back(&l); + } + return Evaluate(computation, arg_literal_ptrs); + } + + // Gets the value of running a single HLO instruction. + // + // This function may recursively evaluate the dependency of this instruction + // within its parent computation until it encounters something that cannot be + // evaluated, such as an Infeed or a Parameter instruction. + // It makes best effort to partially evaluate a dependency if possible. + StatusOr Evaluate( + const HloInstruction* instruction, + bool recursively_evaluate_nonconstant_operands = false); + + // Same as Evaluate, except returning false on error and accepts an output + // pointer. + bool TryEvaluate(const HloInstruction* instruction, Literal* result, + bool recursively_evaluate_nonconstant_operands = false); + + // Evaluates a single HLO instruction, substituting the given literals for + // some of the instruction's operands. + // + // For example, given instruction = op(A, B, C) and the map + // {A = x, C = y}, this evaluates op(x, B, y). + StatusOr EvaluateWithSubstitutions( + const HloInstruction* instruction, + const absl::flat_hash_map& + substitutions); + + StatusOr EvaluateElementwiseBinaryOp(HloOpcode opcode, + const Literal& lhs, + const Literal& rhs); + + StatusOr EvaluateElementwiseUnaryOp(HloOpcode opcode, + const Literal& operand); + + StatusOr EvaluateElementwiseTernaryOp(HloOpcode opcode, + const Literal& lhs, + const Literal& rhs, + const Literal& ehs); + + StatusOr EvaluateElementwiseCompareOp(ComparisonDirection direction, + const Literal& lhs, + const Literal& rhs); + + StatusOr EvaluateDotOp(const DotDimensionNumbers& dim_numbers, + const PrecisionConfig& precision_config, + const Literal& lhs, const Literal& rhs); + + void set_dynamic_dimension_inference( + DynamicDimensionInference* dynamic_dimension_inference) { + dynamic_dimension_inference_ = dynamic_dimension_inference; + } + + DynamicDimensionInference* dynamic_dimension_inference() { + return dynamic_dimension_inference_; + } + + // Enable the fast path for certain operations like dot or convolution. + void set_use_fast_path(bool value) { use_fast_path_ = value; } + + // Handles evaluation of a custom-call op. + // Operand literals are provided in |operands| and implementations must + // populate |output| before returning. + using CustomCallHandler = std::function( + const HloInstruction* custom_call, absl::Span operands)>; + + // Sets a handler that is called during evaluation for custom-call ops. + // If no handler is defined the default error behavior will occur. The handler + // will be provided evaluated literals for all operands and is expected to + // return an output literal of the appropriate shape. + void set_custom_call_handler(CustomCallHandler handler) { + custom_call_handler_ = std::move(handler); + } + + // Returns the result of a matrix multiply `lhs x rhs`. + static std::unique_ptr> MatmulArray2D( + const Array2D& lhs, const Array2D& rhs); + static std::unique_ptr> MatmulArray2D( + const Array2D& lhs, const Array2D& rhs); + static std::unique_ptr> MatmulArray2D( + const Array2D& lhs, const Array2D& rhs); + static std::unique_ptr>> MatmulArray2D( + const Array2D>& lhs, + const Array2D>& rhs); + static std::unique_ptr>> MatmulArray2D( + const Array2D>& lhs, + const Array2D>& rhs); + static std::unique_ptr> MatmulArray2D( + const Array2D& lhs, const Array2D& rhs); + + protected: + // Evaluates the given instruction, and stores the evaluation result in the + // evaluated_ map. + // When a non-empty shape_index is given, the instruction may be partially + // evaluated at the given shape_index and the rest of the result could be + // marked as undetermined unless it has been previously evaluated using + // EvaluateInternal. Such partial evaluation reduces the computation and + // memory overhead in cases where we need only one tuple element by avoiding + // the evaluation of a full tuple. + Status EvaluateInternal( + const HloInstruction* instruction, const ShapeIndex& shape_index = {}, + bool recursively_evaluate_nonconstant_operands = false); + + Status EvaluateParameterFromCallerArgument(const HloInstruction* parameter, + const ShapeIndex& shape_index); + + // Helper method to extract a list of int64_t from evaluated instruction for + // start_indices for DynamicSlice and DynamicUpdateSlice. + std::vector GetS64Indices( + absl::Span start_indices); + + // Creates a vector of multipliers which can be used to create a linear index + // into shape. + // + // Given the multidimensional index {i1, ..., iN} and + // M = MakeDimMultipliers(shape), the corresponding linear index LI is simply + // + // LI = i1 * M[1] + i2 * M[2] + ... + iN * M[N]. + // + // This lets you calculate LI given the multidimensional indices in any order. + static DimensionVector MakeDimMultipliers(const Shape& shape); + + // Make HloEvaluatorTypedVisitor a friend because it is logically part of this + // class. + // + // A straightforward implementation would be to make it a nested class + // declared and defined in hlo_evaluator.cc. Instead HloEvaluatorTypedVisitor + // lives as a separate class with its own header because its template gets + // instantiated many times and we want to use extern templates to shard out + // the compilation of those instantiations across multiple cc files. + template + friend class HloEvaluatorTypedVisitor; + + // Wraps around instruction handling to infer types before dispatching to + // the corresponding typed Visitor. + Status DefaultAction(const HloInstruction* hlo) override { + return hlo->Visit(typed_visitors_[hlo->shape().element_type()].get()); + } + + Status Preprocess(const HloInstruction* hlo) override; + Status Postprocess(const HloInstruction* hlo) override; + + // Operations that are type-agnostic or always return a specific type, such as + // HandleIsFinite where boolean is always returned. + // + Status HandleBitcast(const HloInstruction* bitcast) override; + Status HandleBitcastConvert(const HloInstruction* convert) override; + Status HandleGetDimensionSize( + const HloInstruction* get_dimension_size) override; + Status HandleSetDimensionSize( + const HloInstruction* set_dimension_size) override; + Status HandleParameter(const HloInstruction* parameter) override; + Status HandleInfeed(const HloInstruction* infeed) override; + Status HandleConstant(const HloInstruction* constant) override; + Status HandleConcatenate(const HloInstruction* concatenate) override; + Status HandleReshape(const HloInstruction* reshape) override; + Status HandleTranspose(const HloInstruction* transpose) override; + Status HandleIsFinite(const HloInstruction* is_finite) override; + Status HandleCompare(const HloInstruction* compare) override; + Status HandleTuple(const HloInstruction* tuple) override; + Status HandleFft(const HloInstruction* fft) override; + Status HandleGather(const HloInstruction* gather) override; + Status HandleScatter(const HloInstruction* hlo) override; + Status HandleGetTupleElement( + const HloInstruction* get_tuple_element) override; + Status HandleAsyncStart(const HloInstruction* async_start) override; + Status HandleAsyncUpdate(const HloInstruction* async_update) override; + Status HandleAsyncDone(const HloInstruction* async_done) override; + Status HandleCopy(const HloInstruction* copy) override; + Status HandleCopyStart(const HloInstruction* copy_start) override; + Status HandleCopyDone(const HloInstruction* copy_done) override; + Status HandleConditional(const HloInstruction* conditional) override; + Status HandleConvert(const HloInstruction* convert) override; + Status HandleCall(const HloInstruction* call) override; + Status HandleDynamicSlice(const HloInstruction* dynamic_slice) override; + Status HandleDynamicUpdateSlice(const HloInstruction* dus) override; + Status HandleFusion(const HloInstruction* fusion) override; + Status HandleWhile(const HloInstruction* while_hlo) override; + Status HandleSelect(const HloInstruction* select) override; + Status HandleBroadcast(const HloInstruction* broadcast) override; + Status HandleAfterAll(const HloInstruction* after_all) override; + Status HandleAddDependency(const HloInstruction* add_dependency) override; + Status HandleReverse(const HloInstruction* reverse) override; + Status HandleSelectAndScatter( + const HloInstruction* select_and_scatter) override; + Status HandleSlice(const HloInstruction* slice) override; + Status HandleSort(const HloInstruction* sort) override; + Status HandleStochasticConvert( + const HloInstruction* stochastic_convert) override; + Status HandleReal(const HloInstruction* real) override; + Status HandleImag(const HloInstruction* imag) override; + Status HandleComplex(const HloInstruction* complex) override; + Status HandleReduce(const HloInstruction* hlo) override; + Status HandleReduceWindow(const HloInstruction* hlo) override; + Status HandleMap(const HloInstruction* map) override; + Status HandleCustomCall(const HloInstruction* custom_call) override; + + // Unsupported HLOs, note some of them (such as BatchNorm*) are typically + // expanded in a semantic-preserving way into other HLOs by adding expansion + // HLO pass to the HLO optimization pass during compilation, which can then be + // handled by the evaluator. + Status HandleBatchNormGrad(const HloInstruction* batch_norm_grad) override { + return Unimplemented("BatchNormGrad HLO is unsupported by the evaluator."); + } + Status HandleBatchNormInference( + const HloInstruction* batch_norm_inference) override { + return Unimplemented( + "BatchNormInference HLO is unsupported by the evaluator."); + } + Status HandleBatchNormTraining( + const HloInstruction* batch_norm_training) override { + return Unimplemented( + "BatchNormTraining HLO is unsupported by the evaluator."); + } + Status HandleOutfeed(const HloInstruction* outfeed) override { + return Unimplemented("Outfeed HLO is unsupported by the evaluator."); + } + + // Returns the already-evaluated literal result for the instruction. + // + // A Constant instruction is considered evaluated and its literal will be + // returned directly without looking up the cache. + // + // Similarly, a Parameter instruction is considered evaluated and its literal + // is looked up in arg_literals. + // + // Crash with log if the given instruction has not been evaluated previously. + const Literal& GetEvaluatedLiteralFor(const HloInstruction* hlo) { + if (hlo->IsConstant()) { + return hlo->literal(); + } + if (hlo->opcode() == HloOpcode::kParameter && !arg_literals_.empty()) { + return *arg_literals_.at(hlo->parameter_number()); + } + + auto it = evaluated_.find(hlo); + CHECK(it != evaluated_.end()) + << "could not find evaluated value for: " << hlo->ToString(); + return it->second; + } + + // Returns true if the given hlo has been evaluated and cached. + bool IsAlreadyEvaluated(const HloInstruction* hlo, + const ShapeIndex& shape_index = {}) { + if (hlo->IsConstant()) { + return true; + } + if (hlo->opcode() == HloOpcode::kParameter && !arg_literals_.empty()) { + return true; + } + auto it = evaluated_.find(hlo); + if (it == evaluated_.end()) { + return false; + } + // We may evaluate some elements of a tuple-shaped instruction and mark + // the other elements as undetermined. This way we avoid the computation + // and memory overhead of evaluating a large tuple when only some elements + // are needed. By marking the other elements undetermined, we allow the + // evaluator to update the cached tuple literal when more elements are + // evaluated. + return it->second.IsDetermined(shape_index); + } + + // Tracks the HLO instruction and its evaluated literal result. + // + // Parameters and constants aren't stored here, see implementation of + // GetEvaluatedLiteralFor. + // + // TODO(b/35950897): have better memory management here to free instructions + // that are no longer a parent for any other subsequent instruction in + // post-ordering. + // + // Must be cleared for each evaluation. + // + // Storing Literal in place requires the container to have pointer stability + // so we cannot use flat_hash_map any more. + absl::node_hash_map evaluated_; + // Set by EvaluateInternal and opportunitiscally used by the HandleXXX + // functions. When non-empty, the HandleXXX function may evaluate the + // instruction at only the given shape index. + ShapeIndex visitor_shape_index_; + bool enable_partial_evaluation_ = false; + + std::unique_ptr call_graph_cache_; + std::unique_ptr tuple_points_to_analysis_cache_; + + // Use fast path that uses eigen in the evaluator. + bool use_fast_path_ = false; + + private: + template + static StatusOr ElementWiseUnaryOpImpl( + const HloInstruction* instruction, + const std::function& unary_op, + const Literal& operand_literal) { + const Shape& shape = instruction->shape(); + const auto* operand = instruction->operand(0); + TF_RET_CHECK(ShapeUtil::SameDimensions(shape, operand->shape())); + + Literal result(shape); + TF_RETURN_IF_ERROR(result.PopulateParallel( + [&](absl::Span multi_index, int) { + return unary_op(operand_literal.Get(multi_index)); + })); + return std::move(result); + } + + // Map from a primitive type to its associated (templated) DfsHloVisitor. + std::unique_ptr typed_visitors_[PrimitiveType_ARRAYSIZE]; + + // Caches pointers to input literals, assuming they are in post-order. + // Literals are not owned by this class, and they must outlive the lifetime of + // each invocation to the Evaluate* method. + // Must be cleared for each evaluation. + std::vector arg_literals_; + + // Max loop iterations to execute with no maximum if negative. + int64_t max_loop_iterations_ = 0; + + // Module-level seed handle. + uint64_t seed_ = 0; + // RNG engine. + std::minstd_rand0 engine_; + + // DynamicDimensionInference is used to evaluate GetDimensionSize, which + // returns the dynamic dimension size of its operand. + DynamicDimensionInference* dynamic_dimension_inference_ = nullptr; + + // Optional handler for custom_call ops. + CustomCallHandler custom_call_handler_; + + HloEvaluator(const HloEvaluator&) = delete; + HloEvaluator& operator=(const HloEvaluator&) = delete; +}; + +std::unique_ptr> MatmulArray2D(const Array2D& lhs, + const Array2D& rhs); +} // namespace xla + +#endif // XLA_HLO_EVALUATOR_HLO_EVALUATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator_typed_visitor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator_typed_visitor.h new file mode 100644 index 0000000000000000000000000000000000000000..274a5431fa6b4f1239ac470fcc15a8f446c9090f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/evaluator/hlo_evaluator_typed_visitor.h @@ -0,0 +1,1662 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_EVALUATOR_HLO_EVALUATOR_TYPED_VISITOR_H_ +#define XLA_HLO_EVALUATOR_HLO_EVALUATOR_TYPED_VISITOR_H_ + +#include // NOLINT + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/base/casts.h" +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "xla/array2d.h" +#include "xla/hlo/evaluator/hlo_evaluator.h" +#include "xla/hlo/ir/hlo_casting_utils.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/primitive_util.h" +#include "xla/service/shape_inference.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/statusor.h" + +namespace xla { + +template +T Nibble0(T t) { + if constexpr (std::is_integral_v) { + constexpr auto shift = (8 * sizeof(T)) - 4; + return (t << shift) >> shift; + } + return t; +} + +template +T Nibble1(T t) { + if constexpr (std::is_integral_v) { + return t >> 4; + } + return t; +} + +namespace detail { +template +using unsigned_promoted_type_t = + std::make_unsigned_t() + std::declval())>; +} + +// ToArithmeticSafeType(T t): +// - converts `t` to an unsigned integer at least as wide as `int` if T is an +// integer, and +// - otherwise returns `t` unchanged. +// +// It's UB in C++ to under/overflow a signed integer, so we wrap all arithmetic +// in this type to force 2's complement behavior. +template +auto ToArithmeticSafeType(T t) { + if constexpr (std::is_integral_v) { + return static_cast>(t); + } + if constexpr (!std::is_integral_v) { + return std::move(t); + } +} + +// Templated DfsHloVisitor for use by HloEvaluator. +// +// Typically ReturnT here indicates the resulting literal type of each evaluated +// Handle* method of a TypedVisitor. There are however a few exceptions to this +// rule, notably: +// - HandleCompare and HandleIsFinite: where the resulting literal type is +// always boolean. +// - HandleImag and HandleReal: where the resulting literal type is always float +// and the operand is always complex, or real in the case of HandleReal. +// These operations are handled outside of the parent HloEvaluator handlers +// instead of from within TypedVisitor. +// +// Type params: +// - ReturnT: The type of input and output of each operation. +// - ElementwiseT: The type in which internal computation are done. +// +// This is logically a private part of HloEvaluator. It lives in this header +// file rather than in hlo_evaluator.cc because we use extern templates and a +// bunch of independent cc files to speed up compiling the many instantiations +// of this class. +// +// NOTE: Prefer putting new implementation to HloEvalator rather than +// HloEvaluatorTypedVisitor whenever possible, because this class is templated +// for all primitive types and is an order of magnitude larger in code size as +// well as compile time. Only put op handling that involves compute using native +// C++ types here, such as elementwise ops with compute, convolution, dot, etc. +template +class HloEvaluatorTypedVisitor : public ConstDfsHloVisitorWithDefault { + private: + ABSL_ATTRIBUTE_NOINLINE Status + UnsupportedTypeError(const HloInstruction* instruction) { + return InvalidArgument( + "Unsupported type for %s: %s", HloOpcodeString(instruction->opcode()), + PrimitiveType_Name(instruction->shape().element_type())); + } + + public: + explicit HloEvaluatorTypedVisitor(HloEvaluator* p) : parent_(p) {} + + // The following higher-order functions convert a function with ElementwiseT + // to a function with ReturnT. + std::function ConvertUnaryFunction( + const std::function& unary_op) { + return [&unary_op](ReturnT arg) { + return static_cast(unary_op(static_cast(arg))); + }; + } + std::function ConvertBinaryFunction( + const std::function& + binary_op) { + return [&binary_op](ReturnT arg1, ReturnT arg2) { + return static_cast(binary_op(static_cast(arg1), + static_cast(arg2))); + }; + } + std::function ConvertTernaryFunction( + const std::function& ternary_op) { + return [&ternary_op](ReturnT arg1, ReturnT arg2, ReturnT arg3) { + return static_cast(ternary_op(static_cast(arg1), + static_cast(arg2), + static_cast(arg3))); + }; + } + + Status DefaultAction(const HloInstruction* hlo_instruction) override { + return Unimplemented("unhandled HLO ops for HloEvaluator: %s.", + HloOpcodeString(hlo_instruction->opcode())); + } + + template >* = nullptr> + Status HandleAbs(const HloInstruction* abs) { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[abs], + ElementWiseUnaryOp(abs, [](NativeT elem_operand) { + return elem_operand; + })); + return OkStatus(); + } + + template >* = nullptr> + Status HandleAbs(const HloInstruction* abs) { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[abs], + ElementWiseUnaryOp(abs, [](NativeT elem_operand) { + return std::abs(elem_operand); + })); + return OkStatus(); + } + + template >* = nullptr> + Status HandleAbs(const HloInstruction* abs) { + const Literal& operand_literal = + parent_->GetEvaluatedLiteralFor(abs->operand(0)); + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[abs], + (HloEvaluator::ElementWiseUnaryOpImpl( + abs, [](NativeT elem_operand) { return std::abs(elem_operand); }, + operand_literal))); + + return OkStatus(); + } + + Status HandleAbs(const HloInstruction* abs) override { + // If the operand is of C64 type, the return type of abs will be F32. + // However, ElementwiseT would still be the return type, F32, and thus + // specifying the ElementwiseT explicitly as C64 is needed below. + if (abs->operand(0)->shape().element_type() == C64) { + return HandleAbs(abs); + } else if (abs->operand(0)->shape().element_type() == C128) { + return HandleAbs(abs); + } + return HandleAbs(abs); + } + + Status HandleRound(const HloInstruction* round) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[round], + ElementWiseUnaryOp(round, [](ElementwiseT elem_operand) { + return std::round(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(round); + } + + Status HandleRoundNearestEven(const HloInstruction* round) override { + if constexpr (!is_complex_v) { + // Verify the current rounding direction. + TF_RET_CHECK(fegetround() == FE_TONEAREST); + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[round], + ElementWiseUnaryOp(round, [](ElementwiseT elem_operand) { + return std::nearbyint(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(round); + } + + Status HandleCeil(const HloInstruction* ceil) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[ceil], + ElementWiseUnaryOp(ceil, [](ElementwiseT elem_operand) { + return std::ceil(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(ceil); + } + + Status HandleExp(const HloInstruction* exp) override { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[exp], + ElementWiseUnaryOp(exp, [](ElementwiseT elem_operand) { + return std::exp(elem_operand); + })); + return OkStatus(); + } + + Status HandleExpm1(const HloInstruction* expm1) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[expm1], + ElementWiseUnaryOp(expm1, [](ElementwiseT elem_operand) { + return std::expm1(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(expm1); + } + + Status HandleFloor(const HloInstruction* floor) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[floor], + ElementWiseUnaryOp(floor, [](ElementwiseT elem_operand) { + return std::floor(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(floor); + } + + Status HandleLog(const HloInstruction* log) override { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[log], + ElementWiseUnaryOp(log, [](ElementwiseT elem_operand) { + return std::log(elem_operand); + })); + return OkStatus(); + } + + Status HandleLog1p(const HloInstruction* log1p) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[log1p], + ElementWiseUnaryOp(log1p, [](ElementwiseT elem_operand) { + return std::log1p(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(log1p); + } + + Status HandleNot(const HloInstruction* not_) override { + if constexpr (std::is_arithmetic_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[not_], + ElementWiseUnaryOp(not_, [](ElementwiseT elem_operand) { + if constexpr (std::is_floating_point_v || + std::is_same_v) { + return !elem_operand; + } else { + static_assert(std::is_integral_v); + return ~elem_operand; + } + })); + return OkStatus(); + } + return UnsupportedTypeError(not_); + } + + template < + typename NativeT, + typename std::enable_if_t && + !std::is_floating_point_v>* = nullptr> + Status HandleNegate(const HloInstruction* negate) { + using type = std::make_unsigned_t; + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[negate], + ElementWiseUnaryOp(negate, [](ElementwiseT elem_operand) { + return NativeT(-type(elem_operand)); + })); + return OkStatus(); + } + + template || + std::is_floating_point_v>* = nullptr> + Status HandleNegate(const HloInstruction* negate) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[negate], + ElementWiseUnaryOp( + negate, [](ElementwiseT elem_operand) { return -elem_operand; })); + return OkStatus(); + } + + Status HandleNegate(const HloInstruction* negate) override { + return HandleNegate(negate); + } + + Status HandleLogistic(const HloInstruction* logistic) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[logistic], + ElementWiseUnaryOp(logistic, [](ElementwiseT elem_operand) { + return static_cast(1) / + (static_cast(1) + std::exp(-elem_operand)); + })); + return OkStatus(); + } + + Status HandleSign(const HloInstruction* sign) override { + using NativeT = ElementwiseT; + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[sign], + ElementWiseUnaryOp(sign, [](ElementwiseT elem_operand) { + if constexpr (std::is_integral_v) { + return (ElementwiseT(0) < elem_operand) - + (elem_operand < ElementwiseT(0)); + } + if constexpr (std::is_floating_point_v) { + return std::isnan(elem_operand) + ? elem_operand + : std::copysign(elem_operand != ElementwiseT(0), + elem_operand); + } + if constexpr (is_complex_v) { + auto abs_val = std::abs(elem_operand); + return 0 == abs_val ? ElementwiseT(0) : elem_operand / abs_val; + } + })); + return OkStatus(); + } + + Status HandleAtan2(const HloInstruction* atan2) override { + if constexpr (std::is_floating_point_v) { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[atan2], + ElementWiseBinaryOp(atan2, [](ElementwiseT lhs_elem, + ElementwiseT rhs_elem) { + return std::atan2(lhs_elem, rhs_elem); + })); + return OkStatus(); + } + if constexpr (is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[atan2], + ElementWiseBinaryOp(atan2, [](ElementwiseT y, ElementwiseT x) { + // atan2(y,x) = -i * log((x + i * y)/sqrt(x**2+y**2)) + auto i = ElementwiseT(0.0, 1.0); + return (-i) * (std::log((x + i * y) / std::sqrt(x * x + y * y))); + })); + return OkStatus(); + } + return UnsupportedTypeError(atan2); + } + + Status HandleTanh(const HloInstruction* tanh) override { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[tanh], + ElementWiseUnaryOp(tanh, [](ElementwiseT elem_operand) { + return std::tanh(elem_operand); + })); + return OkStatus(); + } + + Status HandleMultiply(const HloInstruction* multiply) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[multiply], + ElementWiseBinaryOp( + multiply, [](ElementwiseT lhs_elem, ElementwiseT rhs_elem) { + return ElementwiseT(ToArithmeticSafeType(lhs_elem) * + ToArithmeticSafeType(rhs_elem)); + })); + return OkStatus(); + } + + Status HandleSubtract(const HloInstruction* subtract) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[subtract], + ElementWiseBinaryOp( + subtract, [](ElementwiseT lhs_elem, ElementwiseT rhs_elem) { + return ElementwiseT(ToArithmeticSafeType(lhs_elem) - + ToArithmeticSafeType(rhs_elem)); + })); + return OkStatus(); + } + + Status HandleAdd(const HloInstruction* add) override { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[add], + ElementWiseBinaryOp(add, [](ElementwiseT lhs_elem, + ElementwiseT rhs_elem) { + return ElementwiseT(ToArithmeticSafeType(lhs_elem) + + ToArithmeticSafeType(rhs_elem)); + })); + return OkStatus(); + } + + Status HandleDivide(const HloInstruction* divide) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[divide], + ElementWiseBinaryOp( + divide, + [](ElementwiseT lhs_elem, ElementwiseT rhs_elem) -> ElementwiseT { + if constexpr (std::is_integral_v) { + if constexpr (std::is_unsigned_v) { + if (rhs_elem == 0) { + return std::numeric_limits::max(); + } + } + if constexpr (std::is_signed_v) { + if (rhs_elem == 0) { + return static_cast(-1); + } + if (rhs_elem == -1 && + lhs_elem == std::numeric_limits::min()) { + return lhs_elem; + } + } + } + return lhs_elem / rhs_elem; + })); + return OkStatus(); + } + + Status HandleMaximum(const HloInstruction* maximum) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[maximum], + ElementWiseBinaryOp(maximum, [](ElementwiseT lhs, ElementwiseT rhs) { + if constexpr (std::numeric_limits::has_quiet_NaN) { + if (std::isnan(lhs)) { + return lhs; + } + if (std::isnan(rhs)) { + return rhs; + } + } + return std::max(lhs, rhs); + })); + return OkStatus(); + } + return UnsupportedTypeError(maximum); + } + + Status HandleMinimum(const HloInstruction* minimum) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[minimum], + ElementWiseBinaryOp(minimum, [](ElementwiseT lhs, ElementwiseT rhs) { + if constexpr (std::numeric_limits::has_quiet_NaN) { + if (std::isnan(lhs)) { + return lhs; + } + if (std::isnan(rhs)) { + return rhs; + } + } + return std::min(lhs, rhs); + })); + return OkStatus(); + } + return UnsupportedTypeError(minimum); + } + + Status HandlePower(const HloInstruction* power) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[power], + ElementWiseBinaryOp( + power, [](ElementwiseT lhs_el, ElementwiseT rhs_el) { + return lhs_el == ElementwiseT(1) ? static_cast(1) + : lhs_el == ElementwiseT(0) && rhs_el == ElementwiseT(0) + ? static_cast(1) + : std::pow(lhs_el, rhs_el); + })); + return OkStatus(); + } + + Status HandleSqrt(const HloInstruction* sqrt) override { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[sqrt], + ElementWiseUnaryOp(sqrt, [](ElementwiseT elem_operand) { + return std::sqrt(elem_operand); + })); + return OkStatus(); + } + + Status HandleCbrt(const HloInstruction* cbrt) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[cbrt], + ElementWiseUnaryOp(cbrt, [](ElementwiseT elem_operand) { + return std::cbrt(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(cbrt); + } + + Status HandleRsqrt(const HloInstruction* rsqrt) override { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[rsqrt], + ElementWiseUnaryOp(rsqrt, [](ElementwiseT elem_operand) { + return static_cast(1) / std::sqrt(elem_operand); + })); + return OkStatus(); + } + + Status HandleRemainder(const HloInstruction* remainder) override { + if constexpr (!is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[remainder], + ElementWiseBinaryOp( + remainder, + [](ElementwiseT lhs_el, ElementwiseT rhs_el) -> ElementwiseT { + if constexpr (std::is_integral_v) { + if (rhs_el == 0) { + return lhs_el; + } + if constexpr (std::is_signed_v) { + if (rhs_el == -1 && + lhs_el == std::numeric_limits::min()) { + return 0; + } + } + return lhs_el % rhs_el; + } + if constexpr (std::is_floating_point_v) { + return std::fmod(lhs_el, rhs_el); + } + })); + return OkStatus(); + } + return UnsupportedTypeError(remainder); + } + + Status HandleAnd(const HloInstruction* and_inst) override { + if constexpr (std::is_integral_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[and_inst], + ElementWiseBinaryOp(and_inst, + [](ElementwiseT lhs_el, ElementwiseT rhs_el) { + return lhs_el & rhs_el; + })); + return OkStatus(); + } + return UnsupportedTypeError(and_inst); + } + + Status HandleOr(const HloInstruction* or_inst) override { + if constexpr (std::is_integral_v) { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[or_inst], + ElementWiseBinaryOp(or_inst, [](ElementwiseT lhs_el, + ElementwiseT rhs_el) { + return lhs_el | rhs_el; + })); + return OkStatus(); + } + return UnsupportedTypeError(or_inst); + } + + Status HandleXor(const HloInstruction* xor_inst) override { + if constexpr (std::is_integral_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[xor_inst], + ElementWiseBinaryOp(xor_inst, + [](ElementwiseT lhs_el, ElementwiseT rhs_el) { + return lhs_el ^ rhs_el; + })); + return OkStatus(); + } + return UnsupportedTypeError(xor_inst); + } + + Status HandleShiftLeft(const HloInstruction* shl) override { + if constexpr (std::is_integral_v && + !std::is_same_v) { + TF_ASSIGN_OR_RETURN(parent_->evaluated_[shl], + ElementWiseBinaryOp(shl, [](ElementwiseT lhs_elem, + ElementwiseT rhs_elem) { + return IsShiftOutOfBounds(rhs_elem) + ? 0 + : (lhs_elem << rhs_elem); + })); + return OkStatus(); + } + return UnsupportedTypeError(shl); + } + + Status HandleShiftRightArithmetic(const HloInstruction* shr) override { + if constexpr (std::is_integral_v && + !std::is_same_v) { + using SignedT = make_specialized_signed_t; + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[shr], + ElementWiseBinaryOp( + shr, [](ElementwiseT lhs_elem, ElementwiseT rhs_elem) { + SignedT lhs_signed = static_cast(lhs_elem); + if (IsShiftOutOfBounds(rhs_elem)) { + return lhs_signed < 0 ? static_cast(-1) : 0; + } else { + return static_cast(lhs_signed >> rhs_elem); + } + })); + return OkStatus(); + } + return UnsupportedTypeError(shr); + } + + Status HandleShiftRightLogical(const HloInstruction* shr) override { + if constexpr (std::is_integral_v && + !std::is_same_v) { + using UnsignedT = make_specialized_unsigned_t; + TF_ASSIGN_OR_RETURN(parent_->evaluated_[shr], + ElementWiseBinaryOp(shr, [](ElementwiseT lhs_elem, + ElementwiseT rhs_elem) { + // If shift amount is greater than the number of + // bits, then return 0. + if (IsShiftOutOfBounds(rhs_elem)) { + return static_cast(0); + } + return static_cast( + static_cast(lhs_elem) >> rhs_elem); + })); + return OkStatus(); + } + return UnsupportedTypeError(shr); + } + + Status HandleClamp(const HloInstruction* clamp) override { + if constexpr (!is_complex_v) { + auto clamp_op = [](ElementwiseT low, ElementwiseT value, + ElementwiseT high) { + if constexpr (std::numeric_limits::has_quiet_NaN) { + if (std::isnan(low)) { + return low; + } + if (std::isnan(value)) { + return value; + } + if (std::isnan(high)) { + return high; + } + } + return std::min(high, std::max(value, low)); + }; + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[clamp], + ElementwiseTernaryOp(clamp, + std::move(ConvertTernaryFunction(clamp_op)))); + return OkStatus(); + } + return UnsupportedTypeError(clamp); + } + + Status HandleSelect(const HloInstruction* select) override { + CHECK(!ShapeUtil::IsScalar(select->operand(0)->shape())); + CHECK(select->shape().IsArray()); + std::function select_op = + [](bool pred, ReturnT on_true, ReturnT on_false) { + if (pred) { + return on_true; + } + return on_false; + }; + TF_ASSIGN_OR_RETURN(parent_->evaluated_[select], + ElementwiseTernaryOp(select, std::move(select_op))); + return OkStatus(); + } + + Status HandleConvolutionWithLiterals(const HloInstruction* conv, + const Literal& lhs_literal, + const Literal& rhs_literal) { + const auto& window = conv->window(); + const Shape& result_shape = conv->shape(); + const Shape& lhs_shape = lhs_literal.shape(); + const Shape& rhs_shape = rhs_literal.shape(); + const auto packed_nibble_count = + absl::c_count(conv->precision_config().operand_precision(), + PrecisionConfig::PACKED_NIBBLE); + CHECK_NE(packed_nibble_count, 1); + const bool is_packed_nibble = packed_nibble_count == 2; + + TF_CHECK_OK(ShapeUtil::ValidateShape(lhs_shape)); + TF_CHECK_OK(ShapeUtil::ValidateShape(rhs_shape)); + CHECK(lhs_shape.IsArray()); + CHECK(rhs_shape.IsArray()); + CHECK(ShapeUtil::SameElementType(lhs_shape, rhs_shape)); + CHECK(ShapeUtil::SameElementType(lhs_shape, result_shape)); + + const auto& dnums = conv->convolution_dimension_numbers(); + const int64_t num_spatial_dims = dnums.output_spatial_dimensions_size(); + CHECK_EQ(num_spatial_dims, dnums.input_spatial_dimensions_size()); + CHECK_EQ(num_spatial_dims, dnums.kernel_spatial_dimensions_size()); + CHECK_GE(num_spatial_dims, 0); + CHECK_EQ(window.dimensions_size(), num_spatial_dims); + + std::vector window_dimension_sizes; + for (auto i : dnums.kernel_spatial_dimensions()) { + window_dimension_sizes.push_back(ShapeUtil::GetDimension(rhs_shape, i)); + } + + const Shape& window_shape = + ShapeUtil::MakeShape(rhs_shape.element_type(), window_dimension_sizes); + + DimensionVector lhs_dim_multipliers = + HloEvaluator::MakeDimMultipliers(lhs_shape); + DimensionVector rhs_dim_multipliers = + HloEvaluator::MakeDimMultipliers(rhs_shape); + + auto lhs_literal_data = lhs_literal.data(); + auto rhs_literal_data = rhs_literal.data(); + + const int64_t feature_group_count = conv->feature_group_count(); + const int64_t batch_group_count = conv->batch_group_count(); + + auto func = [&window_shape, &dnums, &lhs_shape, &rhs_shape, &window, + &lhs_dim_multipliers, &rhs_dim_multipliers, lhs_literal_data, + rhs_literal_data, feature_group_count, batch_group_count, + is_packed_nibble](const absl::Span out_index, + int /*thread_id*/) { + // Dimension number applicable for input (lhs). + const int64_t input_batch_dim = dnums.input_batch_dimension(); + const int64_t input_z_dim = dnums.input_feature_dimension(); + // Dimension number applicable for kernel (rhs). + const int64_t kernel_input_z_dim = dnums.kernel_input_feature_dimension(); + const int64_t kernel_output_z_dim = + dnums.kernel_output_feature_dimension(); + // Dimension number applicable for output. + const int64_t output_batch_dim = dnums.output_batch_dimension(); + const int64_t output_z_dim = dnums.output_feature_dimension(); + + const int64_t input_z_size = + ShapeUtil::GetDimension(lhs_shape, input_z_dim); + + const int64_t input_batch_size = + ShapeUtil::GetDimension(lhs_shape, input_batch_dim); + + const int64_t batch_group_size = input_batch_size / batch_group_count; + + // The size of an input feature group. + const int64_t input_feature_group_size = + input_z_size / feature_group_count; + + const int64_t output_z_size = + ShapeUtil::GetDimension(rhs_shape, kernel_output_z_dim); + // The output feature dimension is a concatenation of convolution results + // from the different groups. + const int64_t output_feature_group_size = + output_z_size / feature_group_count; + + // Calculate the group index to which the current output index + // belongs. + const int64_t feature_group_index = + out_index[output_z_dim] / output_feature_group_size; + + const int64_t depthwise_multiplier = output_z_size / batch_group_count; + const int64_t batch_group_index = + out_index[output_z_dim] / depthwise_multiplier; + + ElementwiseT result_val = static_cast(0); + DimensionVector rhs_spatial_index(dnums.kernel_spatial_dimensions_size(), + 0); + + // Convolve input feature with kernel. + // The mechanism indexes into the correct LHS (input) and RHS (kernel) + // locations and accumulates multiplications for a given output index. + do { + // Find corresponding spatial dimension index for input (lhs). + int64_t lhs_linear_spatial_index = 0; + int64_t rhs_linear_spatial_index = 0; + for (int64_t ki = 0; ki < rhs_spatial_index.size(); ++ki) { + // Spatial dimension number for input (lhs) and output. + const int64_t input_spatial_dim = dnums.input_spatial_dimensions(ki); + const int64_t output_spatial_dim = + dnums.output_spatial_dimensions(ki); + + // Calculate lhs (input) index without taking base dilation into + // account. + const auto& window_dim = window.dimensions(ki); + const int64_t undilated_index = + out_index[output_spatial_dim] * window_dim.stride() - + window_dim.padding_low() + + rhs_spatial_index[ki] * window_dim.window_dilation(); + // Skip if the lhs (input) index is to be dilated. As an + // optimization, skip this mod if there's no dilation. + if (window_dim.base_dilation() > 1 && + undilated_index % window_dim.base_dilation() != 0) { + goto cnt; + } + + // Calculate the actual lhs (input) index after dilation. As an + // optimization, skip this integer divide if there's no dilation. + int64_t lhs_spatial_index; + if (window_dim.base_dilation() > 1) { + lhs_spatial_index = undilated_index / window_dim.base_dilation(); + } else { + lhs_spatial_index = undilated_index; + } + + // Skip if input index is not in bounds. + if (!(lhs_spatial_index >= 0 && + lhs_spatial_index < lhs_shape.dimensions(input_spatial_dim))) { + goto cnt; + } + + lhs_linear_spatial_index += + lhs_spatial_index * lhs_dim_multipliers[input_spatial_dim]; + rhs_linear_spatial_index += + (window_dim.window_reversal() + ? ((window_dim.size() - 1) - rhs_spatial_index[ki]) + : rhs_spatial_index[ki]) * + rhs_dim_multipliers[dnums.kernel_spatial_dimensions(ki)]; + } + + for (int64_t rhs_iz = 0; rhs_iz < input_feature_group_size; ++rhs_iz) { + const int64_t iz = + feature_group_index * input_feature_group_size + rhs_iz; + + int64_t lhs_linear_index = lhs_linear_spatial_index; + lhs_linear_index += out_index[output_batch_dim] * + lhs_dim_multipliers[input_batch_dim]; + + // We are scraping only the diagonal elements in the resultant + // convolution output when batch_group_count is greater than 1, + // where 1 is the default. No scraping is done in that case. + // This approach works out automatically for 'groups' in batches + // with group_size > 1, because we already descend down the batch + // dimension for the 'output_batch_dim' above. + lhs_linear_index += (batch_group_index * batch_group_size) * + lhs_dim_multipliers[input_batch_dim]; + + lhs_linear_index += iz * lhs_dim_multipliers[input_z_dim]; + int64_t rhs_linear_index = rhs_linear_spatial_index; + + rhs_linear_index += out_index[output_z_dim] * + rhs_dim_multipliers[kernel_output_z_dim]; + rhs_linear_index += rhs_iz * rhs_dim_multipliers[kernel_input_z_dim]; + auto lhs = + static_cast(lhs_literal_data[lhs_linear_index]); + auto rhs = + static_cast(rhs_literal_data[rhs_linear_index]); + if (is_packed_nibble) { + auto lhs_n0 = ToArithmeticSafeType(Nibble0(lhs)); + auto lhs_n1 = ToArithmeticSafeType(Nibble1(lhs)); + auto rhs_n0 = ToArithmeticSafeType(Nibble0(rhs)); + auto rhs_n1 = ToArithmeticSafeType(Nibble1(rhs)); + result_val += (lhs_n0 * rhs_n0) + (lhs_n1 * rhs_n1); + } else { + result_val += ToArithmeticSafeType(lhs) * ToArithmeticSafeType(rhs); + } + } + cnt: {} + } while (IndexUtil::BumpIndices(window_shape, + absl::MakeSpan(rhs_spatial_index))); + + if constexpr (std::is_integral_v) { + auto l = static_cast(std::numeric_limits::min()); + auto h = static_cast(std::numeric_limits::max()); + result_val = std::max(l, std::min(h, result_val)); + } + return static_cast(result_val); + }; + + Literal result(result_shape); + TF_RETURN_IF_ERROR(result.PopulateParallel(func)); + + parent_->evaluated_[conv] = std::move(result); + return OkStatus(); + } + + Status HandleConvolution(const HloInstruction* conv) override { + auto lhs = conv->operand(0); + auto rhs = conv->operand(1); + const auto& window = conv->window(); + const Shape& result_shape = conv->shape(); + const Shape& lhs_shape = lhs->shape(); + const Shape& rhs_shape = rhs->shape(); + + TF_CHECK_OK(ShapeUtil::ValidateShape(lhs_shape)); + TF_CHECK_OK(ShapeUtil::ValidateShape(rhs_shape)); + CHECK(lhs_shape.IsArray()); + CHECK(rhs_shape.IsArray()); + + const auto& dnums = conv->convolution_dimension_numbers(); + const int64_t num_spatial_dims = dnums.output_spatial_dimensions_size(); + CHECK_EQ(num_spatial_dims, dnums.input_spatial_dimensions_size()); + CHECK_EQ(num_spatial_dims, dnums.kernel_spatial_dimensions_size()); + CHECK_GE(num_spatial_dims, 0); + CHECK_EQ(window.dimensions_size(), num_spatial_dims); + + const auto lhs_rank = lhs_shape.rank(); + const auto rhs_rank = rhs_shape.rank(); + + CHECK_EQ(num_spatial_dims + 2, lhs_rank); + CHECK_EQ(num_spatial_dims + 2, rhs_rank); + + TF_ASSIGN_OR_RETURN( + auto inferred_return_shape, + ShapeInference::InferConvolveShape( + lhs_shape, rhs_shape, conv->feature_group_count(), + conv->batch_group_count(), window, dnums, + /*preferred_element_type=*/conv->shape().element_type())); + CHECK(ShapeUtil::Compatible(result_shape, inferred_return_shape)) + << "return shape set to: " << ShapeUtil::HumanString(result_shape) + << " but is inferred to be: " + << ShapeUtil::HumanString(inferred_return_shape); + + const Literal& lhs_literal = parent_->GetEvaluatedLiteralFor(lhs); + const Literal& rhs_literal = parent_->GetEvaluatedLiteralFor(rhs); + const bool lhs_same = ShapeUtil::SameElementType(lhs_shape, result_shape); + const bool rhs_same = ShapeUtil::SameElementType(rhs_shape, result_shape); + if (rhs_same && lhs_same) { + return HandleConvolutionWithLiterals(conv, lhs_literal, rhs_literal); + } + if (rhs_same) { + return HandleConvolutionWithLiterals( + conv, lhs_literal.Convert(result_shape.element_type()).value(), + rhs_literal); + } + if (lhs_same) { + return HandleConvolutionWithLiterals( + conv, lhs_literal, + rhs_literal.Convert(result_shape.element_type()).value()); + } + return HandleConvolutionWithLiterals( + conv, lhs_literal.Convert(result_shape.element_type()).value(), + rhs_literal.Convert(result_shape.element_type()).value()); + } + + Status HandleDot(const HloInstruction* dot) override { + if (dot->dot_dimension_numbers().rhs_contracting_dimensions_size() == 1 && + parent_->use_fast_path_ && + ShapeUtil::SameElementType(dot->operand(0)->shape(), dot->shape()) && + ShapeUtil::SameElementType(dot->operand(1)->shape(), dot->shape())) { + return HandleDot(dot); + } + return HandleDotSlowPath(dot); + } + + template >* = nullptr> + Status HandleDot(const HloInstruction* dot) { + const HloInstruction* lhs = dot->operand(0); + const HloInstruction* rhs = dot->operand(1); + CHECK(dot->shape().IsArray()); + CHECK(lhs->shape().IsArray()); + CHECK(rhs->shape().IsArray()); + + const auto& dnums = dot->dot_dimension_numbers(); + + const int64_t lhs_rank = lhs->shape().rank(); + const int64_t rhs_rank = rhs->shape().rank(); + + CHECK(ShapeUtil::SameElementType(lhs->shape(), rhs->shape())); + CHECK(ShapeUtil::SameElementType(lhs->shape(), dot->shape())); + + // There must be 1 and only 1 Contracting dimension for lhs and rhs. + const int64_t lhs_contracting_dimension = + dnums.lhs_contracting_dimensions(0); + const int64_t rhs_contracting_dimension = + dnums.rhs_contracting_dimensions(0); + // Contracted dimension sizes must be the same. + CHECK_EQ(lhs->shape().dimensions(lhs_contracting_dimension), + rhs->shape().dimensions(rhs_contracting_dimension)) + << "lhs contracted dimension: " + << lhs->shape().dimensions(lhs_contracting_dimension) + << " rhs contracted dimension: " + << rhs->shape().dimensions(rhs_contracting_dimension); + + // The fast path is for a simple rank 2 dot with default layout operands. + if (lhs_rank != 2 || rhs_rank != 2 || lhs_contracting_dimension != 1 || + rhs_contracting_dimension != 0 || + !LayoutUtil::Equal(lhs->shape().layout(), + LayoutUtil::GetDefaultLayoutForR2()) || + !LayoutUtil::Equal(rhs->shape().layout(), + LayoutUtil::GetDefaultLayoutForR2()) || + !LayoutUtil::Equal(dot->shape().layout(), + LayoutUtil::GetDefaultLayoutForR2())) { + return HandleDotSlowPath(dot); + } + + const PrimitiveType native_ty = + primitive_util::NativeToPrimitiveType(); + Literal lhs_literal = + parent_->GetEvaluatedLiteralFor(lhs).Convert(native_ty).value(); + Literal rhs_literal = + parent_->GetEvaluatedLiteralFor(rhs).Convert(native_ty).value(); + const int64_t contracted_dimension_size = + lhs->shape().dimensions(lhs_contracting_dimension); + Array2D lhs_array(lhs->shape().dimensions(0), + contracted_dimension_size); + lhs_array.SetValues(lhs_literal.data()); + Array2D rhs_array(contracted_dimension_size, + rhs->shape().dimensions(1)); + rhs_array.SetValues(rhs_literal.data()); + std::unique_ptr> result_array = + HloEvaluator::MatmulArray2D(lhs_array, rhs_array); + Literal result(ShapeUtil::MakeShape(native_ty, dot->shape().dimensions())); + result.PopulateR2FromArray2D(*result_array); + parent_->evaluated_[dot] = + std::move(result).Convert(dot->shape().element_type()).value(); + return OkStatus(); + } + + template >* = nullptr> + Status HandleDot(const HloInstruction* dot) { + return HandleDotSlowPath(dot); + } + + Status HandleDotSlowPathWithLiterals(const HloInstruction* dot, + const Literal& lhs_literal, + const Literal& rhs_literal) { + const auto& dnums = dot->dot_dimension_numbers(); + + const auto lhs_rank = lhs_literal.shape().rank(); + const auto rhs_rank = rhs_literal.shape().rank(); + + CHECK(ShapeUtil::SameElementType(lhs_literal.shape(), rhs_literal.shape())); + CHECK(ShapeUtil::SameElementType(lhs_literal.shape(), dot->shape())); + + const auto packed_nibble_count = + absl::c_count(dot->precision_config().operand_precision(), + PrecisionConfig::PACKED_NIBBLE); + CHECK_NE(packed_nibble_count, 1); + const bool is_packed_nibble = packed_nibble_count == 2; + CHECK_EQ(dnums.lhs_batch_dimensions_size(), + dnums.rhs_batch_dimensions_size()); + + DimensionVector lhs_non_contracting_dims; + DimensionVector rhs_non_contracting_dims; + for (int64_t i = 0; i < lhs_rank; i++) { + if (!absl::c_linear_search(dnums.lhs_contracting_dimensions(), i) && + !absl::c_linear_search(dnums.lhs_batch_dimensions(), i)) { + lhs_non_contracting_dims.push_back(i); + } + } + for (int64_t i = 0; i < rhs_rank; i++) { + if (!absl::c_linear_search(dnums.rhs_contracting_dimensions(), i) && + !absl::c_linear_search(dnums.rhs_batch_dimensions(), i)) { + rhs_non_contracting_dims.push_back(i); + } + } + + DimensionVector contracting_dim_sizes; + contracting_dim_sizes.reserve(dnums.lhs_contracting_dimensions_size()); + DimensionVector lhs_contracting_dims; + DimensionVector rhs_contracting_dims; + for (int64_t i = 0; i < dnums.lhs_contracting_dimensions_size(); ++i) { + const int64_t lhs_dnum = dnums.lhs_contracting_dimensions(i); + const int64_t rhs_dnum = dnums.rhs_contracting_dimensions(i); + lhs_contracting_dims.push_back(lhs_dnum); + rhs_contracting_dims.push_back(rhs_dnum); + const int64_t dim_size = lhs_literal.shape().dimensions(lhs_dnum); + contracting_dim_sizes.push_back(dim_size); + } + const int64_t total_contraction_size = Product(contracting_dim_sizes); + Literal result(dot->shape()); + TF_RETURN_IF_ERROR(result.PopulateParallel( + [&](absl::Span result_index, int /*thread_id*/) { + // Locations in LHS and RHS that we read from. + DimensionVector lhs_index(lhs_rank); + DimensionVector rhs_index(rhs_rank); + + // First come the batch dimensions. + int64_t idx = 0; + for (int64_t i = 0; i < dnums.lhs_batch_dimensions_size(); i++) { + lhs_index[dnums.lhs_batch_dimensions(i)] = result_index[idx]; + rhs_index[dnums.rhs_batch_dimensions(i)] = result_index[idx]; + idx++; + } + + // Next we have non-contracting dimensions, if any. + for (int64_t i = 0; i < lhs_non_contracting_dims.size(); i++) { + lhs_index[lhs_non_contracting_dims[i]] = result_index[idx++]; + } + for (int64_t i = 0; i < rhs_non_contracting_dims.size(); i++) { + rhs_index[rhs_non_contracting_dims[i]] = result_index[idx++]; + } + + // Accumulate resulting product along the contracting dimensions. + ElementwiseT result_val = static_cast(0); + for (int64_t k = 0; k < total_contraction_size; k++) { + const auto lhs = + static_cast(lhs_literal.Get(lhs_index)); + const auto rhs = + static_cast(rhs_literal.Get(rhs_index)); + if (is_packed_nibble) { + auto lhs_n0 = ToArithmeticSafeType(Nibble0(lhs)); + auto lhs_n1 = ToArithmeticSafeType(Nibble1(lhs)); + auto rhs_n0 = ToArithmeticSafeType(Nibble0(rhs)); + auto rhs_n1 = ToArithmeticSafeType(Nibble1(rhs)); + result_val += (lhs_n0 * rhs_n0) + (lhs_n1 * rhs_n1); + } else { + result_val += + ToArithmeticSafeType(lhs) * ToArithmeticSafeType(rhs); + } + + // If there are no contracting dimensions, do not try to count down + // from -1 to 0; that's an infinite loop. + if (!contracting_dim_sizes.empty()) { + for (int64_t i = contracting_dim_sizes.size() - 1; i >= 0; --i) { + lhs_index[lhs_contracting_dims[i]]++; + rhs_index[rhs_contracting_dims[i]]++; + if (lhs_index[lhs_contracting_dims[i]] != + contracting_dim_sizes[i]) { + break; + } + lhs_index[lhs_contracting_dims[i]] = 0; + rhs_index[rhs_contracting_dims[i]] = 0; + } + } + } + + return static_cast(result_val); + })); + + parent_->evaluated_[dot] = std::move(result); + return OkStatus(); + } + + Status HandleDotSlowPath(const HloInstruction* dot) { + auto lhs = dot->operand(0); + auto rhs = dot->operand(1); + CHECK(dot->shape().IsArray()); + CHECK(lhs->shape().IsArray()); + CHECK(rhs->shape().IsArray()); + const bool lhs_same = + ShapeUtil::SameElementType(lhs->shape(), dot->shape()); + const bool rhs_same = + ShapeUtil::SameElementType(rhs->shape(), dot->shape()); + const Literal& lhs_literal = parent_->GetEvaluatedLiteralFor(lhs); + const Literal& rhs_literal = parent_->GetEvaluatedLiteralFor(rhs); + if (lhs_same && rhs_same) { + return HandleDotSlowPathWithLiterals(dot, lhs_literal, rhs_literal); + } + if (lhs_same) { + return HandleDotSlowPathWithLiterals( + dot, lhs_literal, + rhs_literal.Convert(dot->shape().element_type()).value()); + } + if (rhs_same) { + return HandleDotSlowPathWithLiterals( + dot, lhs_literal.Convert(dot->shape().element_type()).value(), + rhs_literal); + } + return HandleDotSlowPathWithLiterals( + dot, lhs_literal.Convert(dot->shape().element_type()).value(), + rhs_literal.Convert(dot->shape().element_type()).value()); + } + + Status HandlePad(const HloInstruction* pad) override { + CHECK(pad->operand(0)->shape().IsArray()); + // Padding value must be scalar. + CHECK(ShapeUtil::IsScalar(pad->operand(1)->shape())); + CHECK_EQ(pad->operand(0)->shape().rank(), + pad->padding_config().dimensions_size()); + + TF_ASSIGN_OR_RETURN(auto inferred_return_shape, + ShapeInference::InferPadShape( + /*operand_shape=*/pad->operand(0)->shape(), + /*padding_value_shape=*/pad->operand(1)->shape(), + /*padding_config=*/pad->padding_config())); + CHECK(ShapeUtil::Compatible(pad->shape(), inferred_return_shape)) + << "return shape is set to: " << ShapeUtil::HumanString(pad->shape()) + << " but is inferred to be: " + << ShapeUtil::HumanString(inferred_return_shape); + + // Create new HLO of padded shape with padding value. + ReturnT scalar = + parent_->GetEvaluatedLiteralFor(pad->operand(1)).Get({}); + Literal result(pad->shape()); + TF_RETURN_IF_ERROR(result.PopulateParallel( + [&scalar](absl::Span multi_index, int) { + return scalar; + })); + + const Literal& evaluated_operand = + parent_->GetEvaluatedLiteralFor(pad->operand(0)); + + std::vector target_index(result.shape().rank(), 0); + + // Loop through each element of the operand, assign them to the + // corresponding index of the resulting padded literal. + const PaddingConfig& pad_config = pad->padding_config(); + + auto func = [&](absl::Span input_index) { + for (auto i = 0; i < input_index.size(); ++i) { + // Interior padding occurs logically before edge padding, so in the case + // of negative edge padding elements are removed from the + // interior-padded operand. + target_index[i] = + pad_config.dimensions(i).edge_padding_low() + + input_index[i] * (pad_config.dimensions(i).interior_padding() + 1); + + // Account for negative low and high padding: skip assignment if the + // any target index is out of range. + if (!(target_index[i] >= 0 && + target_index[i] < pad->shape().dimensions(i))) { + return true; + } + } + result.Set(target_index, + evaluated_operand.Get(input_index)); + return true; + }; + + std::vector zero_base(evaluated_operand.shape().dimensions_size(), + 0); + std::vector step(evaluated_operand.shape().dimensions_size(), 1); + + ShapeUtil::ForEachIndexNoStatus(evaluated_operand.shape(), zero_base, + evaluated_operand.shape().dimensions(), + step, func); + + parent_->evaluated_[pad] = std::move(result); + return OkStatus(); + } + + Status HandleClz(const HloInstruction* clz) override { + // Enable CLZ only for integer types. + if constexpr (std::is_integral_v && + !std::is_same_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[clz], + ElementWiseUnaryOp(clz, [](ElementwiseT elem_operand) { + int64_t unsigned_digits = std::numeric_limits::digits + + std::numeric_limits::is_signed; + return (unsigned_digits - 1) - Log2Floor(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(clz); + } + + Status HandlePopulationCount(const HloInstruction* popcnt) override { + if constexpr (std::is_integral_v && + !std::is_same_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[popcnt], + ElementWiseUnaryOp(popcnt, [](ElementwiseT elem_operand) { + return std::bitset(elem_operand) + .count(); + })); + return OkStatus(); + } + return UnsupportedTypeError(popcnt); + } + + Status HandleSin(const HloInstruction* sin) override { + if constexpr (std::is_floating_point_v || + is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[sin], + ElementWiseUnaryOp(sin, [](ElementwiseT elem_operand) { + return std::sin(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(sin); + } + + Status HandleCos(const HloInstruction* cos) override { + if constexpr (std::is_floating_point_v || + is_complex_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[cos], + ElementWiseUnaryOp(cos, [](ElementwiseT elem_operand) { + return std::cos(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(cos); + } + + Status HandleTan(const HloInstruction* tan) override { + if constexpr (std::is_floating_point_v) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[tan], + ElementWiseUnaryOp(tan, [](ElementwiseT elem_operand) { + return std::tan(elem_operand); + })); + return OkStatus(); + } + return UnsupportedTypeError(tan); + } + + template >* = nullptr> + Status HandleReducePrecision(const HloInstruction* reduce_precision) { + TF_ASSIGN_OR_RETURN( + parent_->evaluated_[reduce_precision], + ElementWiseUnaryOp(reduce_precision, [&](ElementwiseT elem) { + const uint32_t src_mantissa_bits = + std::numeric_limits::digits - 1; + const uint32_t src_exponent_bits = + 8 * sizeof(NativeT) - src_mantissa_bits - 1; + const uint32_t dest_mantissa_bits = reduce_precision->mantissa_bits(); + const uint32_t dest_exponent_bits = reduce_precision->exponent_bits(); + + using Uint = UnsignedIntegerTypeForSizeType; + Uint value_as_int = absl::bit_cast(elem); + + // Code is based on the CPU/GPU implementation in LLVM-emitting code. + // + // Bits in float32 type: + // mantissa : bits [0:22] + // exponent : bits [23:30] + // sign : bits [31] + if (dest_mantissa_bits < src_mantissa_bits) { + const Uint last_mantissa_bit_mask = + Uint{1} << (src_mantissa_bits - dest_mantissa_bits); + + // Compute rounding bias for round-to-nearest with ties to even. + // This is equal to a base value of 0111... plus one bit if the last + // remaining mantissa bit is 1. + const Uint base_rounding_bias = (last_mantissa_bit_mask >> 1) - 1; + const Uint x_last_mantissa_bit = + (value_as_int & last_mantissa_bit_mask) >> + (src_mantissa_bits - dest_mantissa_bits); + const Uint x_rounding_bias = + x_last_mantissa_bit + base_rounding_bias; + + // Add rounding bias, and mask out truncated bits. Note that the + // case where adding the rounding bias overflows into the exponent + // bits is correct; the non-masked mantissa bits will all be zero, + // and the exponent will be incremented by one. + const Uint truncation_mask = ~(last_mantissa_bit_mask - 1); + value_as_int = value_as_int + x_rounding_bias; + value_as_int = value_as_int & truncation_mask; + } + if (dest_exponent_bits < src_exponent_bits) { + // Masks for f32 values. + const Uint sign_bit_mask = Uint{1} << 8 * sizeof(NativeT) - 1; + const Uint exp_bits_mask = (Uint{1 << src_exponent_bits} - 1) + << src_mantissa_bits; + + // An exponent of 2^(n-1)-1 -- that is, 0111... with the zero in the + // most- significant bit -- is equal to 1.0f for all exponent sizes. + // Adding 2^(n-1)-1 to this gives us the highest non-infinite + // exponent for a bit- size of n, and subtracting 2^(n-1)-1 from + // this gives us the lowest' exponent (corresponding to 0.0f). + // + // Thus, the f32 exponent corresponding to the highest non-infinite + // exponent for a bit size of n is (2^7-1) + 2^(n-1)-1, and the f32 + // exponent corresponding to the lowest exponent for a bit size of n + // is (2^7-1) - 2^(n-1)-1. + // + // Note that we have already checked that exponents_bits >= 1. + const Uint exponent_bias = (Uint{1} << (src_exponent_bits - 1)) - 1; + const Uint reduced_exponent_bias = + (1 << (dest_exponent_bits - 1)) - 1; + const Uint reduced_max_exponent = + exponent_bias + reduced_exponent_bias; + const Uint reduced_min_exponent = + exponent_bias - reduced_exponent_bias; + + // Do we overflow or underflow? + const Uint x_exponent = value_as_int & exp_bits_mask; + const bool x_overflows = + x_exponent > (reduced_max_exponent << src_mantissa_bits); + const bool x_underflows = + x_exponent <= (reduced_min_exponent << src_mantissa_bits); + + // Compute appropriately-signed values of zero and infinity. + const Uint x_signed_zero = value_as_int & sign_bit_mask; + const Uint x_signed_inf = x_signed_zero | exp_bits_mask; + + // Force to zero or infinity if overflow or underflow. (Note that + // this truncates all denormal values to zero, rather than rounding + // them.) + value_as_int = x_overflows ? x_signed_inf : value_as_int; + value_as_int = x_underflows ? x_signed_zero : value_as_int; + } + + NativeT reduced_result = absl::bit_cast(value_as_int); + if (std::isnan(elem)) { + reduced_result = dest_mantissa_bits > 0 + ? elem + : std::numeric_limits::infinity(); + } + return reduced_result; + })); + return OkStatus(); + } + + template || + is_complex_v>* = nullptr> + Status HandleReducePrecision(const HloInstruction* reduce_precision) { + return UnsupportedTypeError(reduce_precision); + } + + Status HandleReducePrecision( + const HloInstruction* reduce_precision) override { + return HandleReducePrecision(reduce_precision); + } + + Status HandleIota(const HloInstruction* instruction) override { + auto* iota = Cast(instruction); + if constexpr (std::is_integral_v || + is_complex_v || + std::is_floating_point_v) { + Literal result(iota->shape()); + ShapeUtil::ForEachIndexNoStatus( + iota->shape(), [&](absl::Span idx) { + result.Set(idx, static_cast(idx[iota->iota_dimension()])); + return true; + }); + parent_->evaluated_[iota] = std::move(result); + return OkStatus(); + } + return UnsupportedTypeError(iota); + } + + Status HandleRng(const HloInstruction* random) override { + RandomDistribution distribution = random->random_distribution(); + const Shape& result_shape = random->shape(); + Literal result(result_shape); + + if constexpr (std::is_floating_point_v) { + switch (distribution) { + case RNG_UNIFORM: { + const Literal& low = + parent_->GetEvaluatedLiteralFor(random->operand(0)); + const Literal& high = + parent_->GetEvaluatedLiteralFor(random->operand(1)); + + // std::uniform_real_distribution(a, b) can sometimes return a value + // equal to b. Unclear if this is a spec bug or an implementation bug + // or WAI [0] [1] [2]. Anyway for our purposes we want a half-open + // interval, so we have to re-sample if we get `b` out. + // + // [0] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176 + // [1] https://bugs.llvm.org/show_bug.cgi?id=18767 + // [2] http://open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#2524 + const ReturnT low_val = low.Get({}); + const ReturnT high_val = high.Get({}); + std::uniform_real_distribution generator( + static_cast(low_val), + static_cast(high_val)); + TF_RETURN_IF_ERROR(result.Populate( + [&](absl::Span /*indexes*/) { + while (true) { + const ReturnT v = + static_cast(generator(parent_->engine_)); + if (v >= low_val && v < high_val) { + return v; + } + } + })); + break; + } + case RNG_NORMAL: { + const Literal& mean = + parent_->GetEvaluatedLiteralFor(random->operand(0)); + const Literal& stddev = + parent_->GetEvaluatedLiteralFor(random->operand(1)); + + std::normal_distribution generator( + static_cast(mean.Get({})), + static_cast(stddev.Get({}))); + + TF_RETURN_IF_ERROR(result.Populate( + [&](absl::Span /*indexes*/) { + return static_cast(generator(parent_->engine_)); + })); + break; + } + default: + return UnimplementedStrCat("The distribution ", + RandomDistribution_Name(distribution), + " is not implemented."); + } + parent_->evaluated_[random] = std::move(result); + return OkStatus(); + } + if constexpr (std::is_integral_v) { + switch (distribution) { + case RNG_UNIFORM: { + const Literal& low = + parent_->GetEvaluatedLiteralFor(random->operand(0)); + const Literal& high = + parent_->GetEvaluatedLiteralFor(random->operand(1)); + + // Note std::uniform_int_distribution assumes interval is closed, + // i.e., [low, high], but we want [low, high) instead. Hence high-1 is + // used as the upper range. + std::uniform_int_distribution generator( + static_cast(low.Get({})), + static_cast(high.Get({})) - 1); + + TF_RETURN_IF_ERROR(result.Populate( + [&](absl::Span /*indexes*/) { + return static_cast(generator(parent_->engine_)); + })); + break; + } + case RNG_NORMAL: { + return Unimplemented( + "Normal distribution is not supported for integral types."); + } + default: + return UnimplementedStrCat("The distribution ", + RandomDistribution_Name(distribution), + " is not implemented."); + } + parent_->evaluated_[random] = std::move(result); + return OkStatus(); + } + return UnsupportedTypeError(random); + } + + private: + StatusOr ElementWiseUnaryOp( + const HloInstruction* instruction, + const std::function& unary_op) { + const Literal& operand_literal = + parent_->GetEvaluatedLiteralFor(instruction->operand(0)); + TF_ASSIGN_OR_RETURN( + auto result_literal, + (HloEvaluator::ElementWiseUnaryOpImpl( + instruction, ConvertUnaryFunction(unary_op), operand_literal))); + + return std::move(result_literal); + } + + StatusOr ElementWiseBinaryOp( + const HloInstruction* instruction, + const std::function& + binary_op) { + const auto& shape = instruction->shape(); + const auto* lhs = instruction->operand(0); + const auto* rhs = instruction->operand(1); + TF_RET_CHECK(ShapeUtil::SameDimensions(shape, rhs->shape())); + TF_RET_CHECK(ShapeUtil::SameDimensions(lhs->shape(), rhs->shape())); + + const Literal& lhs_literal = parent_->GetEvaluatedLiteralFor(lhs); + const Literal& rhs_literal = parent_->GetEvaluatedLiteralFor(rhs); + + Literal result(shape); + + TF_RETURN_IF_ERROR(result.PopulateParallel( + [&](absl::Span multi_index, int) { + return ConvertBinaryFunction(binary_op)( + lhs_literal.Get(multi_index), + rhs_literal.Get(multi_index)); + })); + return std::move(result); + } + + template + StatusOr ElementwiseTernaryOp( + const HloInstruction* instruction, + const std::function& ternary_op) { + const auto& shape = instruction->shape(); + const auto* lhs = instruction->operand(0); + const auto* rhs = instruction->operand(1); + const auto* ehs = instruction->operand(2); + TF_RET_CHECK(ShapeUtil::SameDimensions(shape, lhs->shape())); + TF_RET_CHECK(ShapeUtil::SameDimensions(lhs->shape(), rhs->shape())); + TF_RET_CHECK(ShapeUtil::SameDimensions(rhs->shape(), ehs->shape())); + + const Literal& lhs_literal = parent_->GetEvaluatedLiteralFor(lhs); + const Literal& rhs_literal = parent_->GetEvaluatedLiteralFor(rhs); + const Literal& ehs_literal = parent_->GetEvaluatedLiteralFor(ehs); + + Literal result(shape); + + TF_RETURN_IF_ERROR(result.PopulateParallel( + [&](absl::Span multi_index, int) { + return ternary_op(lhs_literal.Get(multi_index), + rhs_literal.Get(multi_index), + ehs_literal.Get(multi_index)); + })); + + return std::move(result); + } + + template + static bool IsShiftOutOfBounds(ElementwiseT rhs) { + using UnsignedT = make_specialized_unsigned_t; + UnsignedT lhs_bits_unsigned = + static_cast(std::numeric_limits::digits); + UnsignedT rhs_unsigned = static_cast(rhs); + return rhs_unsigned >= lhs_bits_unsigned; + } + + HloEvaluator* parent_; +}; + +// These extern templates prevent users of this class from implicitly +// instantiating it. We explicitly instantiate this class in the various +// hlo_evaluator_typed_visitor*.cc files. +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; +extern template class HloEvaluatorTypedVisitor; + +} // namespace xla + +#endif // XLA_HLO_EVALUATOR_HLO_EVALUATOR_TYPED_VISITOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor.h new file mode 100644 index 0000000000000000000000000000000000000000..1d981823c74797aeb9d1d49b27c772ed2018ae38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor.h @@ -0,0 +1,431 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_DFS_HLO_VISITOR_H_ +#define XLA_HLO_IR_DFS_HLO_VISITOR_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/literal.h" +#include "xla/status.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { + +class HloComputation; +class HloInstruction; + +// A postorder depth-first HloInstruction visitor. When Handle* is called on an +// instruction, all its operands were already visited. User code can subclass +// this to iterate over an HloInstruction DAG. The Handle* routines have +// operands / data unpacked for ease of use in the visitor subclass. +// +// No instruction will ever be visited twice; however, the root instruction will +// be reported again when the traversal is done via a call to FinishVisit. +// +// If new HloInstructions are added during the traversal (e.g. by replacing an +// instruction), they will also be visited if they are the operand of an +// instruction that has not been visited yet (i.e. the instruction is in state +// kNotVisited). If you want to avoid that a newly added instruction 'hlo' is +// visited, you can call SetVisited(hlo). This may be necessary in normalization +// passes that replace all instructions, otherwise already replaced instructions +// might be visited (and replaced) again. +// +// A subclass must override at least +// (either HandleElementwiseUnary or all the Handle methods for unary ops) and +// (either HandleElementwiseBinary or all the Handle methods for binary ops)). +// The default Handle methods for (unary, binary) ops call +// (HandleElementwiseUnary, HandleElementwiseBinary). +// The default (HandleElementwiseUnary, HandleElementwiseBinary) return an +// "unimplemented" error status. +// +// Note: this may change to an iterator in the future for flexibility purposes. +// +// Users should not use this class directly, but use the type-aliases +// DfsHloVisitor/ConstDfsHloVisitor instead. +template +class DfsHloVisitorBase { + static_assert( + std::is_same::value || + std::is_same::value, + "Template argument expected to be HloInstruction* or const " + "HloInstruction*"); + + public: + DfsHloVisitorBase() = default; + virtual ~DfsHloVisitorBase() = default; + + // These routines are self-descriptive, see class comment for usage + // information. + + virtual Status HandleElementwiseUnary(HloInstructionPtr hlo); + virtual Status HandleElementwiseBinary(HloInstructionPtr hlo); + + virtual Status HandleClamp(HloInstructionPtr hlo) = 0; + virtual Status HandleSelect(HloInstructionPtr hlo) = 0; + virtual Status HandleMaximum(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleMinimum(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleConcatenate(HloInstructionPtr hlo) = 0; + virtual Status HandleConvert(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleBitcastConvert(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleStochasticConvert(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleCopy(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleComplex(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleMultiply(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleDot(HloInstructionPtr hlo) = 0; + virtual Status HandlePower(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleSqrt(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleRsqrt(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleCbrt(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + /* go/keep-sorted start */ + virtual Status HandleAllGather(HloInstructionPtr hlo) = 0; + virtual Status HandleAllGatherDone(HloInstructionPtr hlo) = 0; + virtual Status HandleAllGatherStart(HloInstructionPtr hlo) = 0; + virtual Status HandleAllReduce(HloInstructionPtr hlo) = 0; + virtual Status HandleAllReduceDone(HloInstructionPtr hlo) = 0; + virtual Status HandleAllReduceStart(HloInstructionPtr hlo) = 0; + virtual Status HandleAllToAll(HloInstructionPtr hlo) = 0; + virtual Status HandleCollectivePermute(HloInstructionPtr hlo) = 0; + virtual Status HandleCollectivePermuteDone(HloInstructionPtr hlo) = 0; + virtual Status HandleCollectivePermuteStart(HloInstructionPtr hlo) = 0; + virtual Status HandleConvolution(HloInstructionPtr hlo) = 0; + virtual Status HandleOptimizationBarrier(HloInstructionPtr hlo) = 0; + virtual Status HandlePartitionId(HloInstructionPtr hlo) = 0; + virtual Status HandleReduceScatter(HloInstructionPtr hlo) = 0; + virtual Status HandleReplicaId(HloInstructionPtr hlo) = 0; + /* go/keep-sorted end */ + + /* go/keep-sorted start */ + virtual Status HandleCholesky(HloInstructionPtr hlo) = 0; + virtual Status HandleFft(HloInstructionPtr fft) = 0; + virtual Status HandleTopK(HloInstructionPtr hlo) = 0; + virtual Status HandleTriangularSolve(HloInstructionPtr hlo) = 0; + /* go/keep-sorted end */ + + virtual Status HandleGetDimensionSize(HloInstructionPtr hlo) = 0; + virtual Status HandleSetDimensionSize(HloInstructionPtr hlo) = 0; + + virtual Status HandleCompare(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleAdd(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleDivide(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleRemainder(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleSubtract(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleAbs(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleAtan2(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleRound(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleRoundNearestEven(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleLogistic(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleSign(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleNegate(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleExp(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleExpm1(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleFloor(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleCeil(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleLog(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleClz(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleLog1p(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleCos(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleSin(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleTan(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleTanh(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleReal(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleImag(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleIsFinite(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleAnd(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleNot(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleOr(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleXor(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandlePopulationCount(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + virtual Status HandleShiftLeft(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleShiftRightArithmetic(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + virtual Status HandleShiftRightLogical(HloInstructionPtr hlo) { + return HandleElementwiseBinary(hlo); + } + + virtual Status HandleReducePrecision(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + + virtual Status HandleDomain(HloInstructionPtr hlo) { + return HandleElementwiseUnary(hlo); + } + + /* go/keep-sorted start */ + virtual Status HandleInfeed(HloInstructionPtr hlo) = 0; + virtual Status HandleOutfeed(HloInstructionPtr hlo) = 0; + /* go/keep-sorted end */ + + /* go/keep-sorted start */ + virtual Status HandleBitcast(HloInstructionPtr hlo) = 0; + virtual Status HandleBroadcast(HloInstructionPtr hlo) = 0; + virtual Status HandleCall(HloInstructionPtr hlo) = 0; + virtual Status HandleConditional(HloInstructionPtr hlo) = 0; + virtual Status HandleConstant(HloInstructionPtr hlo) = 0; + virtual Status HandleCustomCall(HloInstructionPtr hlo) = 0; + virtual Status HandleDynamicReshape(HloInstructionPtr hlo) = 0; + virtual Status HandleDynamicSlice(HloInstructionPtr hlo) = 0; + virtual Status HandleDynamicUpdateSlice(HloInstructionPtr hlo) = 0; + virtual Status HandleFusion(HloInstructionPtr hlo) = 0; + virtual Status HandleGather(HloInstructionPtr hlo) = 0; + virtual Status HandleGetTupleElement(HloInstructionPtr hlo) = 0; + virtual Status HandleIota(HloInstructionPtr hlo) = 0; + virtual Status HandleMap(HloInstructionPtr hlo) = 0; + virtual Status HandleParameter(HloInstructionPtr hlo) = 0; + virtual Status HandleReduce(HloInstructionPtr hlo) = 0; + virtual Status HandleReduceWindow(HloInstructionPtr hlo) = 0; + virtual Status HandleReshape(HloInstructionPtr hlo) = 0; + virtual Status HandleReverse(HloInstructionPtr hlo) = 0; + virtual Status HandleRng(HloInstructionPtr hlo) = 0; + virtual Status HandleRngBitGenerator(HloInstructionPtr hlo) = 0; + virtual Status HandleRngGetAndUpdateState(HloInstructionPtr hlo) = 0; + virtual Status HandleScatter(HloInstructionPtr hlo) = 0; + virtual Status HandleSelectAndScatter(HloInstructionPtr hlo) = 0; + virtual Status HandleSlice(HloInstructionPtr hlo) = 0; + virtual Status HandleSort(HloInstructionPtr hlo) = 0; + virtual Status HandleTranspose(HloInstructionPtr hlo) = 0; + virtual Status HandleTuple(HloInstructionPtr hlo) = 0; + virtual Status HandleWhile(HloInstructionPtr hlo) = 0; + /* go/keep-sorted end */ + + virtual Status HandlePad(HloInstructionPtr hlo) = 0; + + virtual Status HandleAsyncStart(HloInstructionPtr hlo) = 0; + virtual Status HandleAsyncUpdate(HloInstructionPtr hlo) = 0; + virtual Status HandleAsyncDone(HloInstructionPtr hlo) = 0; + + virtual Status HandleCopyStart(HloInstructionPtr copy_start) = 0; + virtual Status HandleCopyDone(HloInstructionPtr copy_done) = 0; + + virtual Status HandleSend(HloInstructionPtr send) = 0; + virtual Status HandleSendDone(HloInstructionPtr send_done) = 0; + + virtual Status HandleRecv(HloInstructionPtr recv) = 0; + virtual Status HandleRecvDone(HloInstructionPtr recv_done) = 0; + + virtual Status HandleBatchNormTraining(HloInstructionPtr hlo) = 0; + + virtual Status HandleBatchNormInference(HloInstructionPtr hlo) = 0; + + virtual Status HandleBatchNormGrad(HloInstructionPtr hlo) = 0; + + virtual Status HandleAddDependency(HloInstructionPtr add_dependency) = 0; + virtual Status HandleAfterAll(HloInstructionPtr token) = 0; + + // Invoked to inform the visitor that the traversal has completed, and that + // the root was "root". + virtual Status FinishVisit(HloInstructionPtr root) = 0; + + // 3 possible visitation states of HLO instructions. Each instruction's + // state only flows one way: kNotVisited -> kVisiting -> kVisited. + enum VisitState { + kNotVisited = 0, + kVisiting = 1, + kVisited = 2, + }; + + VisitState GetVisitState(int id) { + auto iter = visit_state_.find(id); + if (iter == visit_state_.end()) { + return VisitState::kNotVisited; + } + return iter->second; + } + VisitState GetVisitState(const HloInstruction& instruction); + + // Resize internal state if necessary to hold state for ids <= num. + // This call is purely a performance hint and can be omitted without + // affecting correctness. + void ReserveVisitStates(int num) { visit_state_.reserve(num); } + size_t VisitStateCapacity() const { return visit_state_.capacity(); } + + // Useful when we want to visit the same computation more than once with the + // same visitor. + void ResetVisitStates() { + // Clear the map, but don't resize the capacity across uses -- Calculating + // and reserving space could be expensive, and we always use the same + // module->instruction_count() as the capacity. + visit_state_.erase(visit_state_.begin(), visit_state_.end()); + } + + // Useful when we want to free up the memory used by the visit state without + // destroying the actual visitor subclass. + void DestroyVisitState() { + visit_state_ = absl::flat_hash_map{}; + } + + void SetVisitState(int id, VisitState state) { visit_state_[id] = state; } + + // Sets the visitation state of the given instruction as kVisiting. + // + // Precondition: current state must be kNotVisited. + void SetVisiting(const HloInstruction& instruction); + + // Sets the visitation state of the given instruction as kVisited. + // + // Precondition: current state must be either kNotVisited or kVisiting. + void SetVisited(const HloInstruction& instruction); + + // Returns whether the state of the given instruction is kVisiting. + bool IsVisiting(const HloInstruction& instruction) { + return GetVisitState(instruction) == kVisiting; + } + + // Returns whether the state of the given instruction is kVisited. + bool DidVisit(const HloInstruction& instruction) { + return GetVisitState(instruction) == kVisited; + } + + // Returns whether the state of the given instruction is kNotVisited. + bool NotVisited(const HloInstruction& instruction) { + return GetVisitState(instruction) == kNotVisited; + } + + // This method should be overridden by subclasses that wish to run some + // operation on an op before its Handle* visitor method is called. + // + // For any HLO op, the order of calls is: + // + // Preprocess(op); + // Handle/OpType/(op); + // Postprocess(op); + // + // Overriding methods should call DfsHloVisitor::Preprocess before doing their + // own preprocessing. + virtual Status Preprocess(HloInstructionPtr hlo); + + // This method should be overridden by subclasses that wish to run some + // operation on an op after its Handle* visitor method is called. See + // Preprocess for more details. + // + // Overriding methods should call DfsHloVisitor::Postprocess after doing their + // own postprocessing. + virtual Status Postprocess(HloInstructionPtr hlo); + + private: + absl::flat_hash_map visit_state_; + + DfsHloVisitorBase(const DfsHloVisitorBase&) = delete; + DfsHloVisitorBase& operator=(const DfsHloVisitorBase&) = delete; +}; + +// Explicit instantiations in dfs_hlo_visitor.cc. +extern template class DfsHloVisitorBase; +extern template class DfsHloVisitorBase; + +// Users should use one of these two type aliases, which are the only two valid +// instantiations of DfsHloVisitorBase. +using DfsHloVisitor = DfsHloVisitorBase; +using ConstDfsHloVisitor = DfsHloVisitorBase; + +} // namespace xla + +#endif // XLA_HLO_IR_DFS_HLO_VISITOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor_with_default.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor_with_default.h new file mode 100644 index 0000000000000000000000000000000000000000..93cf5a6dba06d96c8e80506ae3fdd142317cf0b7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dfs_hlo_visitor_with_default.h @@ -0,0 +1,401 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_DFS_HLO_VISITOR_WITH_DEFAULT_H_ +#define XLA_HLO_IR_DFS_HLO_VISITOR_WITH_DEFAULT_H_ + +#include +#include + +#include "absl/base/optimization.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/dfs_hlo_visitor.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/statusor.h" +#include "tsl/platform/status.h" + +namespace xla { + +// DfsHloVisitor with default action based on the HloInstruction being visited. +// Users should not use this class directly, but use the type aliases +// DfsHloVisitorWithDefault/ConstDfsHloVisitorWithDefault instead. +// +// Do *not* add an override to this class if the opcode is covered by +// HandleElementwiseUnary/Binary. These opcode handlers dispatch to +// HandleElementwiseUnary/Binary in DfsHloVisitorBase. Adding such a handler +// here will break passes which rely on the HandleElementwiseUnary/Binary +// handling these opcodes. +template +class DfsHloVisitorWithDefaultBase + : public DfsHloVisitorBase { + public: + DfsHloVisitorWithDefaultBase() = default; + ~DfsHloVisitorWithDefaultBase() override = default; + + // Default action performed on HloInstruction. + virtual Status DefaultAction(HloInstructionPtr hlo_instruction) = 0; + + Status HandleElementwiseUnary(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleElementwiseBinary(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + + Status HandleBatchNormTraining(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + + Status HandleBatchNormInference(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + + Status HandleBatchNormGrad(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + + Status HandleClamp(HloInstructionPtr clamp) override { + return DefaultAction(clamp); + } + Status HandleConcatenate(HloInstructionPtr concatenate) override { + return DefaultAction(concatenate); + } + Status HandleSelect(HloInstructionPtr select) override { + return DefaultAction(select); + } + Status HandleDot(HloInstructionPtr dot) override { + return DefaultAction(dot); + } + Status HandleConvolution(HloInstructionPtr convolution) override { + return DefaultAction(convolution); + } + Status HandleFft(HloInstructionPtr fft) override { + return DefaultAction(fft); + } + Status HandleTriangularSolve(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleCholesky(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleOptimizationBarrier(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleAllGather(HloInstructionPtr crs) override { + return DefaultAction(crs); + } + Status HandleAllGatherStart(HloInstructionPtr crs) override { + return DefaultAction(crs); + } + Status HandleAllGatherDone(HloInstructionPtr crs) override { + return DefaultAction(crs); + } + Status HandleAllReduce(HloInstructionPtr crs) override { + return DefaultAction(crs); + } + Status HandleReduceScatter(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleAllReduceStart(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleAllReduceDone(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleAllToAll(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleCollectivePermute(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleCollectivePermuteStart(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleCollectivePermuteDone(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleReplicaId(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandlePartitionId(HloInstructionPtr hlo) override { + return DefaultAction(hlo); + } + Status HandleRng(HloInstructionPtr random) override { + return DefaultAction(random); + } + Status HandleRngBitGenerator(HloInstructionPtr random) override { + return DefaultAction(random); + } + Status HandleRngGetAndUpdateState(HloInstructionPtr random) override { + return DefaultAction(random); + } + Status HandleInfeed(HloInstructionPtr infeed) override { + return DefaultAction(infeed); + } + Status HandleOutfeed(HloInstructionPtr outfeed) override { + return DefaultAction(outfeed); + } + Status HandleReverse(HloInstructionPtr reverse) override { + return DefaultAction(reverse); + } + Status HandleSort(HloInstructionPtr sort) override { + return DefaultAction(sort); + } + Status HandleConstant(HloInstructionPtr constant) override { + return DefaultAction(constant); + } + Status HandleIota(HloInstructionPtr iota) override { + return DefaultAction(iota); + } + Status HandleGetTupleElement(HloInstructionPtr get_tuple_element) override { + return DefaultAction(get_tuple_element); + } + Status HandleParameter(HloInstructionPtr parameter) override { + return DefaultAction(parameter); + } + Status HandleFusion(HloInstructionPtr fusion) override { + return DefaultAction(fusion); + } + Status HandleCall(HloInstructionPtr call) override { + return DefaultAction(call); + } + Status HandleCustomCall(HloInstructionPtr custom_call) override { + return DefaultAction(custom_call); + } + Status HandleSlice(HloInstructionPtr slice) override { + return DefaultAction(slice); + } + Status HandleDynamicSlice(HloInstructionPtr dynamic_slice) override { + return DefaultAction(dynamic_slice); + } + Status HandleDynamicUpdateSlice( + HloInstructionPtr dynamic_update_slice) override { + return DefaultAction(dynamic_update_slice); + } + Status HandleTuple(HloInstructionPtr tuple) override { + return DefaultAction(tuple); + } + Status HandleMap(HloInstructionPtr map) override { + return DefaultAction(map); + } + Status HandleReduce(HloInstructionPtr reduce) override { + return DefaultAction(reduce); + } + Status HandleReduceWindow(HloInstructionPtr reduce_window) override { + return DefaultAction(reduce_window); + } + Status HandleSelectAndScatter(HloInstructionPtr select_and_scatter) override { + return DefaultAction(select_and_scatter); + } + Status HandleBitcast(HloInstructionPtr bitcast) override { + return DefaultAction(bitcast); + } + Status HandleBroadcast(HloInstructionPtr broadcast) override { + return DefaultAction(broadcast); + } + Status HandlePad(HloInstructionPtr pad) override { + return DefaultAction(pad); + } + Status HandleDynamicReshape(HloInstructionPtr dynamic_reshape) override { + return DefaultAction(dynamic_reshape); + } + Status HandleReshape(HloInstructionPtr reshape) override { + return DefaultAction(reshape); + } + Status HandleTranspose(HloInstructionPtr transpose) override { + return DefaultAction(transpose); + } + Status HandleWhile(HloInstructionPtr xla_while) override { + return DefaultAction(xla_while); + } + Status HandleConditional(HloInstructionPtr conditional) override { + return DefaultAction(conditional); + } + Status HandleAsyncStart(HloInstructionPtr async_start) override { + return DefaultAction(async_start); + } + Status HandleAsyncUpdate(HloInstructionPtr async_update) override { + return DefaultAction(async_update); + } + Status HandleAsyncDone(HloInstructionPtr async_done) override { + return DefaultAction(async_done); + } + Status HandleCopyStart(HloInstructionPtr copy_start) override { + return DefaultAction(copy_start); + } + Status HandleCopyDone(HloInstructionPtr copy_done) override { + return DefaultAction(copy_done); + } + Status HandleRecv(HloInstructionPtr recv) override { + return DefaultAction(recv); + } + Status HandleRecvDone(HloInstructionPtr recv_done) override { + return DefaultAction(recv_done); + } + Status HandleSend(HloInstructionPtr send) override { + return DefaultAction(send); + } + Status HandleTopK(HloInstructionPtr topk) override { + return DefaultAction(topk); + } + Status HandleSendDone(HloInstructionPtr send_done) override { + return DefaultAction(send_done); + } + Status HandleGather(HloInstructionPtr gather) override { + return DefaultAction(gather); + } + Status HandleScatter(HloInstructionPtr scatter) override { + return DefaultAction(scatter); + } + Status HandleAfterAll(HloInstructionPtr token) override { + return DefaultAction(token); + } + Status HandleGetDimensionSize(HloInstructionPtr get_size) override { + return DefaultAction(get_size); + } + Status HandleSetDimensionSize(HloInstructionPtr get_size) override { + return DefaultAction(get_size); + } + Status HandleAddDependency(HloInstructionPtr add_dependency) override { + return DefaultAction(add_dependency); + } + + // Invoked to inform the visitor that the traversal has completed, and that + // the root was "root". + Status FinishVisit(HloInstructionPtr /*root*/) override { return OkStatus(); } + + private: + DfsHloVisitorWithDefaultBase(const DfsHloVisitorWithDefaultBase&) = delete; + DfsHloVisitorWithDefaultBase& operator=(const DfsHloVisitorWithDefaultBase&) = + delete; +}; + +// Users should use these type aliases which are only two valid instantiations. +using DfsHloVisitorWithDefault = DfsHloVisitorWithDefaultBase; +using ConstDfsHloVisitorWithDefault = + DfsHloVisitorWithDefaultBase; + +// A common base class for visitors performing rewriting operation. +// +// Subclasses call ReplaceWithNewInstruction and ReplaceInstruction while +// visiting. +class DfsHloRewriteVisitor : public DfsHloVisitorWithDefault { + public: + // Runs a visitor on the module and returns whether the module has changed. + StatusOr RunOnModule( + HloModule* module, + const absl::flat_hash_set& execution_threads = {}) { + Status status; + for (HloComputation* computation : + module->MakeNonfusionComputations(execution_threads)) { + status = computation->Accept(this); + if (ABSL_PREDICT_FALSE(!status.ok())) return status; + } + return changed(); + } + + // Default visitor action is to do nothing and return OK. + Status DefaultAction(HloInstruction* /*hlo_instruction*/) override { + return OkStatus(); + } + + bool changed() const { return changed_; } + + protected: + // Replaces the existing HLO instruction old_instruction, with + // new_instruction, and marks the optimizer status as changed. + // Returns the Status representing the result of the replace operation. + Status ReplaceWithNewInstruction( + HloInstruction* old_instruction, + std::unique_ptr new_instruction) { + VLOG(3) << "Replacing instruction:" + << "\n old: " << old_instruction->ToString() + << "\n new: " << new_instruction->ToString(); + Status status = old_instruction->parent()->ReplaceWithNewInstruction( + old_instruction, std::move(new_instruction)); + if (ABSL_PREDICT_TRUE(status.ok())) { + changed_ = true; + } + return status; + } + + // Replaces the existing HLO instruction old_instruction, with + // new_instruction, and marks the optimizer status as changed. + // Returns the Status representing the result of the replace operation. + StatusOr ReplaceInstruction(HloInstruction* old_instruction, + HloInstruction* new_instruction, + bool preserve_sharding) { + VLOG(3) << "Replacing instruction:" + << "\n old: " << old_instruction->ToString() + << "\n new: " << new_instruction->ToString(); + StatusOr changed_or = old_instruction->parent()->ReplaceInstruction( + old_instruction, new_instruction, preserve_sharding); + if (ABSL_PREDICT_TRUE(changed_or.ok())) { + changed_ |= changed_or.value(); + } + return changed_or; + } + + Status ReplaceInstruction(HloInstruction* old_instruction, + HloInstruction* new_instruction) { + StatusOr changed_or = + ReplaceInstruction(old_instruction, new_instruction, + /*preserve_sharding=*/false); + if (ABSL_PREDICT_TRUE(changed_or.ok())) { + DCHECK(changed_or.value()); + } + return changed_or.status(); + } + + // Mark the computation as having changed. + void MarkAsChanged() { changed_ = true; } + + private: + bool changed_ = false; +}; + +// (Const)FunctionVisitor lets you transform an +// std::function into a (Const)DfsHloVisitor. +// +// This is useful if you have code that needs to handle visitors in the form of +// both std::function and DfsHloVisitor. You can wrap the function in a +// FunctionVisitor and then treat it like any other DfsHloVisitor. +template +class FunctionVisitorBase + : public DfsHloVisitorWithDefaultBase { + public: + explicit FunctionVisitorBase( + std::function visitor_func) + : visitor_func_(std::move(visitor_func)) {} + + Status DefaultAction(HloInstructionPtr hlo_instruction) override { + return visitor_func_(hlo_instruction); + } + + private: + FunctionVisitorBase(const FunctionVisitorBase&) = delete; + FunctionVisitorBase& operator=(const FunctionVisitorBase&) = delete; + + std::function visitor_func_; +}; + +using FunctionVisitor = FunctionVisitorBase; +using ConstFunctionVisitor = FunctionVisitorBase; + +} // namespace xla + +#endif // XLA_HLO_IR_DFS_HLO_VISITOR_WITH_DEFAULT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dynamic_parameter_binding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dynamic_parameter_binding.h new file mode 100644 index 0000000000000000000000000000000000000000..b40569d249a9e2645618190810e570da56523d6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/dynamic_parameter_binding.h @@ -0,0 +1,123 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_DYNAMIC_PARAMETER_BINDING_H_ +#define XLA_HLO_IR_DYNAMIC_PARAMETER_BINDING_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.h" + +namespace xla { + +class HloModule; +// We currently use an explicit API that takes an extra parameter to indicate +// the runtime size of a dynamic dimension. DynamicParameterBinding indicates +// the relationship between parameter: We can have a dynamic parameter that +// points to another target parameter to indicate that the target parameter is +// dynamic. +// +// +// TODO(b/119520625): Remove this API once we have more dynamic shape infra +// ready. +class DynamicParameterBinding { + public: + // DynamicParameter represents a special parameter that is used to represent + // the runtime size of a dimension of another parameter. A dynamic parameter + // has to be a scalar value. + struct DynamicParameter { + // The parameter number of dynamic parameter. + int64_t parameter_num; + // The index of the parameter. + ShapeIndex parameter_index; + }; + + // DynamicDimension represents a dimension whose size is determined at + // runtime. A DynamicDimension's runtime size is determined by the binded + // DynamicParameter using `DynamicParameterBinding::Bind` method. + struct DynamicDimension { + // The parameter number of dynamic dimension. + int64_t parameter_num; + // The subshape index of the parameter. + ShapeIndex parameter_index; + // The dimension number in the subshape. + int64_t dimension; + + // "friend" keyword are added so these functions can be found by ADL. + template + friend H AbslHashValue(H h, const DynamicDimension& m) { + return H::combine(std::move(h), m.parameter_num, m.parameter_index, + m.dimension); + } + + friend bool operator==(const DynamicDimension& lhs, + const DynamicDimension& rhs) { + return lhs.parameter_num == rhs.parameter_num && + lhs.parameter_index == rhs.parameter_index && + lhs.dimension == rhs.dimension; + } + }; + + DynamicParameterBinding() = default; + + virtual ~DynamicParameterBinding() = default; + + // Adds binding which indicates that the dimension indicated by + // `dynamic_dimension` is dynamic, and its runtime size is represented by + // `dynamic_parameter`. + Status Bind(const DynamicParameter& dynamic_parameter, + const DynamicDimension& dynamic_dimension); + + // Returns the parameter and the index representing the runtime size of + // dimension `dim_num` of parameter `param_num` at `param_index`. + // + // Returns nullopt if the binding is not set. + std::optional GetBinding( + const DynamicDimension& dynamic_dimension) const; + + using BindingFn = + std::function; + + // Iterate through each binding. + Status ForEachBinding(BindingFn fn) const; + + std::string ToString() const; + + // Verifies that the given binding is valid for the given module. + // Specifically, the binding's parameter and parameter size should be valid. + Status Verify(const HloModule& module) const; + + private: + // Keeps track of mappings from DynamicDimension to DynamicParameter. The + // direction of is chosen so that we can easily query if a dimension is + // dynamic and which dynamic parameter represents the real size of that + // dimension. + absl::flat_hash_map bindings_; +}; + +std::ostream& operator<<(std::ostream& out, + const DynamicParameterBinding& binding); + +} // namespace xla + +#endif // XLA_HLO_IR_DYNAMIC_PARAMETER_BINDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_casting_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_casting_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..38549d68fad5fdb9254fc98a299e69ce6bd80479 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_casting_utils.h @@ -0,0 +1,115 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Casting utility functions for HLO instructions. + +#ifndef XLA_HLO_IR_HLO_CASTING_UTILS_H_ +#define XLA_HLO_IR_HLO_CASTING_UTILS_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "tsl/platform/logging.h" + +namespace xla { + +template +using EnableIfDerivedFromHlo = + typename std::enable_if::value>::type; + +// Casts an HloInstruction pointer to one of its subclasses, dies if argument is +// nullptr or runtime information does not match. +// +// Similar to LLVM's cast. +template * = nullptr> +const T* Cast(const HloInstruction* instruction) { + CHECK(instruction != nullptr); + CHECK(T::ClassOf(instruction)) + << "Invalid HloInstruction casting. Destination type: " + << typeid(T).name() << ". Instruction: " << instruction->name(); + const T* casted = static_cast(instruction); +#ifndef NDEBUG + const T* dynamic_casted = dynamic_cast(instruction); + CHECK(dynamic_casted != nullptr) + << "Invalid HloInstruction casting. Destination type: " + << typeid(T).name() << ". Instruction: " << instruction->name(); +#endif + return casted; +} + +// Non-const overload of Cast. +template * = nullptr> +T* Cast(HloInstruction* instruction) { + return const_cast( + Cast(const_cast(instruction))); +} + +// Works just like the Cast, except that it allows for a null pointer as an +// argument which it then propagates. +// +// Similar to LLVM's cast_or_null. +template * = nullptr> +const T* CastOrNull(const HloInstruction* instruction) { + return instruction != nullptr ? Cast(instruction) : nullptr; +} + +// Non-const overload of CastOrNull. +template * = nullptr> +T* CastOrNull(HloInstruction* instruction) { + return const_cast( + CastOrNull(const_cast(instruction))); +} + +// Casts an HloInstruction pointer to one of its subclasses, dies if argument is +// nullptr, returns nullptr if runtime information does not match. +// +// Similar to LLVM's dyn_cast. +template * = nullptr> +const T* DynCast(const HloInstruction* instruction) { + CHECK(instruction != nullptr); + const T* casted = + T::ClassOf(instruction) ? static_cast(instruction) : nullptr; +#ifndef NDEBUG + CHECK_EQ(casted, dynamic_cast(instruction)); +#endif + return casted; +} + +// Non-const overload of DynCast. +template * = nullptr> +T* DynCast(HloInstruction* instruction) { + return const_cast( + DynCast(const_cast(instruction))); +} + +// Works just like the DynCast, except that it allows for a null pointer as an +// argument which it then propagates. +// +// Similar to LLVM's dyn_cast_or_null. +template * = nullptr> +const T* DynCastOrNull(const HloInstruction* instruction) { + return instruction != nullptr ? DynCast(instruction) : nullptr; +} + +// Non-const overload of DynCastOrNull. +template * = nullptr> +T* DynCastOrNull(HloInstruction* instruction) { + return const_cast( + DynCastOrNull(const_cast(instruction))); +} + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_CASTING_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_clone_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_clone_context.h new file mode 100644 index 0000000000000000000000000000000000000000..b9115bb46cae48358026b8deecdf9dc860a992b6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_clone_context.h @@ -0,0 +1,98 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_CLONE_CONTEXT_H_ +#define XLA_HLO_IR_HLO_CLONE_CONTEXT_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/map_util.h" + +namespace xla { + +class HloInstruction; +class HloComputation; +class HloModule; + +// Data structure used to track the cloning of HloInstruction and HloComputation +// objects. +class HloCloneContext { + public: + // Creates a new HloCloneContext object to clone HloInstruction and + // HloComputation objects to be added to the module specified as argument. + // The suffix string will be appended to computation names. + explicit HloCloneContext(HloModule* module, const std::string& suffix = "") + : module_(module), suffix_(suffix) {} + + HloModule* module() const { return module_; } + + const std::string& suffix() const { return suffix_; } + + void MapInstruction(const HloInstruction* old_instruction, + HloInstruction* new_instruction) { + instructions_[old_instruction] = new_instruction; + } + + void MapComputation(const HloComputation* old_computation, + HloComputation* new_computation) { + computations_[old_computation] = new_computation; + } + + // Finds the new instruction mapped to its old copy, or return nullptr in case + // it is not found. + HloInstruction* FindInstruction(const HloInstruction* old_instruction) const { + return FindOrDefault(instructions_, old_instruction, nullptr); + } + + // Finds the new computation mapped to its old copy, or return nullptr in case + // it is not found. + HloComputation* FindComputation(const HloComputation* old_computation) const { + return FindOrDefault(computations_, old_computation, nullptr); + } + + // Retrieves the new instruction mapped to its old copy, or fail if not found. + HloInstruction* GetInstruction(const HloInstruction* old_instruction) const { + return FindOrDie(instructions_, old_instruction); + } + + // Retrieves the new computation mapped to its old copy, or fail if not found. + HloComputation* GetComputation(const HloComputation* old_computation) const { + return FindOrDie(computations_, old_computation); + } + + const absl::flat_hash_map& + cloned_instructions() const { + return instructions_; + } + + const absl::flat_hash_map& + cloned_computations() const { + return computations_; + } + + private: + HloCloneContext(const HloCloneContext&) = delete; + const HloCloneContext& operator=(const HloCloneContext&) = delete; + + HloModule* module_; + std::string suffix_; + absl::flat_hash_map instructions_; + absl::flat_hash_map computations_; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_CLONE_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_computation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_computation.h new file mode 100644 index 0000000000000000000000000000000000000000..af2b80496d6c252b24c94ce9930d8cb128d76406 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_computation.h @@ -0,0 +1,927 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_COMPUTATION_H_ +#define XLA_HLO_IR_HLO_COMPUTATION_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/cord.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/dfs_hlo_visitor.h" +#include "xla/hlo/ir/hlo_clone_context.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/iterator_util.h" +#include "xla/printer.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/name_uniquer.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +class HloModule; + +// Describes a computation at the HLO level. +// +// You can think of an HloComputation like a function. It has some inputs +// (parameters) and returns exactly one value (the value of its root node). If +// you want to return multiple values, you can return a tuple. +// +// The instructions inside of a computation do not have an explicit total order. +// Instead, they have a partial order determined by their data and control +// dependencies. +// +// An HloModule contains one "entry computation" -- this is like main() in a C +// program. Every other computation inside of a module is attached to one or +// more HloInstructions, as a "nested computation". For example, the kMap +// instruction has a nested computation and "applies" it to every element of its +// input, elementwise. (That is, the input [x, y, z] is transformed to [f(x), +// f(y), f(z)].) +class HloComputation { + public: + // Used by instructions_. + using InstructionList = std::list>; + + // Builder class for HloComputation. + class Builder { + public: + explicit Builder(absl::string_view name, + HloInstruction* fusion_instruction = nullptr) + : name_(name), fusion_instruction_(fusion_instruction) {} + Builder(Builder&& b) = default; + virtual ~Builder() = default; + + // Build and return an HloComputation. The parameter root_instruction + // specifies the already-added instruction to use as the root. If + // root_instruction is nullptr then use the last added instruction as the + // root. + std::unique_ptr Build( + HloInstruction* root_instruction = nullptr); + + // Add the instruction to be part of this computation. + // If the new instruction is derived from another one, + // you probably want to do + // `original_inst->AddInstruction(new_inst)` instead. + virtual HloInstruction* AddInstruction( + std::unique_ptr instruction) { + auto* added_instruction = instruction.get(); + instructions_.push_back(std::move(instruction)); + return added_instruction; + } + + HloInstruction* AddInstruction(std::unique_ptr instruction, + std::optional new_name) { + instruction->SetAndSanitizeName(new_name.value()); + return AddInstruction(std::move(instruction)); + } + + StatusOr AddParameter( + std::unique_ptr parameter) { + if (!parameter_numbers_.insert(parameter->parameter_number()).second) { + return InternalError("Duplicate parameter number %d", + parameter->parameter_number()); + } + return AddInstruction(std::move(parameter)); + } + + Status ForEachInstruction( + absl::FunctionRef func) const { + for (const auto& instruction : instructions_) { + TF_RETURN_IF_ERROR(func(instruction.get())); + } + return OkStatus(); + } + + HloInstruction* last_added_instruction() const { + return instructions_.empty() ? nullptr : instructions_.back().get(); + } + + private: + const std::string name_; + HloInstruction* fusion_instruction_; + std::vector> instructions_; + absl::flat_hash_set parameter_numbers_; + + Builder(const Builder&) = delete; + Builder& operator=(const Builder&) = delete; + }; + + // Helper class to automatically set the OpMetadata for every instruction + // added to a computation. + class MetadataBuilder { + public: + MetadataBuilder(HloComputation* computation, const OpMetadata& metadata) + : computation_(computation), metadata_(metadata) {} + + HloInstruction* AddInstruction( + std::unique_ptr instruction) { + instruction->set_metadata(metadata_); + return computation_->AddInstruction(std::move(instruction)); + } + + private: + HloComputation* computation_; + OpMetadata metadata_; + }; + + ~HloComputation(); + + // Add an instruction to the computation. The computation takes ownership of + // the instruction. + HloInstruction* AddInstruction(std::unique_ptr instruction, + absl::string_view new_name = ""); + + HloInstruction* AddInstruction(std::unique_ptr instruction, + const OpMetadata* metadata); + + // Replace the old parameter at index param_no with + // `instruction`. Updates uses and root instruction. Removes old + // instruction from computation. No check is done on the shape. + HloInstruction* ReplaceParameter(int64_t param_no, + std::unique_ptr instruction); + + // Remove the param_no'th parameter from the computation. + // Note this is only applicatable to the computation for the fusion + // instruction. + Status RemoveParameter(int64_t param_no); + + // Remove unused parameters from the computation. + // Note this is only applicatable to the computation for the fusion + // instruction. + Status RemoveUnusedParametersFromFusedComputation(); + + // Remove unused parameters from the computation. Unlike + // RemoveUnusedParametersFromFusedComputation, this function can be used + // to remove parameters from non-fusion computations. + Status RemoveUnusedParametersFromAnyComputation(); + + // Adds a new parameter instruction to a fusion computation. + // + // This should be a new parameter. Instruction will be appended to parameters + // and inserted to the instruction list. + HloInstruction* AddParameter(std::unique_ptr instruction); + + // Adds a new parameter instruction to the entry computation and update + // the parent module config to reflect the change. + // + // This should be a new parameter. Instruction will be appended to parameters + // and inserted to the instruction list. + HloInstruction* AddEntryComputationParameter( + std::unique_ptr instruction); + + // Replaces an old parameter with a new parameter. Adds the new parameter + // instruction to the entry computation. Updates users instruction. + Status ReplaceEntryComputationParameter( + int64_t param_no, HloInstruction* old_instruction, + std::unique_ptr instruction); + + // Remove an instruction from the computation. The instruction must have no + // users. Instruction is deallocated with this call. + Status RemoveInstruction(HloInstruction* instruction); + + // Removes an instruction from the computation. The instruction must have no + // users. Instruction is deallocated with this call. The instruction will be + // removed even if it is marked as not removable. + Status ForceRemoveInstruction(HloInstruction* instruction); + + // Remove an instruction (including side effecting ones) from the computation + // and also transitively any operand that has no side effect and no users post + // removing an instruction. The instruction must have no users. Instruction is + // deallocated with this call. If given, the cleanup routine is executed on a + // removed instruction before its deallocation. If ignore_control_dependencies + // is set to true, if will remove the unused operands even when they have + // control dependencies, and transitively pass the control dependencies from + // the predecessors to the succesors of the removed instructions, so that the + // logical exeuction order of the remaining unremoved instructions are + // preserved. + Status RemoveInstructionAndUnusedOperands( + HloInstruction* instruction, + std::optional> cleanup = + std::nullopt, + bool ignore_control_dependencies = false); + + // Set the root of the computation to the given instruction. The instruction + // must have already been added to the computation. In addition it must have + // the same shape as the result of the computation for non fusion + // computations, except if accept_different_shape is set to true. + void set_root_instruction(HloInstruction* new_root_instruction, + bool accept_different_shape = false); + + // Return the root instruction of the computation. The root instruction is the + // instruction which produces the output of the computation. + HloInstruction* root_instruction() const { return root_instruction_; } + + // Returns the number of parameters for this computation. + int64_t num_parameters() const { return param_instructions_.size(); } + + // Returns the parameter instruction for the given parameter number. + HloInstruction* parameter_instruction(int64_t param_no) const { + CHECK_GE(param_no, 0); + CHECK_LT(param_no, static_cast(param_instructions_.size())) + << "Computation " << name() << " has no parameter number " << param_no; + return param_instructions_[param_no]; + } + + const HloInstruction::InstructionVector& parameter_instructions() const { + return param_instructions_; + } + + absl::string_view name() const { return name_; } + + // Use the given NameUniquer to select a unique name for the computation based + // on the computation's existing name. + void UniquifyName(NameUniquer* name_uniquer); + + // Prints a string representation of the computation. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + void Print(Printer* printer) const { + return Print(printer, HloPrintOptions::Default()); + } + void Print(Printer* printer, const HloPrintOptions& options) const; + void Print(Printer* printer, const HloPrintOptions& options, + absl::Span instruction_order) const; + + // Return a string representation of the computation. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + std::string ToString() const; + std::string ToString(const HloPrintOptions& options) const; + + // Overload which accepts an order to emit the instructions in. + std::string ToString( + const HloPrintOptions& options, + absl::Span instruction_order) const; + + // Returns a Cord representation of the computation. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + absl::Cord ToCord() const { return ToCord(HloPrintOptions::Default()); } + absl::Cord ToCord(const HloPrintOptions& options) const; + + // Overload which accepts an order to emit the instructions in. + absl::Cord ToCord( + const HloPrintOptions& options, + absl::Span instruction_order) const; + + // Returns a serialized representation of this computation. + HloComputationProto ToProto() const; + + // Creates a computation from the given proto. Arguments: + // + // proto: the proto to convert from. + // computation_map: a map from computation id to HloComputation*. This map + // must contain all computations which the newly constructed computation + // calls. + static StatusOr> CreateFromProto( + const HloComputationProto& proto, + const absl::flat_hash_map& computation_map, + bool prohibit_empty_literal = true); + + // Generates a hash value of an HLO computation. Hash considers + // information on opcode, shape, operands, and typically a root instruction. + // This function returns the same hash value for equivalent HLO computations, + // with respect to HloComputation::Equal() method. + template + friend H AbslHashValue(H h, const HloComputation& computation) { + auto instructions = computation.MakeInstructionPostOrder(); + for (auto* instruction : instructions) { + h = H::combine(std::move(h), *instruction); + } + return H::combine(std::move(h), instructions.size()); + } + + using InstructionSequence = tsl::gtl::iterator_range< + UnwrappingIterator>::iterator>>; + + using ConstInstructionSequence = tsl::gtl::iterator_range>::const_iterator>>; + + // Gets the instructions in this computation. + // + // The returned type is a range of HloInstruction*s, so you can iterate over + // it using a range-based for loop in the natural way: + // + // for (HloInstruction* instr : computation->instructions()) { ... } + // + ConstInstructionSequence instructions() const { + return {MakeUnwrappingIterator(instructions_.begin()), + MakeUnwrappingIterator(instructions_.end())}; + } + InstructionSequence instructions() { + return {MakeUnwrappingIterator(instructions_.begin()), + MakeUnwrappingIterator(instructions_.end())}; + } + + using ChannelDependencies = + absl::flat_hash_map>; + + // Compute and return a post-order of the instructions in the computation. In + // this order, definitions of values always appear before their uses. + std::vector MakeInstructionPostOrder() const; + // Same as MakeInstructionPostOrder but starting at any instruction in the + // computation, not just the root. Describes the corresponding subgraph. + std::vector MakeInstructionPostOrderFrom( + HloInstruction&) const; + std::vector MakeInstructionPostOrder( + const ChannelDependencies& channel_dependencies) const; + // Same as MakeInstructionPostOrder but with special tie-breaking behavior. + // Specifically, when ties (in ordering) between instructions occur, Reshapes + // will be sorted before other operations. + std::vector MakeInstructionPostOrderWithReshapeFirst() const; + + // Calls `func` with each instruction in the computation in post-order. + void ForEachInstructionPostOrder( + absl::FunctionRef func) const; + + int64_t instruction_count() const { return instruction_iterators_.size(); } + + // Creates and returns a list of the embedded computations called by this + // computation. This includes all embedded computations called directly or + // transitively. The embedded computations are sorted such that if computation + // A calls computation B (eg, via a map instruction) then A will appear after + // B in the list. + std::vector MakeEmbeddedComputationsList() const; + + // Creates a fusion instruction containing the given instructions. + // `fusion_kind` indicates the type of the fusion, e.g., loop fusion or fusion + // into a library call. Instructions must be in reverse topological order + // (root of the fused expression first). Replaces all uses of the original + // root instruction with the fusion instruction. The original instructions are + // removed if they have no uses after fusion (this is necessarily true for at + // least the root). + HloInstruction* CreateFusionInstruction( + absl::Span instructions_to_fuse, + HloInstruction::FusionKind fusion_kind); + + // Creates a call instruction containing the given instructions. Instructions + // must be in reverse topological order (root of the called computation + // first). Replaces all uses of the original root instruction with the call + // instruction. The original instructions are removed if they have no uses + // after creating the call (this is necessarily true for at least the root). + HloInstruction* CreateCallInstruction( + absl::Span instructions_to_call); + + // Creates an async start/done instruction pair where instruction is wrapped + // inside an asynchronous computation. The context shapes are appended to the + // output tuple of the asynchronous start which is backend specific. Returns + // the async done instruction. The new async start instruction is the operand + // of the async done instruction so that can be accessed using that. If + // present, `async_execution_thread` will be attached to the + // async-start/update/done instructions as well as wrapped computations. + // If `replace` is true, replace instruction with the async done instruction. + // If `override_names` is true, the clone on `instruction` and the async op + // created will get non-default names. + StatusOr CreateAsyncInstructions( + HloInstruction* instruction, absl::Span context_shapes, + absl::string_view async_execution_thread = + HloInstruction::kMainExecutionThread, + bool replace = true, bool override_names = false); + + // Create a deep copy of the given instruction and return the instruction + // producing the copied result. All instructions performing the copy are added + // to the computation. For array-shaped values, this method trivially returns + // a kCopy instruction. For tuple-shaped instructions, the copy is performed + // with a series of kGetTupleElement and kTuple instructions. If + // indices_to_copy is non-null then this ShapeTree indicates which elements + // (arrays) of the shape to copy. Non-copied elements are passed through + // transparently. If copies_added is non-null, then the added kCopy + // instructions will be inserted in the respective index in the given + // ShapeTree. + StatusOr DeepCopyInstruction( + HloInstruction* instruction, + const ShapeTree* indices_to_copy = nullptr, + ShapeTree* copies_added = nullptr); + + // As above, but uses a custom function to copy the leaf nodes, which could + // create alternative HLOs other than kCopy, or even pass-throughs. + StatusOr DeepCopyInstructionWithCustomCopier( + HloInstruction* instruction, + absl::FunctionRef + copy_leaf); + + // Computes and returns the ProgramShape of this computation (shape of + // parameters and result with layout). + ProgramShape ComputeProgramShape(bool include_ids = true) const; + + // Return whether `*this` and `other` are functionally equivalent. + bool Equal( + const HloComputation& other, bool is_layout_sensitive, + std::optional< + absl::FunctionRef> + computations_comparator = std::nullopt) const { + return EqualInternal(other, is_layout_sensitive, computations_comparator, + /*ignore_channel_id_values=*/false, + /*ignore_execution_thread=*/false); + } + + // Same as Equal() but ignores channel ID value mismatches on instructions, as + // long as the two instructions both have channel IDs or neither has a channel + // ID. + bool EqualIgnoringChannelIdValues( + const HloComputation& other, bool is_layout_sensitive, + std::optional< + absl::FunctionRef> + computations_comparator = std::nullopt) const { + return EqualInternal(other, is_layout_sensitive, computations_comparator, + /*ignore_channel_id_values=*/true, + /*ignore_execution_thread=*/false); + } + + bool EqualIgnoringExecutionThread( + const HloComputation& other, bool is_layout_sensitive, + bool ignore_channel_id_values, + std::optional< + absl::FunctionRef> + computations_comparator = std::nullopt) const { + return EqualInternal(other, is_layout_sensitive, computations_comparator, + ignore_channel_id_values, + /*ignore_execution_thread=*/true); + } + + // Return whether `*this` and `other` are functionally equivalent. + bool operator==(const HloComputation& other) const { + return Equal(other, true); + } + bool operator!=(const HloComputation& other) const { + return !(*this == other); + } + + // Replaces old instruction with newly created instruction. Removes old + // instruction from computation. Updates uses and root instruction. + Status ReplaceWithNewInstruction( + HloInstruction* old_instruction, + std::unique_ptr new_instruction); + + // Replaces an old instruction with a newly created instruction, and adds the + // new instruction as an entry computation's parameter. Removes old + // instruction from computation. Updates uses and root instruction. + Status ReplaceWithNewEntryComputationParameter( + HloInstruction* old_instruction, + std::unique_ptr new_instruction); + + // Replace old instruction with new instruction. Updates uses and root + // instruction. Removes old instruction from computation. Transitively removes + // non-side effecting operands of old instruction that no longer have users, + // similar to RemoveInstructionAndUnusedOperands(). Precondition: + // old_instruction and new_instruction must have the compatible shapes. + // If preserve_sharding is true, the replacement will fail if both new and old + // instruction have sharding that is not compatible, and the function will + // return false. Otherwise, when the replacement happens, if |new_instruction| + // doesn't have any sharding information it will receive the sharding + // information of |old_instruction|, and function will return true. + StatusOr ReplaceInstruction(HloInstruction* old_instruction, + HloInstruction* new_instruction, + bool preserve_sharding, + bool relay_control_dependency = false); + + // Same as above, with preserve_sharding=false. Since this replacement always + // happens, it returns just a Status as opposed to StatusOr + Status ReplaceInstruction(HloInstruction* old_instruction, + HloInstruction* new_instruction); + + // Same as ReplaceInstruction, but the new instruction can have a different + // shape. + StatusOr ReplaceInstructionWithDifferentShape( + HloInstruction* old_instruction, HloInstruction* new_instruction, + bool preserve_sharding, bool relay_control_dependency = false); + Status ReplaceInstructionWithDifferentShape(HloInstruction* old_instruction, + HloInstruction* new_instruction); + + // Set/get the module containing this computation. + void set_parent(HloModule* module) { parent_ = module; } + const HloModule* parent() const { return parent_; } + HloModule* parent() { return parent_; } + + // Visit every node in the computation in DFS post-order with the given + // visitor. This is similar to calling HloInstruction::Accept on the root of + // the computation except this method also visits instructions not reachable + // via the root. The root instruction of the computation is visited last, and + // the visitor's FinishVisit method is called once upon completion (with the + // root instruction as the argument). + template + Status Accept(DfsHloVisitorBase* visitor) const; + + // Same as Accept() above, but the order of operand and control predecessor + // visitation is determined by the given operand order; if compare(A, B) == + // true, A is visited before B. + Status AcceptWithOperandOrder( + DfsHloVisitor* visitor, + const HloInstruction::CompareFunction& operand_order) const; + + // Visit every node in the computation in the given order. 'order' must + // be a topological sort of all instructions in the computation. + template + Status AcceptOrdered(DfsHloVisitorBase* visitor, + absl::Span order) const; + + // Returns a deep copy of this computation including all instructions. + // If the clone context is specified, it will be populated with the cloned + // object mappings, and its module() will be used to add new computations + // into. + std::unique_ptr Clone(const std::string& suffix = "clone", + HloCloneContext* context = nullptr); + + // Like Clone(), but if an instruction is present in replacement_map, we use + // the map's value to replace that instruction in the cloned computation. + // + // If replacements is nullptr, don't perform replacement. + // If replacements maps a key to nullptr, we remove that instruction from the + // new computation. If an element of `replacements` references an instruction + // that's not already in the computation, it's cloned and added to the new + // computation. + // + // 'extra_parameters' allows to specify additional parameters that should be + // added to the computation. + // + // All relevant instructions are cloned, *including* unique_ptr in the + // `replacements` map. + std::unique_ptr CloneWithReplacements( + const absl::flat_hash_map>* replacements, + absl::Span extra_parameters = {}, + HloCloneContext* context = nullptr, const std::string& suffix = "clone", + const HloInstruction* new_root = nullptr); + + // Like CloneWithReplacements(), but this is a const method and `context` must + // be specified. + std::unique_ptr CloneInContext( + HloCloneContext& context, + const absl::flat_hash_map>* replacements = + nullptr, + absl::Span extra_parameters = {}, + const std::string& suffix = "clone", + const HloInstruction* new_root = nullptr) const; + + // Convenience overloads for CloneWithReplacements. You want to do + // + // CloneWithReplacements({{a, std::move(b)}, {c, std::move(d)}}) // ERROR + // + // but that doesn't work because std::initializer_list is not movable. These + // overloads let you do + // + // CloneWithReplacementPairs({a, std::move(b)}, {c, std::move(d)}); // OK + // + std::unique_ptr CloneWithReplacementPairs( + std::pair> r1, + HloCloneContext* context = nullptr, const std::string& suffix = "clone"); + std::unique_ptr CloneWithReplacementPairs( + std::pair> r1, + std::pair> r2, + HloCloneContext* context = nullptr, const std::string& suffix = "clone"); + std::unique_ptr CloneWithReplacementPairs( + std::pair> r1, + std::pair> r2, + std::pair> r3, + HloCloneContext* context = nullptr, const std::string& suffix = "clone"); + + // Returns true if the given instruction can be removed from the computation. + // Parameter instructions cannot be removed without violating invariants of + // the HLO computation with the exception of fusion computation. A parameter + // instruction is removable for a fusion computation. + // + // Note that IsSafelyRemovable() is a necessary condition to remove an + // instruction rather than a sufficient condition. For example, instructions + // with side-effect (e.g., Send, Infeed) may be removed from a computation, + // but the transformation must guarantee the invariants relevant to the + // instructions still hold (e.g., Send and Recv must be removed together to + // make each channel complete). + bool IsSafelyRemovable(const HloInstruction* instruction, + bool ignore_control_dependency = false); + + // Returns a map from an instruction to the group of instructions associated + // with the same channel. These instructions will be considered as a single + // node for dependency purposes. + // RecvDone ops will map to the corresponding Send op. + // Cross-partition collectives will map to every other instruction with the + // same channel ID (it doesn't map to itself). + ChannelDependencies ComputeChannelDependencies() const; + + // Returns true if this computation has a side effect. A computation has a + // side effect if it contains one or more instructions with a side effect. + bool HasSideEffect() const; + + // Returns if this computation is a fusion computation. + // Do not use this method to determine if fusion_instruction_ != nullptr. + // Instead, directly do: FusionInstruction() != nullptr + bool IsFusionComputation() const { return is_fusion_computation_; } + + // Returns if this computation is the entry computation of the module. + bool IsEntryComputation() const; + + // Returns the owning fusion instruction, or nullptr if this is not a fusion + // computation. + HloInstruction* FusionInstruction() const { return fusion_instruction_; } + void SetFusionInstruction(HloInstruction* fusion_instruction) { + CHECK(!IsCustomCallComputation() && !IsAsyncComputation()); + fusion_instruction_ = fusion_instruction; + is_fusion_computation_ |= (fusion_instruction != nullptr); + } + + // Returns if this computation is a custom-call computation. + bool IsCustomCallComputation() const { return is_custom_call_computation_; } + + // Returns the owning custom call instruction, or nullptr if this is not a + // custom call computation. + HloInstruction* CustomCallInstruction() const { + return custom_call_instruction_; + } + void SetCustomCallInstruction(HloInstruction* custom_call_instruction) { + CHECK(!IsFusionComputation() && !IsAsyncComputation()); + custom_call_instruction_ = custom_call_instruction; + is_custom_call_computation_ |= (custom_call_instruction != nullptr); + } + + // Returns if this computation is a to_apply region of a collective. + bool IsCollectiveCalledComputation() const { + return is_collective_called_computation_; + } + + // Returns the owning collective call instruction, or nullptr if this is not a + // collective call computation. + HloInstruction* CollectiveCallInstruction() const { + return collective_call_instruction_; + } + + void SetCollectiveCallInstruction( + HloInstruction* collective_call_instruction) { + CHECK(!IsFusionComputation() && !IsAsyncComputation() && + !IsCustomCallComputation()); + collective_call_instruction_ = collective_call_instruction; + is_collective_called_computation_ |= + (collective_call_instruction != nullptr); + } + + // Returns if this computation is an async computation. + bool IsAsyncComputation() const { return !async_instructions_.empty(); } + + // Returns the owning async instruction. It's empty if this is not an async + // computation. + const std::vector& AsyncInstructions() const { + return async_instructions_; + } + + std::vector& AsyncInstructions() { + return async_instructions_; + } + + void AddAsyncInstruction(HloInstruction& async_instruction) { + CHECK(!IsFusionComputation() && !IsCustomCallComputation()); + CHECK(async_instruction.opcode() == HloOpcode::kAsyncStart || + async_instruction.opcode() == HloOpcode::kAsyncUpdate || + async_instruction.opcode() == HloOpcode::kAsyncDone); + async_instructions_.push_back(&async_instruction); + } + + void RemoveAsyncInstruction(HloInstruction* async_instruction) { + if (async_instruction == nullptr) { + return; + } + async_instructions_.erase( + std::remove(async_instructions_.begin(), async_instructions_.end(), + async_instruction), + async_instructions_.end()); + } + + // Returns if this computation is invoked by an Hlo instruction. + bool IsCalledComputation() const { + return IsFusionComputation() || IsCustomCallComputation(); + } + + // Clear the unique ID of the computation so that it can be re-assigned, such + // as for the purpose of compacting the unique IDs. + void ClearUniqueIdInternal() { unique_id_ = -1; } + + // The id of this computation should be unique within the module. + void SetUniqueId(int64_t id) { + CHECK_EQ(unique_id_, -1); + CHECK_GE(id, 0); + unique_id_ = id; + } + + // Returns the instruction in this computation that has name `name`. Returns + // null if there is no such computation. + HloInstruction* GetInstructionWithName(absl::string_view name); + + int64_t unique_id() const { return unique_id_; } + + void SetExecutionThread(absl::string_view execution_thread) { + execution_thread_ = std::string(execution_thread); + } + + absl::string_view execution_thread() const { return execution_thread_; } + // Returns true if this computation is annotated on "main" execution thread. + bool IsMainThread() const { + return execution_thread_ == HloInstruction::kMainExecutionThread; + } + + // Deallocate instructions that are marked by "RemoveInstruction". The two + // stage clean up process is designed such that HloPass can have stable + // internal pointers to HloInstructions while we create and remove + // HloInstructions in a pass. + void Cleanup() { to_be_deleted_.clear(); } + + // Returns true if a given instruction is marked dead in this computation. + bool IsMarkedAsDead(const HloInstruction* inst); + + // Returns true iff this computation can be inlined as a single instruction. + bool CanExpandIntoSingleInstruction() const; + + private: + explicit HloComputation( + const std::string& name, int parameter_count, + std::vector>* instructions, + HloInstruction* root_instruction, HloInstruction* fusion_instruction); + + // Internal helper for adding instructions. + HloInstruction* AddInstructionInternal( + std::unique_ptr instruction); + + // Internal helper for comparison with different options. + bool EqualInternal( + const HloComputation& other, bool is_layout_sensitive, + std::optional< + absl::FunctionRef> + computations_comparator, + bool ignore_channel_id_values, bool ignore_execution_thread) const; + // Appends (fuses) HLOs in instructions_to_append into the called computation + // of the caller. + void AppendInstructionsIntoCalledComputation( + absl::Span instructions_to_append, + HloInstruction* caller); + + // Internal helper for recursive copying of an instruction. Creates and + // returns a deep copy of the given instruction. + StatusOr DeepCopyHelper( + HloInstruction* instruction, ShapeIndex* index, + absl::FunctionRef + copy_leaf); + + // Internal helper to collect unreachable roots. + std::vector CollectUnreachableRoots() const; + + enum VisitState { kVisiting, kVisited }; + void ComputeInstructionPostOrder( + HloInstruction* root, const ChannelDependencies& channel_dependencies, + absl::flat_hash_map& visited, + std::vector& post_order) const; + + void ForEachInstructionPostOrderImpl( + absl::FunctionRef func, HloInstruction* root, + const ChannelDependencies& channel_dependencies, + absl::flat_hash_map& visited) const; + + Status RemoveUnusedParametersImpl(bool allow_non_fusion); + + Status RemoveInstructionImpl(HloInstruction* instruction, + bool ignore_safety_check); + + std::string name_; + int64_t unique_id_; + HloInstruction* root_instruction_; + + // If this computation is a fusion computation, this field points to the + // corresponding fusion instruction (if it is live). Otherwise, this is null. + HloInstruction* fusion_instruction_; + + // Determines whether this computation is a fusion computation. A fusion + // computation ordinarily also has a non-null fusion_instruction_. However, if + // a fusion instruction is removed during compilation, the fusion computation + // becomes unreachable, and its fusion_instruction_ is set to null. We still + // need to regard such computations as fusion computations for HLO scheduling + // purposes. + bool is_fusion_computation_; + + // If this computation is a custom-call computation, this field points to the + // corresponding custom-call instruction (if it is live). Otherwise, this is + // null. + HloInstruction* custom_call_instruction_; + + // Determines whether this computation is a custom-call computation. + bool is_custom_call_computation_; + + // If this computation is a collective sub-computation, this field points to + // the corresponding collective instruction. Otherwise, this is null. + HloInstruction* collective_call_instruction_; + + // Determines whether this computation is a collective sub-computation. + bool is_collective_called_computation_; + + // If this computation is an async computation, this field points to the + // corresponding async instructions (if live) that call this computation. + // Otherwise, this is empty. + std::vector async_instructions_; + + // Execution thread of this computation. By default, it's main thread. + std::string execution_thread_ = HloInstruction::kMainExecutionThread; + + // Module containing this computation. + HloModule* parent_ = nullptr; + + // Store instructions in std::list as they can be added and removed + // arbitrarily and we want a stable iteration order. Keep a map from + // instruction pointer to location in the list for fast lookup. + InstructionList instructions_; + absl::flat_hash_map + instruction_iterators_; + + // Removed instructions are moved into to_be_deleted_ first and then + // deallocated when Cleanup is called. + std::vector> to_be_deleted_; + + HloInstruction::InstructionVector param_instructions_; + + HloComputation(const HloComputation&) = delete; + HloComputation& operator=(const HloComputation&) = delete; +}; + +template +Status HloComputation::Accept( + DfsHloVisitorBase* visitor) const { + // Visit unreachable roots. Beware that the visitor might delete the currently + // visited root, which would invalidate iterators if the unreachable roots + // weren't computed ahead of time. + for (HloInstruction* root : CollectUnreachableRoots()) { + VLOG(3) << "Traversing unreachable root: " << root->ToString(); + // Call FinishVisit only at the end. + TF_RETURN_IF_ERROR(root->Accept(visitor, /*call_finish_visit=*/false)); + } + // Visit the computation root instruction last. + return root_instruction()->Accept(visitor, /*call_finish_visit=*/true); +} + +// Explicit instantiations. +template Status HloComputation::Accept(DfsHloVisitor* visitor) const; +template Status HloComputation::Accept(ConstDfsHloVisitor* visitor) const; + +template +Status HloComputation::AcceptOrdered( + DfsHloVisitorBase* visitor, + absl::Span order) const { + VLOG(3) << "Accepting visitor with order."; + for (HloInstruction* root : CollectUnreachableRoots()) { + TF_RET_CHECK(absl::c_linear_search(order, root)) << root->ToString(); + } + TF_RET_CHECK(order.size() == instruction_count()); + absl::flat_hash_set visited; + for (const HloInstruction* instruction : order) { + VLOG(3) << "Visiting ordered: " << instruction->ToString(); + TF_RET_CHECK(instruction_iterators_.contains(instruction)) + << "Instruction " << instruction->name() << " is not in computation " + << name(); + TF_RET_CHECK(!visited.contains(instruction)) + << "Instruction " << instruction->name() + << " appears more than once in order"; + HloInstruction* mutable_instruction = + const_cast(instruction); + TF_RETURN_IF_ERROR(visitor->Preprocess(mutable_instruction)); + TF_RETURN_IF_ERROR(mutable_instruction->Visit(visitor)); + visitor->SetVisited(*mutable_instruction); + TF_RETURN_IF_ERROR(visitor->Postprocess(mutable_instruction)); + visited.insert(instruction); + } + return visitor->FinishVisit(root_instruction()); +} + +// Explicit instantiations. +template Status HloComputation::AcceptOrdered( + DfsHloVisitor*, absl::Span) const; +template Status HloComputation::AcceptOrdered( + ConstDfsHloVisitor*, absl::Span) const; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_COMPUTATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_domain_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_domain_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..2849dd2e3b44c747052a1d5056142e309965171b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_domain_metadata.h @@ -0,0 +1,84 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_DOMAIN_METADATA_H_ +#define XLA_HLO_IR_HLO_DOMAIN_METADATA_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "tsl/platform/status.h" + +namespace xla { + +// Cannot include hlo_instruction.h as this file is included from there. +class HloInstruction; + +// The DomainMetadata represents the base class for metadata which can be +// attached to kDomain HLO instructions. +class DomainMetadata { + public: + // A Domain data structure captures all the information about a kDomain + // bounded instruction set. + struct Domain { + // The set of instructions which are reachable from each other via + // operand/user pathways, without crossing a kDomain instruction of a given + // kind. The reach_set can contain kDomain instructions of other kinds, if + // two domains of different kind intersect each other. + absl::flat_hash_set reach_set; + + // The same instructions in reach_set, but purged from kDomain instructions + // and ordered according to their computation graph post-order, i.e. + // if instructions[pos_a] depends on instructions[pos_b], then pos_a > + // pos_b. + std::vector instructions; + + // If we consider a graph edge as an arrow oriented from the operand to the + // user, the enter_domains will contain the set of kDomain instructions + // whose dataflow enters the reach set (domain), while the exit_domains + // contains the set of kDomain instructions whose dataflow exit the reach + // set. + absl::flat_hash_set enter_domains; + absl::flat_hash_set exit_domains; + }; + + virtual ~DomainMetadata() = default; + + // Clones the metadata object. + virtual std::unique_ptr Clone() const = 0; + + // Returns the metadata type. A unique identifier which describes the real + // metadata type. + virtual absl::string_view Kind() const = 0; + + // Compares the metadata object with another one and returns true if the + // two matches. + virtual bool Matches(const DomainMetadata& other) const = 0; + + // Returns the hash value of the metadata. + virtual size_t Hash() const = 0; + + // Returns a string representation of the metadata. + virtual std::string ToString() const = 0; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_DOMAIN_METADATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_frontend_attributes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_frontend_attributes.h new file mode 100644 index 0000000000000000000000000000000000000000..7e38d15806dced518187d3e016082a97b2a72342 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_frontend_attributes.h @@ -0,0 +1,28 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_FRONTEND_ATTRIBUTES_H_ +#define XLA_HLO_IR_HLO_FRONTEND_ATTRIBUTES_H_ + +#include + +#include "xla/xla_data.pb.h" + +namespace xla { +std::string FrontendAttributesToString( + const FrontendAttributes& frontend_attributes); +} // namespace xla + +#endif // XLA_HLO_IR_HLO_FRONTEND_ATTRIBUTES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_input_output_alias_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_input_output_alias_config.h new file mode 100644 index 0000000000000000000000000000000000000000..ab06940319aa397a9fcbb53d01e965c1b59c5528 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_input_output_alias_config.h @@ -0,0 +1,220 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_INPUT_OUTPUT_ALIAS_CONFIG_H_ +#define XLA_HLO_IR_HLO_INPUT_OUTPUT_ALIAS_CONFIG_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/functional/function_ref.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.h" + +namespace xla { + +class HloModule; + +// This class specifies the alias map from output index to parameter number and +// parameter index in the entry computation. +class HloInputOutputAliasConfig { + public: + // The kind of aliases which can be set. A kMayAlias is one setup at + // compilation time by the user, and has to be respected. A kMustAlias one + // might be setup by the compiler, if it decides it is convenient to do so. + enum AliasKind { + kMayAlias, + kMustAlias, + }; + // Defines the alias information for a given output buffer. A given output + // buffer shape index can refer only to one parameter+index. + struct Alias { + Alias(int64_t parameter_number, ShapeIndex parameter_index, + AliasKind kind = kMayAlias) + : parameter_number(parameter_number), + parameter_index(std::move(parameter_index)), + kind(kind) {} + + int64_t parameter_number; + ShapeIndex parameter_index; + AliasKind kind; + + bool must_alias() const { return kind == kMustAlias; } + + std::string ToString() const { + return absl::StrFormat("(%lld, %s, %s)", parameter_number, + parameter_index.ToString(), + kind == kMustAlias ? "must-alias" : "may-alias"); + } + }; + + HloInputOutputAliasConfig() = default; + + explicit HloInputOutputAliasConfig(Shape output_shape) + : alias_(std::move(output_shape)) {} + + virtual ~HloInputOutputAliasConfig() = default; + + // Sets up alias config from `output_index` to `param_index` at + // `param_number`. + Status SetUpAlias(const ShapeIndex& output_index, int64_t param_number, + const ShapeIndex& param_index, + AliasKind must_alias = kMayAlias); + + // Returns true if the given parameter is aliased with one of the output + // buffers. + bool ParameterHasAlias(int64_t param_number, + const ShapeIndex& param_index) const { + return GetAliasedOutput(param_number, param_index).has_value(); + } + + // Checks whether the provided output index has already been aliased. + bool OutputHasAlias(const ShapeIndex& output_index) const; + + // (De)Serializes an HloInputOutputAliasConfig to/from an + // HloInputOutputAliasProto. + HloInputOutputAliasProto ToProto() const; + + static StatusOr CreateFromProto( + Shape output_shape, const HloInputOutputAliasProto& proto); + + // Returns the output index that the given parameter and parameter index is + // aliased with. A nullopt is returned if there is no output that is aliased + // with the parameter number and index. + std::optional GetAliasedOutput( + int64_t param_number, const ShapeIndex& param_index) const; + + // Returns the number of parameter and index of the parameter buffer that the + // given output buffer index is aliased with. A nullopt is returned if there + // is no parameter is aliased with the specific output. + std::optional GetAliasedParameter( + const ShapeIndex& output_index) const; + + // Returns if the parameter at the given parameter number and parameter + // index must-alias with an output. + bool ParameterMustAlias(int64_t param_number, + const ShapeIndex& param_index) const; + + using AliasFn = + absl::FunctionRef; + + // Iterates through each aliased output and input. + void ForEachAlias(AliasFn fn) const; + + using AliasFnWithStatus = + absl::FunctionRef; + + // Verifies that the given config is valid for the given module. + // Specifically, the config's input and output should be in-bound and size of + // the aliased buffers should match. + Status Verify(const HloModule& module, + absl::FunctionRef size_func) const; + + Status ForEachAliasWithStatus(AliasFnWithStatus fn) const; + + // Returns the shape of the output of the alias config. + const Shape& shape() const; + + std::string ToString() const; + + std::string ToShortString() const; + + private: + // A ShapeTree which indicates the list of buffers that's expected to be + // aliased. The key on this shape tree represents the output index. The value + // is an Alias data structure which defines the input parameter coordinates. + // If the value is nullopt, it means there is no parameter aliasing for this + // output. + ShapeTree> alias_; +}; + +// This class specifies donors of the input buffer (specified by parameter +// number and parameter index in the entry computation). The donated buffer can +// be matched with any valid output tensor, which differs from +// HloInputOutputAliasConfig. +class HloBufferDonorConfig { + public: + // Defines a input buffer donor. In real world, organ donors refer to the + // persons agreeing to remove their organs (usually after death). Similarly, a + // registered buffer donor indicates that the input parameter can be removed + // when there is no dependency. Therefore, the memory buffer can be reused by + // a matched output. + struct BufferDonor { + BufferDonor(int64_t param_number, ShapeIndex param_index) + : param_number(param_number), param_index(std::move(param_index)) {} + + int64_t param_number; + ShapeIndex param_index; + + bool operator==(const BufferDonor& other) const { + return param_number == other.param_number && + param_index == other.param_index; + } + + // A hash function borrowed from go/absl-hash. + template + friend H AbslHashValue(H h, const BufferDonor& donor) { + return H::combine(std::move(h), donor.param_number, donor.param_index); + } + }; + + HloBufferDonorConfig() = default; + virtual ~HloBufferDonorConfig() = default; + + // Register and unregister the parameter with `param_index` at `param_number` + // as a buffer donor. + Status AddBufferDonor(int64_t param_number, const ShapeIndex& param_index); + Status RemoveBufferDonor(int64_t param_number, const ShapeIndex& param_index); + + // Returns true if the given parameter is registered as a buffer donor. + bool ParameterIsBufferDonor(int64_t param_number, + const ShapeIndex& param_index) const; + + // (De)Serializes an HloBufferDonorConfig to/from an HloBufferDonorProto. + HloBufferDonorProto ToProto() const; + static StatusOr CreateFromProto( + const HloBufferDonorProto& proto); + + // Verifies that the given config is valid for the given module. + // The config's input should be in-bound and this config cannot overlap with + // the given module's input_output_alias_config. + Status Verify(const HloModule& module) const; + + // Returns the registered buffer donors + const absl::flat_hash_set& buffer_donor() const { + return buffer_donor_; + } + + std::string ToString() const; + + std::string ToShortString() const; + + private: + // A set recording the registered buffer donors. + absl::flat_hash_set buffer_donor_; +}; + +std::ostream& operator<<(std::ostream& out, + const HloInputOutputAliasConfig& config); +std::ostream& operator<<(std::ostream& out, const HloBufferDonorConfig& config); + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_INPUT_OUTPUT_ALIAS_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instruction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instruction.h new file mode 100644 index 0000000000000000000000000000000000000000..aca2ace1b6cd7fcf15c116a57ca6a3d400153ae4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instruction.h @@ -0,0 +1,2586 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// HLO instructions are in DAG form and represent the computations that the user +// has built up via the XLA service interface. They are ultimately lowered +// in a platform-aware way by traversing the HLO DAG and emitting a lowered +// form; e.g. see DfsHloVisitor. + +#ifndef XLA_HLO_IR_HLO_INSTRUCTION_H_ +#define XLA_HLO_IR_HLO_INSTRUCTION_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/attributes.h" +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/container/inlined_vector.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/comparison_util.h" +#include "xla/hlo/ir/dfs_hlo_visitor.h" +#include "xla/hlo/ir/hlo_clone_context.h" +#include "xla/hlo/ir/hlo_domain_metadata.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/iterator_util.h" +#include "xla/layout.h" +#include "xla/literal.h" +#include "xla/printer.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/mapped_ptr_container_sorter.h" +#include "xla/service/name_uniquer.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/gtl/iterator_range.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep +#include "tsl/platform/protobuf.h" + +namespace xla { + +class HloComputation; +class HloModule; + +absl::string_view PrintName(absl::string_view name, bool print_ids); + +// A bunch of switches that control how the hlo text should be printed. +class HloPrintOptions { + public: + enum class PrintSubcomputationMode { + kOff, // Do not print anything about subcomputations. + kNameOnly, // Only print the name of subcomputations. + kFullBodies, // Print the full bodies of subcomputations. + kNonSequentialBodies, // Print the full bodies of subcomputations that are + // not in a sequential context. + }; + + // Constructs the default print options: don't print large constants, don't + // compact operands, no indentation. + constexpr HloPrintOptions() + : print_operand_index_annotation_interval_(5), + print_subcomputation_mode_(PrintSubcomputationMode::kNameOnly), + indent_amount_(0), + print_large_constants_(false), + print_only_essential_constants_(false), + print_metadata_(true), + print_backend_config_(true), + print_infeed_outfeed_config_(true), + compact_operands_(false), + include_layout_in_shapes_(true), + print_result_shape_(true), + print_operand_shape_(true), + print_operand_names_(true), + print_program_shape_(true), + print_percent_(true), + print_control_dependencies_(true), + canonicalize_instruction_names_(false), + is_in_nested_computation_(false), + print_ids_(true), + canonicalize_computations_(false), + print_extra_attributes_(true), + syntax_sugar_async_ops_(true), + print_name_after_closing_brace_(false) {} + // Static reference to a default construction HloPrintOptions, to avoid + // constructing a new one each time default is needed. + static const HloPrintOptions& Default() { + ABSL_CONST_INIT static const HloPrintOptions options; + return options; + } + + static HloPrintOptions ShortParsable() { + return HloPrintOptions() + .set_print_large_constants(true) + .set_print_subcomputation_mode(PrintSubcomputationMode::kNameOnly) + .set_print_metadata(false) + .set_print_backend_config(false) + .set_print_operand_shape(false) + .set_print_operand_index_annotation_interval(0) + .set_print_program_shape(false) + .set_print_percent(false) + .set_print_control_dependencies(false); + } + + // Options to produce the canonical string representing an isomorphic + // computation graph. + static HloPrintOptions Canonical() { + return HloPrintOptions() + .set_print_subcomputation_mode(PrintSubcomputationMode::kFullBodies) + .set_print_metadata(false) + .set_print_backend_config(false) + // Compact option won't print name of operand_k, where k > a threshold. + // Canonical (and Fingerprint) must include all operands. + .set_compact_operands(false) + .set_print_operand_names(false) + .set_print_operand_shape(true) + // No index annotations as they are only for ease of human inspection. + .set_print_operand_index_annotation_interval(0) + .set_print_program_shape(false) + .set_print_percent(false) + .set_print_control_dependencies(false) + .set_canonicalize_instruction_names(true); + } + + // Options to produce a fingerprint of an HLO instruction. + // Based on Canonical() with some important changes commented below. + static HloPrintOptions Fingerprint() { + return Canonical() + // Exclude because they do not affect HLO optimizations. + .set_print_infeed_outfeed_config(false) + // Exclude floating point constant literals that are not all zeros, all + // ones, or integers because they may be randomly initialized weights, + // which may be changed across different runs. + .set_print_only_essential_constants(true) + // Remove "id" in "name.id" (after period) because it can be + // non-deterministic. This mainly affects computations' names because + // canonicalized instructions' names are in "tmp_id" format. + .set_print_ids(false) + // Sort computations. + .set_canonicalize_computations(true); + } + + // Options to produce a fingerprint of an HLO module and computation. + // Shorter (and therefore faster) than Fingerprint(). + static HloPrintOptions ModuleFingerprint() { + return Fingerprint() + // Operand shapes can be inferred from output shapes and canonicalized + // names when we have an entire computation. + .set_print_operand_shape(false); + } + + // If true, large constants will be printed out. + HloPrintOptions& set_print_large_constants(bool value) { + print_large_constants_ = value; + return *this; + } + + // If true, only integer, all-zero, are all-one constants will be printed out. + HloPrintOptions& set_print_only_essential_constants(bool value) { + print_only_essential_constants_ = value; + return *this; + } + + HloPrintOptions& set_print_subcomputation_mode( + PrintSubcomputationMode value) { + print_subcomputation_mode_ = value; + return *this; + } + + // If true, metadata will be printed. + HloPrintOptions& set_print_metadata(bool value) { + print_metadata_ = value; + return *this; + } + + // If true, backend_config will be printed. + HloPrintOptions& set_print_backend_config(bool value) { + print_backend_config_ = value; + return *this; + } + + // If true, infeed_config and outfeed_config will be printed. + HloPrintOptions& set_print_infeed_outfeed_config(bool value) { + print_infeed_outfeed_config_ = value; + return *this; + } + + // If true, result shapes will be printed. + HloPrintOptions& set_print_result_shape(bool value) { + print_result_shape_ = value; + return *this; + } + + // If true, operands' shapes will be printed. + HloPrintOptions& set_print_operand_shape(bool value) { + print_operand_shape_ = value; + return *this; + } + + // If true, operands' shapes will be printed. + HloPrintOptions& set_print_operand_index_annotation_interval(int64_t value) { + print_operand_index_annotation_interval_ = value; + return *this; + } + + // If true, the operand names will be printed. + HloPrintOptions& set_print_operand_names(bool value) { + print_operand_names_ = value; + return *this; + } + + // If true, all printed names include unique identifiers. + HloPrintOptions& set_print_ids(bool value) { + print_ids_ = value; + return *this; + } + + // If true, the HLO includes its attributes. + HloPrintOptions& set_print_extra_attributes(bool value) { + print_extra_attributes_ = value; + return *this; + } + + // If true, program shape of hlo computations will be printed. + HloPrintOptions& set_print_program_shape(bool value) { + print_program_shape_ = value; + return *this; + } + + // If true, names will be printed with prefix '%'. + HloPrintOptions& set_print_percent(bool value) { + print_percent_ = value; + return *this; + } + + // If true, control dependencies will be printed. + HloPrintOptions& set_print_control_dependencies(bool value) { + print_control_dependencies_ = value; + return *this; + } + + // If true, uses the async operation syntax sugar to print async-start, + // async-update, and async-done HLOs. If the syntax sugar is enabled and the + // async computation is trivial (i.e. only a single instruction taking + // computation parameters as operands, and otherwise is illegal), the + // computations called by these instructions will not be printed and instead + // the root of the called computation will be printed instead of these + // instructions and -start, -update, and -done suffixes will be appended to + // the opcode of the async operation. For example, for an HLO module where the + // syntax sugar is off: + // + // HloModule Module + // + // %AsyncOp (p0.1: f32[10]) -> f32[20] { + // %p0.1 = f32[10]{0} parameter(0) + // ROOT %custom-call = f32[20]{0} custom-call(f32[10]{0} %p0.1), + // custom_call_target="foo" + // } + // + // ENTRY %Entry (p0: f32[10]) -> f32[20] { + // %p0 = f32[10]{0} parameter(0) + // %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) async-start(%p0), + // calls=%AsyncOp + // %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) async-update( + // %async-start), + // calls=%AsyncOp + // ROOT %async-done = f32[20]{0} async-done(%async-update), calls=%AsyncOp + // } + // + // will be printed as following if the syntax sugar is enabled: + // + // HloModule Module + // + // ENTRY %Entry (p0: f32[10]) -> f32[20] { + // %p0 = f32[10]{0} parameter(0) + // %async-start = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-start(%p0), + // custom_call_target="foo" + // %async-update = ((f32[10]{0}), f32[20]{0}, s32[]) custom-call-update( + // %async-start), + // custom_call_target="foo" + // ROOT %async-done = f32[20]{0} custom-call-done(%async-update), + // custom_call_target="foo" + // } + HloPrintOptions& set_syntax_sugar_async_ops(bool value) { + syntax_sugar_async_ops_ = value; + return *this; + } + + // If true, only a part of operands will be printed out (note that in this + // case the text will not be parsable). + HloPrintOptions& set_compact_operands(bool value) { + compact_operands_ = value; + return *this; + } + + // If true, include the layout in any shapes that are printed (instruction + // and operands). + HloPrintOptions& set_include_layout_in_shapes(bool value) { + include_layout_in_shapes_ = value; + return *this; + } + + // If true, canonicalizes instructions' name. Instead of using "%foo.1" as + // the name of an instruction, we use "%tmp_1", "%tmp_2" etc. + HloPrintOptions& set_canonicalize_instruction_names(bool value) { + canonicalize_instruction_names_ = value; + return *this; + } + + // If true, canonicalizes computations, sorting by computations' names. + HloPrintOptions& set_canonicalize_computations(bool value) { + canonicalize_computations_ = value; + return *this; + } + + // The indent of the hlo text block. + HloPrintOptions& set_indent_amount(int value) { + indent_amount_ = value; + return *this; + } + + // If true, indicates the instruction being printed is inside a nested + // computation. + HloPrintOptions& set_is_in_nested_computation(bool value) { + is_in_nested_computation_ = value; + return *this; + } + + HloPrintOptions& set_print_name_after_closing_brace(bool value) { + print_name_after_closing_brace_ = value; + return *this; + } + + bool print_large_constants() const { return print_large_constants_; } + bool print_only_essential_constants() const { + return print_only_essential_constants_; + } + PrintSubcomputationMode print_subcomputation_mode() const { + return print_subcomputation_mode_; + } + bool print_metadata() const { return print_metadata_; } + bool print_backend_config() const { return print_backend_config_; } + bool print_infeed_outfeed_config() const { + return print_infeed_outfeed_config_; + } + bool compact_operands() const { return compact_operands_; } + bool include_layout_in_shapes() const { return include_layout_in_shapes_; } + bool print_result_shape() const { return print_result_shape_; } + bool print_operand_shape() const { return print_operand_shape_; } + bool print_operand_names() const { return print_operand_names_; } + int64_t print_operand_index_annotation_interval() const { + return print_operand_index_annotation_interval_; + } + bool print_ids() const { return print_ids_; } + bool print_program_shape() const { return print_program_shape_; } + bool print_percent() const { return print_percent_; } + bool print_control_dependencies() const { + return print_control_dependencies_; + } + bool print_extra_attributes() const { return print_extra_attributes_; } + bool syntax_sugar_async_ops() const { return syntax_sugar_async_ops_; } + bool canonicalize_instruction_names() const { + return canonicalize_instruction_names_; + } + bool canonicalize_computations() const { return canonicalize_computations_; } + int indent_amount() const { return indent_amount_; } + int is_in_nested_computation() const { return is_in_nested_computation_; } + int print_name_after_closing_brace() const { + return print_name_after_closing_brace_; + } + + private: + // The interval between the /*index=*/ annotated operands. 0 means never print + // the annotation, 1 means print annotation for every operand. + int64_t print_operand_index_annotation_interval_; + PrintSubcomputationMode print_subcomputation_mode_; + int indent_amount_; + bool print_large_constants_; + bool print_only_essential_constants_; + bool print_metadata_; + bool print_backend_config_; + bool print_infeed_outfeed_config_; + bool compact_operands_; + bool include_layout_in_shapes_; + bool print_result_shape_; + bool print_operand_shape_; + bool print_operand_names_; + bool print_program_shape_; + bool print_percent_; + bool print_control_dependencies_; + bool canonicalize_instruction_names_; + bool is_in_nested_computation_; + bool print_ids_; + bool canonicalize_computations_; + bool print_extra_attributes_; + bool syntax_sugar_async_ops_; + bool print_name_after_closing_brace_; +}; + +// For canonical string output, we need to have a canonical way to rename +// each instruction and its operands. Each operand is renamed as "tmp_", +// where is an index starting from 0. +class CanonicalNameMap { + public: + const std::string& LookupOrInsert(int unique_id) { + std::string& canonical_name = canonical_name_map_[unique_id]; + if (canonical_name.empty()) { + absl::StrAppend(&canonical_name, "tmp_", canonical_name_map_.size() - 1); + } + return canonical_name; + } + + void Reserve(size_t size) { canonical_name_map_.reserve(size); } + + private: + absl::flat_hash_map canonical_name_map_; +}; + +// HLO instructions are the atomic unit of the high-level compiler's IR. +// +// HloInstructions live inside of an HloComputation, which is analogous to a +// function in other programming languages. Nodes have no total order within +// their computation. Instead, they have a partial ordering determined by their +// data and control dependencies. +// +// HLO does not have basic blocks or explicit "branch" instructions. Instead, +// certain HloInstructions -- namely, kWhile, kConditional, and kCall -- encode +// control flow. For example, the kConditional HLO executes one of two possible +// computations, depending on the runtime value of a predicate. +// +// HLO is pure (mostly). It has no concept of mutable state. Instead, data +// values are produced by one HLO and flow into consumers across dependency +// edges. +class HloInstruction { + public: + // A fusion node computes the same value a call to its fusion computation + // would compute. However, the choice of fusion kind dictates codegen + // strategy for the backend. + // + // To generate code for a kFusion HloInstruction, most backends do something + // like the following: + // + // 1) Identify the "primary" HloInstruction of the fused computation. + // 2) Emit code that does the work of the primary node, creating its inputs + // and transforming its outputs as specified by the fused computation. + // + // In step (2), the code emitted is usually similar to the code that would be + // emitted for an *unfused* version of the primary node, except that + // + // - when the primary node reads an element of one of its operands, instead + // of loading the value from memory, it *computes* the value based on the + // contents of the fused computation. + // - when the primary node outputs a value, instead of storing it to memory, + // it forwards the value to its users, which then perform additional + // computations before the value is finally stored to memory at the root of + // the fusion node. + // + // An HloInstruction's FusionKind helps us find the kFusion instruction's + // primary node, and can also affect how we generate code in step (2). + // + // - kInput: The primary node is the root of the fused instruction. + // + // - kOutput: The primary node is not the root of the fused instruction. + // This fusion kind requires that one operand buffer of the fusion + // instruction be able to alias the output buffer. This constraint is + // usually enough to let backends find the primary node unambiguously. + // + // - kLoop: The primary node is the root of the fused computation, but, + // unlike in input fusion, we prescribe a specific implementation for + // codegen. Rather than generating code that looks like the code we'd emit + // for an unfused version of the primary/root node, we emit code that + // generates one element of the root at a time. + // + // - kCustom: Custom category for backend-specific fusions that don't fit + // into the above patterns. + // + // Not all backends support all fusion kinds, and given a particular fused + // computation, it's not in general safe to change its fusion kind. Creation + // of fusion nodes is always backend-specific. + // + // For elementwise ops (e.g. kAdd), most backends would emit a + // one-element-at-a-time implementation for the unfused version, so loop + // fusion and input fusion are probably equivalent if the root node is + // elementwise. They're not necessarily equivalent e.g. for kReduce, where an + // implementation might emit something more sophisticated for an unfused or + // input-fusion reduce, but will emit the naive code that reduces one element + // at a time for loop fusion with a reduce as the root. + // + // Another way to think of loop fusion is that it's equivalent to input + // fusion, but where the root node is an implicit identity node, whose + // unfused implementation is "read one element, write one element". + // + // TODO(b/79869434): This categorization scheme is not great. For one thing, + // input and loop fusion are basically the same thing: There is no reason for + // the HLO to encode backend-specific decisions about how e.g. a reduce that's + // the root of a fusion should be lowered. In addition, this scheme as + // written doesn't work for multi-output fusion, where the primary node is + // never actually the root (which is a kTuple instruction that gathers the + // multiple outputs of the fusion). + enum class FusionKind { + kLoop, + kInput, + kOutput, + kCustom, + }; + + inline static constexpr char kMainExecutionThread[] = "main"; + + virtual ~HloInstruction() { DetachFromOperandsAndUsers(); } + + // Detaches an instruction from its operands and users. That is, remove the + // instruction from each operand's user set and user's operand set. + void DetachFromOperandsAndUsers(); + + // Adds a derived instruction to the parent computation of this instruction. + // Also update setup the new instruction as a derived instruction. + HloInstruction* AddInstruction( + std::unique_ptr derived_instruction); + + // Creates an instruction from the given proto. Arguments: + // + // proto: the proto to convert from. + // instruction_map: a map from instruction id to HloInstruction*. This map + // must contain all operands of the newly constructed instruction. + // computation_map: a map from computation id to HloComputation*. This map + // must contain all computations which the newly constructed instruction + // calls. + static StatusOr> CreateFromProto( + const HloInstructionProto& proto, + const absl::flat_hash_map& instruction_map, + const absl::flat_hash_map& computation_map = {}, + bool prohibit_empty_literal = true); + + // Creates a parameter-retrieving instruction. + static std::unique_ptr CreateParameter( + int64_t parameter_number, const Shape& shape, absl::string_view name); + + // Creates a literal constant instruction. + static std::unique_ptr CreateConstant(Literal literal); + + // Creates an Iota instruction. + static std::unique_ptr CreateIota(const Shape& shape, + int64_t iota_dimension); + + // Creates a Top-K instruction. + static std::unique_ptr CreateTopK(const Shape& shape, + HloInstruction* input, + int64_t k, + HloComputation* compare); + + // Creates a get tuple element instruction. + static std::unique_ptr CreateGetTupleElement( + const Shape& shape, HloInstruction* operand, int64_t index); + + // Creates a get tuple element instruction. + static std::unique_ptr CreateGetTupleElement( + HloInstruction* operand, int64_t index); + + // Creates a random number generation instruction that fills a shape with + // random numbers from a given distribution. + // + // The parameters to the instruction are interpreted as follows: + // + // - If `distribution` is RNG_UNIFORM, generates a number in range + // [param0, param1). + // + // - If `distribution` is RNG_NORMAL, generates a normally-distributed value + // with mean `param0` and standard deviation `param1`. + static std::unique_ptr CreateRng( + const Shape& shape, RandomDistribution distribution, + absl::Span parameters); + + // Creates a stateless random bit generator instruction that fills a shape + // with random bits. + static std::unique_ptr CreateRngBitGenerator( + const Shape& shape, HloInstruction* state, RandomAlgorithm algorithm); + + // Creates an instruction to update the random number generator state to + // reflect the new state after `delta` units of 32 random bits are generated + // and returns the old state. + static std::unique_ptr CreateRngGetAndUpdateState( + const Shape& shape, int64_t delta); + + // Creates a unary instruction (one operand). + // Precondition: opcode must be a legitimate unary operation. + static std::unique_ptr CreateUnary(const Shape& shape, + HloOpcode opcode, + HloInstruction* operand); + + // Creates a binary instruction (two operands). + // Precondition: opcode must be a legitimate binary operation. + static std::unique_ptr CreateBinary(const Shape& shape, + HloOpcode opcode, + HloInstruction* lhs, + HloInstruction* rhs); + + // Creates a ternary instruction (three operands). + // Precondition: opcode must be a legitimate ternary operation. + static std::unique_ptr CreateTernary(const Shape& shape, + HloOpcode opcode, + HloInstruction* lhs, + HloInstruction* rhs, + HloInstruction* ehs); + + // Creates a variadic instruction (variable number of operands). + // Precondition: opcode must be a legitimate variadic operation. + static std::unique_ptr CreateVariadic( + const Shape& shape, HloOpcode opcode, + absl::Span operands); + + // Creates a map instruction, where the computation (given by the handle) is + // applied element-wise to every element in operands (across the operands, + // at a given index) + static std::unique_ptr CreateMap( + const Shape& shape, absl::Span operands, + HloComputation* map_computation); + + // Creates a convolution op, where rhs is the convolutional filter + // and window describes how the filter is applied to lhs. + static std::unique_ptr CreateConvolve( + const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, + int64_t feature_group_count, int64_t batch_group_count, + const Window& window, + const ConvolutionDimensionNumbers& dimension_numbers, + const PrecisionConfig& precision_config); + + // Creates an FFT op, of the type indicated by fft_type. + static std::unique_ptr CreateFft( + const Shape& shape, HloInstruction* operand, FftType fft_type, + absl::Span fft_length); + + // Creates an asynchronous start, update, and done op. + static std::unique_ptr CreateAsyncStart( + const Shape& shape, absl::Span operands, + HloComputation* async_computation, + std::optional async_group_id = std::nullopt, + absl::string_view async_execution_thread = kMainExecutionThread); + static std::unique_ptr CreateAsyncUpdate( + const Shape& shape, HloInstruction* operand, + HloComputation* async_computation, + std::optional async_group_id = std::nullopt, + absl::string_view async_execution_thread = kMainExecutionThread); + static std::unique_ptr CreateAsyncDone( + const Shape& shape, HloInstruction* operand, + HloComputation* async_computation, + std::optional async_group_id = std::nullopt, + absl::string_view async_execution_thread = kMainExecutionThread); + + // Creates a copy-start op, indicating whether this is a cross-program + // prefetch or not. + static std::unique_ptr CreateCopyStart( + const Shape& shape, HloInstruction* operand, + std::optional cross_program_prefetch_index = std::nullopt); + + // Creates a compare op, performing the comparison specified in direction. + static std::unique_ptr CreateCompare( + const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, + Comparison::Direction direction, + std::optional type = std::nullopt); + + static std::unique_ptr CreateTriangularSolve( + const Shape& shape, HloInstruction* a, HloInstruction* b, + const TriangularSolveOptions& options); + + static std::unique_ptr CreateCholesky( + const Shape& shape, HloInstruction* a, const CholeskyOptions& options); + + // Creates a dot op with operands 'lhs' and 'rhs' with contracting and batch + // dimensions specified in 'dimension_numbers'. + static std::unique_ptr CreateDot( + const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, + const DotDimensionNumbers& dimension_numbers, + const PrecisionConfig& precision_config); + + // Creates a reduce-precision op, where operand is the data to reduce in + // precision, and exponent_bits and mantissa_bits describe the precision to + // reduce it to. + static std::unique_ptr CreateReducePrecision( + const Shape& shape, HloInstruction* operand, int exponent_bits, + int mantissa_bits); + + // Creates an all-gather op, which concats the operands of all participants + // along all_gather_dimension. The replica_groups, channel_id, and + // use_global_device_ids arguments are identical to those in all-reduce, + // except that the order of the group members determines the concatenation + // order of inputs from different participants. + static std::unique_ptr CreateAllGather( + const Shape& shape, absl::Span operands, + int64_t all_gather_dimension, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + + // Creates an all-gather-start op, which concats the operands of all + // participants + // along all_gather_dimension. The replica_groups, channel_id, and + // use_global_device_ids arguments are identical to those in all-reduce, + // except that the order of the group members determines the concatenation + // order of inputs from different participants. Needs to be used in + // conjunction of a AllGatherDone op that synchronizes and returns the result. + static std::unique_ptr CreateAllGatherStart( + const Shape& shape, absl::Span operands, + int64_t all_gather_dimension, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + + // Creates a cross replica reduction op. + // + // `reduction_computation`: the reduction function. + // + // `replica_groups`: each ReplicaGroup contains a list of replica id. If + // empty, all replicas belong to one group in the order of 0 - (n-1). + // Allreduce will be applied within subgroups. + // For example, we have 4 replicas, then replica_groups={{0,2},{1,3}} means, + // replica 0 and 2 are in subgroup 0, replica 1 and 3 are in subgroup 1. + // + // `channel_id`: for Allreduce nodes from different modules, if + // they have the same channel_id, they will be 'Allreduce'd. If + // empty, Allreduce will not be applied cross modules. + static std::unique_ptr CreateAllReduce( + const Shape& shape, absl::Span operands, + HloComputation* reduce_computation, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + + // Creates a reduce-scatter operation which reduces its inputs across the + // given replica groups and then scatters the reduced data across the N + // participants. + static std::unique_ptr CreateReduceScatter( + const Shape& shape, absl::Span operands, + HloComputation* reduce_computation, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids, + int64_t scatter_dimension); + + // Creates an asynchronous cross replica reduction op. + // + // `reduction_computation`: the reduction function. + // + // `replica_groups`: each ReplicaGroup contains a list of replica id. If + // empty, all replicas belong to one group in the order of 0 - (n-1). + // Allreduce will be applied within subgroups. + // For example, we have 4 replicas, then replica_groups={{0,2},{1,3}} means, + // replica 0 and 2 are in subgroup 0, replica 1 and 3 are in subgroup 1. + // + // `channel_id`: for Allreduce nodes from different modules, if + // they have the same channel_id, they will be 'Allreduce'd. If + // empty, Allreduce will not be applied cross modules. + static std::unique_ptr CreateAllReduceStart( + const Shape& shape, absl::Span operands, + HloComputation* reduce_computation, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + + // An all-to-all op takes N array operands of the same shape and scatters them + // to N replicas. Each replica gathers the results into a tuple. + // + // For example, suppose we have 3 replicas, with replica i passing inputs + // [a_i, b_i, c_i] to its all-to-all op. Then the resulting tuples are + // + // replica 0: (a_0, a_1, a_2) + // replica 1: (b_0, b_1, b_2) + // replica 2: (c_0, c_1, c_2). + // + // If replica_groups is set, the op is sharded and the replicas are permuted. + // To explain by way of example, suppose we have replica_groups={{1,2},{3,0}}. + // Then each replica passes two operands, say [a_i, b_i], and the result is + // + // replica 0: (b_3, b_0) + // replica 1: (a_1, a_2) + // replica 2: (b_1, b_2) + // replica 3: (a_3, a_0). + // + // All replica groups must have the same number of elements, and the number of + // operands must be equal to the size of one replica group. Each replica must + // appear in exactly one group. + // + // Note that in addition to supporting this instruction, XlaBuilder also + // supports a higher-level instruction which takes one input and slices it, + // performs AllToAll and then concatenates the results into a single array. + static std::unique_ptr CreateAllToAll( + const Shape& shape, absl::Span operands, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, + const std::optional& split_dimension = std::nullopt); + + // Creates a communication instruction that permutes data cross replicas. + // Data is sent/received according to the (source_replica_id, + // target_replica_id) pairs in `source_target_pairs`. If a replica id is not a + // target_replica_id in any pair, the output on that replica is a tensor + // consists of 0(s) in `shape`. + static std::unique_ptr CreateCollectivePermute( + const Shape& shape, HloInstruction* operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id); + + static std::unique_ptr CreateCollectivePermute( + const Shape& shape, HloInstruction* input, HloInstruction* output, + HloInstruction* input_start_indices, HloInstruction* output_start_indices, + absl::Span> source_target_pairs, + absl::Span> slice_sizes, + const std::optional& channel_id); + + // Creates a communication instruction that initiates the start of + // CollectivePermute. + static std::unique_ptr CreateCollectivePermuteStart( + const Shape& shape, HloInstruction* operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id); + + static std::unique_ptr CreateCollectivePermuteStart( + const Shape& shape, HloInstruction* input, HloInstruction* output, + HloInstruction* input_start_indices, HloInstruction* output_start_indices, + absl::Span> source_target_pairs, + absl::Span> slice_sizes, + const std::optional& channel_id); + + // Creates an instruction that returns a U32 replica ID. + static std::unique_ptr CreateReplicaId( + const Shape& shape = ShapeUtil::MakeShape(U32, {})); + + // Creates an instruction that returns a U32 partition ID. + static std::unique_ptr CreatePartitionId( + const Shape& shape = ShapeUtil::MakeShape(U32, {})); + + // Creates a conversion instruction, where operand is the data to convert and + // shape is the target shape for the conversion. + static std::unique_ptr CreateConvert(const Shape& shape, + HloInstruction* operand); + + // Creates a bitcast instruction, where operand is the data to + // convert and shape is the target shape for the conversion. + static std::unique_ptr CreateBitcast(const Shape& shape, + HloInstruction* operand); + + // Creates a bitcast conversion instruction, where operand is the data to + // convert and shape is the target shape for the conversion. + static std::unique_ptr CreateBitcastConvert( + const Shape& shape, HloInstruction* operand); + + // Creates a stochastic conversion instruction, where operand is the data to + // convert, random is a given random input to determine the rounding direction + // and shape is the target shape for the conversion. + static std::unique_ptr CreateStochasticConvert( + const Shape& shape, HloInstruction* operand, HloInstruction* random); + + // Creates an infeed instruction, which reads data of the given shape from the + // Infeed interface of the device. infeed_shape is the shape of the data + // received from the infeed *not* the shape of the infeed instruction which + // is a tuple containing the infeed_shape and the TOKEN. + static std::unique_ptr CreateInfeed( + const Shape& infeed_shape, HloInstruction* token_operand, + const std::string& config); + + // Creates an outfeed instruction, which outputs data. outfeed_shape is the + // shape of the data being outfed *not* the shape of the outfeed instruction + // which is a TOKEN. + static std::unique_ptr CreateOutfeed( + const Shape& outfeed_shape, HloInstruction* operand, + HloInstruction* token_operand, absl::string_view outfeed_config); + + // Creates an asynchronous send instruction with the given channel id, which + // initiates sending the operand data to a unique receive instruction in + // another computation that has the same channel id. If is_host_transfer is + // true, then this Send operation transfers data to the host. + static std::unique_ptr CreateSend( + HloInstruction* operand, HloInstruction* token, int64_t channel_id, + bool is_host_transfer = false); + + // Blocks until data transfer for the Send instruction (operand) is complete. + // The operand must be kSend. + static std::unique_ptr CreateSendDone( + HloInstruction* operand, bool is_host_transfer = false); + + // Creates an asynchronous receive instruction with the given channel id, + // which allocates resources to receive data of the given shape from a unique + // send instruction in another computation that has the same channel id. If + // is_host_transfer is true, then this Recv operation transfers data from the + // host. + static std::unique_ptr CreateRecv( + const Shape& shape, HloInstruction* token, int64_t channel_id, + bool is_host_transfer = false); + + // Blocks until data transfer for the Recv instruction (operand) is complete + // and returns the receive buffer. The operand must be kRecv. + static std::unique_ptr CreateRecvDone( + HloInstruction* operand, bool is_host_transfer = false); + + // Creates a slice instruction, where the operand is sliced by the given + // start/limit indices. + static std::unique_ptr CreateSlice( + const Shape& shape, HloInstruction* operand, + absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + + // Creates a slice instruction, where the first operand is sliced by + // start indices specified in the second operand, and by size specified in + // 'slice_sizes'. + static std::unique_ptr CreateDynamicSlice( + const Shape& shape, HloInstruction* operand, + absl::Span start_indices, + absl::Span slice_sizes); + + // Creates a dynamic update slice instruction, which updates a slice + // of 'operand' with 'update' and 'start_indices'. + static std::unique_ptr CreateDynamicUpdateSlice( + const Shape& shape, HloInstruction* operand, HloInstruction* update, + absl::Span start_indices); + + // Creates a concatenate instruction, where the operands are concatenated on + // the provided dimension. + static std::unique_ptr CreateConcatenate( + const Shape& shape, absl::Span operands, + int64_t dimension); + + // Creates a reduce instruction, where the computation (given by the handle) + // is applied successively to every element in operand. For example, let f be + // the function to apply, which takes 2 arguments, an accumulator and the + // current value. Let init be an initial value (which is normally chosen to be + // the identity element for f, e.g. 0 if f is addition). + // Then the reduce HLO will compute: + // f(f(init, value0), value1), ...) + static std::unique_ptr CreateReduce( + const Shape& shape, HloInstruction* operand, HloInstruction* init_value, + absl::Span dimensions_to_reduce, + HloComputation* reduce_computation); + + // A more general, multiple-argument version of the above. + // The function to apply, f, now takes N arguments: + // [accumulator0, accumulator1, ..., accumulatorN, value0, value1, ..., + // init_valueN], and returns an N-tuple. The performed computation is (for + // commutative and associative f operators) equivalent to: + // + // f_1 = f(init0, ... initN, input0.value0, ..., inputN.value0) + // f_2 = f(f_1.tuple_element(0), ..., f_1.tuple_element(N), input0.value1, + // ..., inputN.value1) + // ... + static std::unique_ptr CreateReduce( + const Shape& shape, absl::Span operands, + absl::Span init_values, + absl::Span dimensions_to_reduce, + HloComputation* reduce_computation); + + // Helper version where the operands are given by a single instruction which + // either is a tuple of size `init_values`, or a single input, in which case + // size of `init_values` is one. + static std::unique_ptr CreateReduce( + const Shape& shape, HloInstruction* tuple_of_instructions, + absl::Span init_values, + absl::Span dimensions_to_reduce, + HloComputation* reduce_computation); + + // Creates a reduce-window instruction, where the computation (given + // by the handle) is applied window-wise at each valid window + // position in the operand. + static std::unique_ptr CreateReduceWindow( + const Shape& shape, HloInstruction* operand, HloInstruction* init_value, + const Window& window, HloComputation* reduce_computation); + + // A more general, multiple-argument version of the above. + // The reduce_computation being applied,now takes N arguments: + // [accumulator0, accumulator1, ..., accumulatorN, value0, value1, ..., + // valueN], and returns an N-tuple. The operands and init_values now each + // contain a span of N input arrays and n initial values. + static std::unique_ptr CreateReduceWindow( + const Shape& shape, absl::Span operands, + absl::Span init_values, const Window& window, + HloComputation* reduce_computation); + + // Creates a batch-norm-training instruction. + static std::unique_ptr CreateBatchNormTraining( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* offset, float epsilon, int64_t feature_index); + + // Creates a batch-norm-inference instruction. + static std::unique_ptr CreateBatchNormInference( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* offset, HloInstruction* mean, HloInstruction* variance, + float epsilon, int64_t feature_index); + + // Creates a batch-norm-grad instruction. + static std::unique_ptr CreateBatchNormGrad( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* mean, HloInstruction* variance, + HloInstruction* grad_output, float epsilon, int64_t feature_index); + + // Creates a scatter computation that scatters the `source` array to the + // selected indices of each window. + static std::unique_ptr CreateSelectAndScatter( + const Shape& shape, HloInstruction* operand, HloComputation* select, + const Window& window, HloInstruction* source, HloInstruction* init_value, + HloComputation* scatter); + + // Creates a broadcast instruction. + static std::unique_ptr CreateBroadcast( + const Shape& shape, HloInstruction* operand, + absl::Span broadcast_dimensions); + + // Creates a sequence of instructions that performs an explicit broadcast of + // the operand to the target shape. + // + // Interior HLOs are passed to "adder", but the "root" HLO of the sequence is + // returned as a unique_ptr for API consistency with other factory methods in + // this interface. + // + // TODO(b/72173833) Ideally HloComputations would always be present, and so + // the adder being passed by the caller would not be necessary. + static std::unique_ptr CreateBroadcastSequence( + const Shape& output_shape, HloInstruction* operand, + absl::FunctionRef)> + adder); + + // Creates a pad instruction, where the operand is padded on the edges and + // between the elements with the given padding value. + static std::unique_ptr CreatePad( + const Shape& shape, HloInstruction* operand, + HloInstruction* padding_value, const PaddingConfig& padding_config); + + // Creates a reshape instruction, where the operand is flattened row-major + // order and then reshaped to the given result shape. + static std::unique_ptr CreateReshape( + const Shape& shape, HloInstruction* operand, + int64_t inferred_dimension = -1); + + // Creates a dynamic reshape instruction. Similar to reshape but dynamic + // dimensions sizes are provided as additional variadic arguments. + // + // Precondition: dim_sizes.size() == shape.rank() + static std::unique_ptr CreateDynamicReshape( + const Shape& shape, HloInstruction* data_operand, + absl::Span dim_sizes); + + // Creates a transpose instruction which permutes the operand dimensions. + static std::unique_ptr CreateTranspose( + const Shape& shape, HloInstruction* operand, + absl::Span dimensions); + + // Creates a n-ary sort op with a 'compare' computation which is used for + // comparisons in the sorting algorithm. 'compare' gets 2 * n parameters, + // where parameters 2 * i and 2 * i + 1 are the values of the i-th operand at + // specific index positions which should be compared, and should return a + // PRED. 'is_stable' specifies whether stable sorting is required. + static std::unique_ptr CreateSort( + const Shape& shape, int64_t dimension, + absl::Span operands, HloComputation* compare, + bool is_stable); + + // Creates a while instruction, given a condition computation, a body + // computation, and the initial value for the input of the computations. For + // example, shape: S32, condition: i -> i < 1000, body: i -> i * 2, init: 1 + // corresponds to the C code below. + // int32_t i = 1; int32_t result = while(i < 1000) { i = i * 2 } + static std::unique_ptr CreateWhile(const Shape& shape, + HloComputation* condition, + HloComputation* body, + HloInstruction* init); + + static std::unique_ptr CreateConditional( + const Shape& shape, HloInstruction* pred, + HloInstruction* true_computation_arg, HloComputation* true_computation, + HloInstruction* false_computation_arg, HloComputation* false_computation); + + static std::unique_ptr CreateConditional( + const Shape& shape, HloInstruction* branch_index, + absl::Span branch_computations, + absl::Span branch_computation_args); + + static std::unique_ptr CreateGather( + const Shape& shape, HloInstruction* operand, + HloInstruction* start_indices, + const GatherDimensionNumbers& gather_dim_numbers, + absl::Span slice_sizes, bool indices_are_sorted); + + static std::unique_ptr CreateScatter( + const Shape& shape, absl::Span operands, + HloInstruction* scatter_indices, + absl::Span updates, + HloComputation* update_computation, + const ScatterDimensionNumbers& scatter_dim_numbers, + bool indices_are_sorted, bool unique_indices); + + static std::unique_ptr CreateScatter( + const Shape& shape, HloInstruction* operand, + HloInstruction* scatter_indices, HloInstruction* updates, + HloComputation* update_computation, + const ScatterDimensionNumbers& scatter_dim_numbers, + bool indices_are_sorted, bool unique_indices); + + // Creates a kDomain instruction which delimits an HLO domain which have + // the provided user and operand side metadata. + static std::unique_ptr CreateDomain( + const Shape& shape, HloInstruction* operand, + std::unique_ptr operand_side_metadata, + std::unique_ptr user_side_metadata); + + // Creates a fusion instruction. A fusion instruction contains one or more + // fused instructions forming an expression with a single root + // "fused_root". Additional instructions can be added to the fusion + // instruction with the method FuseInstruction. + static std::unique_ptr CreateFusion( + const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root); + + static std::unique_ptr CreateFusion( + const Shape& shape, FusionKind fusion_kind, + absl::Span operands, + HloComputation* fusion_computation, absl::string_view prefix = ""); + + // Creates a call instruction that applies the given computation on the given + // operands. "shape" is the resultant shape. + static std::unique_ptr CreateCall( + const Shape& shape, HloInstruction* called_computation_root); + + static std::unique_ptr CreateCall( + const Shape& shape, absl::Span operands, + HloComputation* computation); + + // Creates a custom call instruction that applies the given custom call target + // to the given operands. "opaque" can be an arbitrary string with a + // backend-specific interpretation. "shape" is the resultant shape. + static std::unique_ptr CreateCustomCall( + const Shape& shape, absl::Span operands, + absl::string_view custom_call_target, std::string opaque = "", + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + + // Overload with a to_apply computation. + static std::unique_ptr CreateCustomCall( + const Shape& shape, absl::Span operands, + HloComputation* to_apply, absl::string_view custom_call_target, + std::string opaque = "", + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + + // Overload with multiple computations. The called computations can have + // different function signatures. + static std::unique_ptr CreateCustomCall( + const Shape& shape, absl::Span operands, + absl::Span called_computations, + absl::string_view custom_call_target, std::string opaque = "", + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + + // Overload which constrains the layouts of the operand and result. 'shape' + // and 'operand_shapes_with_layout' must have layouts. + // 'operand_shapes_with_layout' must have a compatible element for each + // operand. + static std::unique_ptr CreateCustomCall( + const Shape& shape, absl::Span operands, + absl::string_view custom_call_target, + absl::Span operand_shapes_with_layout, + std::string opaque = "", + CustomCallApiVersion api_version = API_VERSION_ORIGINAL); + + // Creates a tuple instruction with the given elements. This is a convenience + // wrapper around CreateVariadic. + static std::unique_ptr CreateTuple( + absl::Span elements); + + // Creates a reverse instruction, which reverses the order of the elements + // in the specified dimensions. + static std::unique_ptr CreateReverse( + const Shape& shape, HloInstruction* operand, + absl::Span dimensions); + + // Creates a Afterall instruction used for joining or creating new values of + // token type which thread through side-effecting operations. Operands must + // all be tokens, and there must be at least one operand. + static std::unique_ptr CreateAfterAll( + absl::Span operands); + + // Creates an AfterAll instruction which creates a token type out of thin air + // (no operands). This is a separate method from CreateAfterAll to facility + // the removal of operand-less AfterAll instructions. + // TODO(b/110532604): Remove this capability of creating a token from nothing + // when we plumb a primordial token from the entry computation. + static std::unique_ptr CreateToken(); + + static std::unique_ptr CreateGetDimensionSize( + const Shape& shape, HloInstruction* operand, int64_t dimension); + + static std::unique_ptr CreateSetDimensionSize( + const Shape& shape, HloInstruction* operand, HloInstruction* val, + int64_t dimension); + + static std::unique_ptr CreateAddDependency( + HloInstruction* data_operand, HloInstruction* token_operand); + + // Returns true if `execution_thread` is included in the + // `execution_threads_set`. + static bool IsThreadIncluded( + absl::string_view execution_thread, + const absl::flat_hash_set& execution_threads_set); + + // Returns the opcode for this instruction. + HloOpcode opcode() const { return opcode_; } + HloOpcode* mutable_opcode() { return &opcode_; } + + // Returns whether this instruction is the root of its parent computation. + bool IsRoot() const; + + // Does this instruction have no users. + bool IsDead() const { return users_.empty() && !IsRoot(); } + + // Returns true if this instruction has a side effect, irrespective of whether + // any called computations may contain an instruction with side effects. + bool HasSideEffectNoRecurse() const; + + // Returns true if this instruction has a side effect. An instruction has a + // side effect if it uses certain opcodes or calls a computation with a side + // effect. + bool HasSideEffect() const; + + // Returns the result shape of this instruction. + const Shape& shape() const; + + // Returns the (mutable) result shape of this instruction. + Shape* mutable_shape() { return &shape_; } + + // Returns the ith operand to this instruction. + const HloInstruction* operand(int64_t i) const; + + // Returns the ith operand to this instruction. + HloInstruction* mutable_operand(int64_t i); + + // Returns the number of operands to this instruction. + int64_t operand_count() const { return operands_.size(); } + + // Returns the vector of operands of this instruction. + using InstructionVector = absl::InlinedVector; + const InstructionVector& operands() const { return operands_; } + InstructionVector mutable_operands() { return operands_; } + + // Returns the vector of unique operands, in the same order they are found + // within the operand vector. + InstructionVector unique_operands() const; + + // Returns the index of 'target' in the operands sequence. + // Precondition: target must be an operand (or a fatal error will occur). + int64_t operand_index(const HloInstruction* target) const; + + // Returns the number of users of this instruction. + int64_t user_count() const { return users_.size(); } + + // Returns the users of this instruction. + const std::vector& users() const { return users_; } + + // Returns the index of the user in the users() vector. + // + // Precondition: `user` is a user of the instruction. + int64_t UserId(HloInstruction* user); + + // Returns true if this instruction is a user of 'instruction'. + bool IsUserOf(const HloInstruction* instruction) const { + return instruction->user_map_.contains(this); + } + + // Adds a control dependency from this instruction to the given + // instruction. This instruction becomes a control predecessor of + // 'instruction', and 'instruction' becomes a control successor of this + // instruction. Returns an error status if either of the given instructions + // does not belong to the same computation. + // + // This is used to enforce an additional ordering requirement that is not + // captured by normal data dependencies, such as ordering among Send or Recv + // operations to avoid deadlock. + Status AddControlDependencyTo(HloInstruction* instruction); + + // Removes a previously added control dependency from this instruction to + // 'instruction'. + Status RemoveControlDependencyTo(HloInstruction* instruction); + + // Drops all control predecessors and successors from this HLO instruction. + Status DropAllControlDeps(); + + // Drops all control predecessors and successors from this HLO instruction, + // and the maintain the transitivie control dependencies between + // control predecessors and control successors. + Status SafelyDropAllControlDependencies(); + + // Returns if instruction has any control dependencies. + bool HasControlDependencies() const; + + // Copies the control predecessors and successors on this HLO instruction to + // `inst`. Does not do a deep copy so this makes sense only if `inst` and + // this HLO are in the same module. + // + // Depending on the use cases we see in practice, in the future we may + // consider folding the logic here into Clone, CloneWithNewOperands and + // ReplaceAllUsesWith by treating control dependencies like data dependencies. + Status CopyAllControlDepsFrom(const HloInstruction* inst); + + // Returns the set of control predecessors (successors) of this + // instruction. Control predecessors (successors) must execute before (after) + // the current instruction. + const std::vector& control_predecessors() const { + return control_predecessors_; + } + const std::vector& control_successors() const { + return control_successors_; + } + + // Returns true if 'other' performs the same computation as this instruction. + bool Identical( + const HloInstruction& other, + absl::FunctionRef + eq_operands = std::equal_to(), + absl::FunctionRef + eq_computations = std::equal_to(), + bool layout_sensitive = true, bool sharding_sensitive = false) const { + return IdenticalInternal(other, eq_operands, eq_computations, + layout_sensitive, sharding_sensitive, + /*ignore_channel_id_values=*/false, + /*ignore_commutative_operand_order=*/false); + } + // Returns true if 'other' is the same kind of op as this instruction. For + // regular ops, it just checks whether the opcode is the same, for ops like + // e.g. kCompare, it also checks extra attributes. + bool SameOp(const HloInstruction& other) const { + return opcode() == other.opcode() && + IdenticalSlowPath(other, std::equal_to()); + } + + // Same as Identical() but ignores the order of commutative operands (e.g. + // considers add(a,b) equal to add(b,a)). + bool IdenticalIgnoringCommutativeOperandOrder( + const HloInstruction& other, + absl::FunctionRef + eq_operands = std::equal_to(), + absl::FunctionRef + eq_computations = std::equal_to(), + bool layout_sensitive = true, bool sharding_sensitive = false) const { + return IdenticalInternal(other, eq_operands, eq_computations, + layout_sensitive, sharding_sensitive, + /*ignore_channel_id_values=*/false, + /*ignore_commutative_operand_order=*/true); + } + + // Same as Identical() but ignores channel ID value mismatches, as long as + // both have channel IDs or neither has a channel ID. + bool IdenticalIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_operands = std::equal_to(), + absl::FunctionRef + eq_computations = std::equal_to(), + bool layout_sensitive = true, bool sharding_sensitive = false) const { + return IdenticalInternal(other, eq_operands, eq_computations, + layout_sensitive, sharding_sensitive, + /*ignore_channel_id_values=*/true, + /*ignore_commutative_operand_order=*/true); + } + + // Generates a hash value of an HLO instruction. Hash considers + // information on opcode, shape, operands, and typically a root instruction. + // This function returns the same hash value for equivalent HLO instructions, + // with respect to HloInstruction::Identical() method. + // TODO(majnemer): Make the comment here more crisp & accurate. + template + friend H AbslHashValue(H h, const HloInstruction& hlo) { + h = H::combine(std::move(h), hlo.opcode(), hlo.shape()); + + if (!hlo.IsCrossModuleAllReduce()) { + for (size_t i = 0; i < hlo.operands().size(); ++i) { + h = H::combine(std::move(h), hlo.operand(i)->shape()); + } + h = H::combine(std::move(h), hlo.operand_count()); + } + + if (hlo.opcode() == HloOpcode::kFusion) { + h = H::combine(std::move(h), *hlo.fused_expression_root(), + hlo.fusion_kind(), hlo.fused_instruction_count(), + hlo.fused_parameters().size()); + } + return h; + } + + // Returns whether the instruction has a constant operand. + bool HasConstantOperand() const; + + // Replaces the use of this instruction in "user" with "new_producer". Note + // that there might be multiple uses of this instruction in "user"; all will + // be replaced. + // + // If user is a fusion instruction, this function will remove any duplicated + // operands of it which could be created due to this replacement. + Status ReplaceUseWith(HloInstruction* user, HloInstruction* new_producer); + + // Same as ReplaceUseWith(), but new_producer can have a different shape. + Status ReplaceUseWithDifferentShape(HloInstruction* user, + HloInstruction* new_producer); + + // Same as ReplaceUseWith but only replaces the use at the given operand + // number. + Status ReplaceUseWith(HloInstruction* user, int operand_number, + HloInstruction* new_producer); + Status ReplaceUseWithDifferentShape(HloInstruction* user, int operand_number, + HloInstruction* new_producer); + + // Replaces the specified operand with new_operand. The old and new operands + // must have compatible shapes ignoring floating-point precision. + // + // This function does NOT remove duplicated operands even if this instruction + // is a fusion, so that the existing operand numbers do not change. + Status ReplaceOperandWith(int64_t operand_num, HloInstruction* new_operand); + + // Same as ReplaceOperandWith(), but new_operand can have a different shape. + Status ReplaceOperandWithDifferentShape(int64_t operand_num, + HloInstruction* new_operand); + + // Replaces all uses of this instruction with the new producer. If + // new_producer is a user of this instruction then new_producer remains a use + // of this instruction to avoid introducing cycles into the graph. + // + // If this instruction is the root of its computation, sets the computation's + // root to new_producer. + // + // The new producer must have a compatible shape ignoring floating-point + // precision. + // + // If a user is a fusion instruction, this function will remove any duplicated + // operands of it which could be created due to this replacement. + // + // trigger is a string used in the error message if the new and the + // current instruction don't have a compatible shape. + Status ReplaceAllUsesWith(HloInstruction* new_producer, + absl::string_view trigger = ""); + + // Same as ReplaceAllUsesWith, but new_producer can have a different shape. + Status ReplaceAllUsesWithDifferentShape(HloInstruction* new_producer); + + // Same as ReplaceAllUsesWith, but only replace given set of users. + Status ReplaceUsesWith(absl::Span users, + HloInstruction* new_producer); + Status ReplaceAllUsesWithDifferentShape( + absl::Span users, HloInstruction* new_producer); + + // Performs a postorder DFS visit using this node as the root. If + // call_finish_visit is true, then DfsHloVisitor::FinishVisit is called when + // complete. If ignore_control_predecessors is true, instructions only + // reachable via control dependencies will not be visited, and the postorder + // will not take control dependencies into account. It is as if the control + // dependencies didn't exist in the graph at all. If cross_computation is + // true, DFS will go across the computation boundary (i.e., from an + // instruction to the root instruction of a computation it calls). + template + Status Accept(DfsHloVisitorBase* visitor, + bool call_finish_visit = true, + bool ignore_control_predecessors = false, + bool cross_computation = false); + Status Accept(ConstDfsHloVisitor* visitor, bool call_finish_visit = true, + bool ignore_control_predecessors = false, + bool cross_computation = false) const { + return const_cast(this)->Accept( + visitor, call_finish_visit, ignore_control_predecessors, + cross_computation); + } + + // Same as Accept() above, but the order of operand and control predecessor + // visitation is determined by the given operand order; if compare(A, B) == + // true, A is visited before B. + using CompareFunction = + absl::FunctionRef; + Status AcceptWithOperandOrder(DfsHloVisitor* visitor, + CompareFunction operand_order, + bool call_finish_visit = true); + + // Visit this instruction and only this instruction with the given visitor. + template + Status Visit(DfsHloVisitorBase* visitor); + Status Visit(ConstDfsHloVisitor* visitor) const { + return const_cast(this)->Visit(visitor); + } + + // Returns the first non-GetTupleElement ancestor instruction of 'hlo'. + // If the first non-GTE ancestor is tuple-shaped, populates 'index' with the + // (possibly nested) tuple indices used on the path from ancestor to 'hlo'. + std::pair LatestNonGteAncestorAndIndex() + const; + + std::pair LatestNonGteAncestorAndIndex() { + auto rv = + const_cast(this)->LatestNonGteAncestorAndIndex(); + return {const_cast(rv.first), rv.second}; + } + + // Same as LatestNonGteAncestorAndIndex, but just returns the HloInstruction. + const HloInstruction* LatestNonGteAncestor() const; + + HloInstruction* LatestNonGteAncestor() { + return const_cast( + const_cast(this)->LatestNonGteAncestor()); + } + + // Returns true whether this instruction is effectively a bitcast. Currently, + // this means it either is a bitcast, or it is a transpose that is effectively + // a bitcast. + bool IsEffectiveBitcast() const; + + // Gets/sets the to_apply HloComputation for Call, Map, Reduce, etc. + // The setter should only be called by HloModule or HloComputation methods. + // + // Precondition: The instruction has a valid to_apply_ field. + HloComputation* to_apply() const; + void set_to_apply(HloComputation* computation); + // Whether the instruction has a valid to_apply_ field. + bool has_to_apply() const; + + // Gets/sets the while_condition or while_body HloComputation for While. The + // setters should only be called by HloModule or HloComputation methods. + // + // Precondition: The instruction is a While instruction. + HloComputation* while_condition() const; + HloComputation* while_body() const; + void set_while_condition(HloComputation* computation); + void set_while_body(HloComputation* computation); + + HloInstruction* while_init() const; + + // Gets/sets the true and false HloComputation for Conditional. + // + // Precondition: The instruction is a predicated Conditional instruction. + HloComputation* true_computation() const; + HloComputation* false_computation() const; + + // Gets the branch HloComputations for Conditional. + // + // Precondition: The instruction is a Conditional instruction. + const std::vector& branch_computations() const; + int branch_count() const; + HloComputation* branch_computation(int b) const; + // Sets a branch HloComputation for Conditional. + // The setter should only be called by HloModule or HloComputation methods. + // + // Precondition: The instruction is a Conditional instruction. + void set_branch_computation(int b, HloComputation* computation); + + // Returns a string for the signature of this instruction if considered as a + // function, e.g. the signature of an F32 add is (F32, F32) -> F32. + std::string SignatureString() const; + + // Prints a debugging string that represents this instruction. + void Print(Printer* printer) const { + return Print(printer, HloPrintOptions::Default()); + } + void Print(Printer* printer, const HloPrintOptions& options) const; + + // Returns a debugging string that represents this instruction. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + // + // TODO(b/73348663): Make ToString() adaptive to the size of the string by + // default, backing off on providing full information for very large strings, + // or provide a different name for a ToString-like function that does that. + std::string ToString() const; + std::string ToString(const HloPrintOptions& options) const; + + // Components of the Print() and ToString() representation: + + // Helper class for PrintExtraAttributes. + class AttributePrinter { + public: + explicit AttributePrinter(std::function next_printer) + : next_printer_(std::move(next_printer)) {} + + void Next(absl::FunctionRef print_func) { + print_func(next_printer_()); + } + + private: + std::function next_printer_; + }; + // Prints the string representation of op-specific attributes. + void PrintExtraAttributes(AttributePrinter& printer, + const HloPrintOptions& options) const; + + // Returns string representation of op-specific attributes. + std::vector ExtraAttributesToString( + const HloPrintOptions& options) const; + + // As ToString, but returns a shorter string. + std::string ToShortString() const; + + // Prints an instruction to a string. + // + // The canonical string representation needs to name operands and instruction + // names in a consistent way. This is implemented through the + // canonical_name_map. + void PrintWithCanonicalNameMap(Printer* printer, + const HloPrintOptions& options, + CanonicalNameMap* canonical_name_map) const; + + // Returns a serialized representation of this instruction. + virtual HloInstructionProto ToProto() const; + + // Returns a category for the HLO. This could be something like "convolution" + // or "elementwise". + virtual std::string ToCategory() const; + + // Returns true if this instruction is fused, ie contained within a fusion + // instruction. + bool IsFused() const; + + bool IsLoopFusion() const; + bool IsInputFusion() const; + bool IsOutputFusion() const; + bool IsCustomFusion() const; + + // Returns true if this instruction can be legally fused into a fusion + // instruction. + bool IsFusible() const; + + bool IsCustomCall(absl::string_view target) const; + bool IsCustomCall(absl::Span targets) const; + + // Returns the sharding applied to this operator. + // REQUIRES: has_sharding() is true. + const HloSharding& sharding() const { + CHECK(has_sharding()); + return *sharding_; + } + std::shared_ptr sharding_ptr() const { return sharding_; } + + // Returns the sharding applied to this operator, or default_ if none exists. + const HloSharding& sharding_or_default(const HloSharding& default_) const { + return sharding_ ? *sharding_ : default_; + } + // Returns the sharding unique device, if any. + std::optional sharding_unique_device() const { + if (sharding_ == nullptr) { + return std::nullopt; + } + return sharding_->UniqueDevice(); + } + // Sets the sharding of this operator. Should only be called by HloModule or + // HloComputation methods. + void set_sharding(const HloSharding& sharding) { + set_sharding(std::make_shared(sharding)); + } + void set_sharding(std::shared_ptr sharding) { + sharding_ = std::move(sharding); + } + // Copies the sharding of another instruction, this is more efficient than + // set_sharding(hlo->sharding()) because it avoids a deep copy and shares the + // storage. Note that if the other instruction has no sharding set, it also + // clears the sharding of the current instruction. + void copy_sharding(const HloInstruction* hlo) { + set_sharding(hlo->sharding_ptr()); + } + void set_single_sharding(const HloSharding& sharding); + // Sets a sharding that assigns the current instruction to device. + void set_device_sharding(int64_t device) { + set_single_sharding(HloSharding::AssignDevice(device)); + } + // Remove any sharding from this operator. + void clear_sharding() { sharding_ = nullptr; } + // Return true if this operator has a sharding assigned. + bool has_sharding() const { return sharding_ != nullptr; } + // Checks whether the instruction has compatible sharding with the other + // instruction. + bool has_compatible_sharding(const HloInstruction* other) const { + if (!has_sharding()) { + return !other->has_sharding(); + } + return other->has_sharding() ? sharding() == other->sharding() : false; + } + + // When creating a new instruction which either replaces, or shifts up (kCopy + // insertion case), another instruction, we need to make sure the certain + // properties of the new instruction are copied into the derived one. As of + // today, the metadata and sharding will be propagated to the derived + // instruction. + void SetupDerivedInstruction(HloInstruction* derived_instruction) const; + + // Clones the HLO instruction. The clone will have the same opcode, shape, and + // operands. After creation the clone has no uses. "this" (the instruction + // cloned from) is not changed. Suffix is the string to append to the name of + // the instruction to form the name of the cloned instruction. + // Ignores the control predecessors and successors of this HLO instruction. + std::unique_ptr Clone( + const std::string& suffix = "clone", + HloCloneContext* context = nullptr) const; + + // Clones the HLO instruction as above but with new shape. + std::unique_ptr CloneWithNewShape( + const Shape& shape, const std::string& suffix = "clone", + HloCloneContext* context = nullptr) const; + + // Clones the HLO instruction as above but with new shape and operands. + std::unique_ptr CloneWithNewOperands( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context = nullptr) const; + + // Returns the computations this instruction directly calls (if any). + const std::vector& called_computations() const { + return called_computations_; + } + + // Replaces all called computations based on a map function. This is needed + // when we clone hlo_computations and want to let the instructions to point + // to the newly cloned nodes. + void ReplaceCalledComputations( + absl::FunctionRef map_function) { + for (int64_t i = 0; i < called_computations_.size(); ++i) { + called_computations_[i] = map_function(called_computations_[i]); + } + } + + // Clears out the called computations. + // + // This is, in particular, necessary when inlining function bodies into their + // caller. If there were side-effecting operations in the called computations, + // the call itself is considered side-effecting and thus cannot be removed. By + // clearing out the computations, we reflect the fact that all side-effecting + // properties have been reflected in the caller, and make the call HLO + // removable. + virtual void ClearCalledComputations() { called_computations_.clear(); } + + // Returns true if this instruction performs an elementwise operation on + // `operand_idx`-th operand. An instruction is elementwise on an operand iff, + // to compute the output at index {i_0,i_1,...,i_n}, the only element required + // from the operand (if any) is the element at {i_0,i_1,...,i_n}. + // + // Note on performance: when this instruction is kFusion, this method, in the + // worst case, scans all fused instructions. We could speed this up by + // caching. + bool IsElementwiseOnOperand(int64_t operand_idx) const; + + // Returns true if this instruction is elementwise on all its operands. + bool IsElementwise() const; + + static bool IsOpElementwise(HloOpcode opcode); + + // Returns true if this is a cross module all-reduce instruction. + bool IsCrossModuleAllReduce() const; + + // Returns true if this is a cross-replica all-reduce instruction. + bool IsCrossReplicaAllReduce() const; + + // Returns true if this instruction is binary and elementwise. + bool IsElementwiseBinary() const; + + // Returns whether this instruction may reuse elements of its `i`th operand. + bool ReusesOperandElements(int64_t i) const; + + // Returns the indices that the given operand appear in the operand list of + // this instruction. Note that an instruction can use the same operand + // multiple times. + absl::InlinedVector OperandIndices( + const HloInstruction* operand) const; + + // Convenience helper for ShapeUtil::InsertedOrDeleted1SizedDimensions. If + // this reshape merely inserts or deletes 1-sized dimensions, return the input + // indices of the deleted dimensions and the output indices of the inserted + // dimensions. + // + // Precondition: this op must be a reshape. + std::optional + ReshapeMerelyInsertsOrDeletes1SizedDimensions() const; + + // Gets the string identifier for this instruction. + absl::string_view name() const { return name_; } + + // Sets the string identifier for this instruction. Name will be sanitized to + // match the regexp "[a-zA-Z_][a-zA-Z0-9_.-]*". + // + // See also HloModule::SetAndUniquifyInstrName(), which does this plus + // UniqufyName(). + void SetAndSanitizeName(absl::string_view name) { + name_ = NameUniquer::GetSanitizedName(name); + } + + // Use the given NameUniquer to select a unique name for the instruction based + // on the instruction's existing name. + // + // See also HloModule::SetAndUniquifyInstrName(), which does this plus + // SetAndSanitizeName(). + void UniquifyName(NameUniquer* name_uniquer); + + // Clear the unique ID of the instruction so that it can be re-assigned, such + // as for the purpose of compacting the instruction unique IDs. + void ClearUniqueIdInternal() { unique_id_ = -1; } + + // Set the unique id for this instruction to "id" + void SetUniqueId(int id) { + CHECK_EQ(unique_id_, -1); // Should not be assigned already + CHECK_GE(id, 0); + unique_id_ = id; + } + + // Return the unique ID assigned to this node via SetUniqueId (or -1 + // if no id has been assigned yet). + int unique_id() const { return unique_id_; } + + template + using EnableIfProto = typename std::enable_if_t< + std::is_base_of::value>; + + // Returns the backend-specific configuration for how a backend should compile + // this HLO. The meaning of the field is backend specific. Not for use before + // or during general HLO optimization, since HLO optimizations do not preserve + // this field and they cannot interpret it due to its meaning being backend + // specific. Except for CustomCall, where this field is preserved and no + // general HLO optimization needs to interpret it. + // + // ConfigProto should be a protobuf Message type. + template * = nullptr> + StatusOr backend_config() const { + ConfigProto proto; + TF_RETURN_IF_ERROR(GetBackendConfigInternal(&proto)); + return std::move(proto); + } + + Status set_backend_config(const tsl::protobuf::Message& proto) { + backend_config_ = proto; + return OkStatus(); + } + + bool preserve_layout() const { return metadata_.preserve_layout(); } + + bool has_backend_config() const { return !backend_config_.empty(); } + + void clear_backend_config() { backend_config_.clear(); } + + void CopyBackendConfigFrom(const HloInstruction* other) { + backend_config_ = other->backend_config_.Clone(); + } + + void set_frontend_attributes(FrontendAttributes frontend_attributes) { + frontend_attributes_ = std::move(frontend_attributes); + } + + void add_frontend_attributes(FrontendAttributes frontend_attributes) { + frontend_attributes_.mutable_map()->insert( + frontend_attributes.map().begin(), frontend_attributes.map().end()); + } + + const FrontendAttributes& frontend_attributes() const { + return frontend_attributes_; + } + + void add_single_statistic(Statistic statistic) { + *statistics_viz_.add_statistics() = std::move(statistic); + } + + void set_stat_index_to_visualize(int64_t index) { + statistics_viz_.set_stat_index_to_visualize(index); + } + + // Whether this specific instruction has statistics + bool has_statistics() const { return !statistics_viz_.statistics().empty(); } + + // Whether any instruction within the same HLO module as this has statistics + bool module_has_statistics() const { + return statistics_viz_.stat_index_to_visualize() == -1; + } + + const Statistic& statistic_to_visualize() const { + return statistics_viz_.statistics().at( + statistics_viz_.stat_index_to_visualize()); + } + + void set_statistics_viz(StatisticsViz statistics_viz) { + statistics_viz_ = std::move(statistics_viz); + } + + const StatisticsViz& statistics_viz() const { return statistics_viz_; } + + // Getter/setter for raw JSON-encoded backend config. Prefer the + // functions above that deal in proto Messages where possible. + const std::string& raw_backend_config_string() const { + return backend_config_.GetRawString(); + } + void set_raw_backend_config_string(std::string config_str) { + backend_config_ = std::move(config_str); + } + + bool is_default_config() const { return is_default_config_; } + void set_default_config() { is_default_config_ = true; } + + // Returns a string representation of a proto in the format used by + // raw_backend_config_string. + // + // This is morally equivalent to: + // + // HloInstruction instr; + // TF_RETURN_IF_ERROR(instr.set_backend_config(proto)); + // return instr.raw_backend_config_string(); + // + static StatusOr BackendConfigToRawString( + const tsl::protobuf::Message& proto); + + // Returns the information used to tell the implementation information about + // what sort of precision is requested. The meaning of the field is backend + // specific. At the moment, it is only supported for kConvolution and kDot. + // Transformations on one kDot or kConvolution to another will preserve this + // information. Transformations to other HLOs will not preserve this + // information but it is presumed that the alternate lowering is strictly + // superior. + // Precondition: opcode must be kConvolution or kDot. + const PrecisionConfig& precision_config() const; + PrecisionConfig* mutable_precision_config(); + + // Sets the debug metadata for this instruction, excluding creation_pass_id, + // which should never be copied anywhere. + void set_metadata(const OpMetadata& metadata) { + int64_t creation_pass_id = metadata_.creation_pass_id(); + metadata_ = metadata; + metadata_.set_creation_pass_id(creation_pass_id); + } + + void set_size_of_generated_code_in_bytes(int64_t code_size_in_bytes) { + metadata_.set_size_of_generated_code_in_bytes(code_size_in_bytes); + } + void set_size_of_memory_working_set_in_bytes( + int64_t working_set_size_in_bytes) { + metadata_.set_size_of_memory_working_set_in_bytes( + working_set_size_in_bytes); + } + void set_creation_pass_id(int64_t pass_id) { + metadata_.set_creation_pass_id(pass_id); + } + void set_metadata_op_name(const std::string& name) { + metadata_.set_op_name(name); + } + void set_logical_creation_pass_id(int64_t pass_id) { + metadata_.set_logical_creation_pass_id(pass_id); + } + void set_metadata_deduplicated_name(std::string deduplicated_name) { + metadata_.set_deduplicated_name(std::move(deduplicated_name)); + } + void set_metadata_preserve_layout(bool preserve_layout) { + metadata_.set_preserve_layout(preserve_layout); + } + const OpMetadata& metadata() const { return metadata_; } + + // Set/get the computation containing this instruction. set_parent should only + // be called by HloComputation methods which add/remove instructions to + // computations. + void set_parent(HloComputation* computation) { parent_ = computation; } + const HloComputation* parent() const { return parent_; } + HloComputation* parent() { return parent_; } + + // Returns the module for this instruction. + HloModule* GetModule() const; + + // A method that sorts users_, control_predecessors_, and control_successors_ + // according to the orders used in sorted_instruction. The sorting is used + // during cloning, to make clone behavior match uncloned behavior. + void SortInstructionUsersAndControlLists( + const MappedPtrContainerSorter::MapPtrFn& map_fn, + const HloInstruction& sorted_instruction); + + // Old methods kept for smooth subclassing transition BEGIN. + // NOTE: Refrain from adding more delegates, prefer down casting to subclasses + // rather than using these methods. + // TODO(b/80131774): Remove this code. + + // Delegates to HloBatchNormInstruction::feature_index. + int64_t feature_index() const; + + // Delegates to HloBatchNormInstruction::epsilon. + float epsilon() const; + + // Delegates to HloFftInstruction::fft_type. + FftType fft_type() const; + + // Delegates to HloFftInstruction::fft_length. + const std::vector& fft_length() const; + + // Delegates to HloChannelInstruction::channel_id. + std::optional channel_id() const; + void set_channel_id(const std::optional& channel_id); + + // Returns the dimension sizes or numbers associated with this instruction. + virtual absl::Span dimensions() const { + LOG(FATAL) << "Unimplemented method."; + } + + int64_t dimensions(int64_t index) const { return dimensions()[index]; } + + virtual std::vector* mutable_dimensions() { + LOG(FATAL) << "Unimplemented method."; + } + + // Delegates to HloConcatenateInstruction::concatenate_dimension. + virtual int64_t concatenate_dimension() const; + + // Delegates to HloGetDimensionSizeInstruction::dimension. + int64_t dimension() const; + + // Delegates to HloReshapeInstruction::inferred_dimension. + int64_t inferred_dimension() const; + + // Returns whether this instruction does a rank-2 transposition. + bool IsRank2Transpose() const; + + // Delegates to HloSliceInstruction::slice_start. + int64_t slice_starts(int64_t dimension) const; + const std::vector& slice_starts() const; + std::vector* mutable_slice_starts(); + + // Delegates to HloSliceInstruction::slice_limits. + int64_t slice_limits(int64_t dimension) const; + const std::vector& slice_limits() const; + std::vector* mutable_slice_limits(); + + // Delegates to HloSliceInstruction::slice_strides. + int64_t slice_strides(int64_t dimension) const; + const std::vector& slice_strides() const; + std::vector* mutable_slice_strides(); + + // Returns the literal associated with this instruction. + const Literal& literal() const; + + // Returns whether the instruction is a constant. + bool IsConstant() const; + + // Delegate to HloConstantInstruction::RelayoutConstant. + void RelayoutConstant(const Layout& new_layout, + const ShapeIndex& shape_index = {}); + + // Delegates to + // HloCallableInstruction::AppendInstructionIntoCalledComputation. + HloInstruction* AppendInstructionIntoCalledComputation( + HloInstruction* instruction_to_append, bool add_output = false); + + // Delegates to HloFusionInstruction::AddFusionOperand. + HloInstruction* AddFusionOperand(HloInstruction* new_operand); + + // Delegates to HloFusionInstruction::MergeFusionInstruction. + void MergeFusionInstruction(HloInstruction* instruction_to_merge); + + // Delegates to HloFusionInstruction::MergeFusionInstructionIntoMultiOutput. + void MergeFusionInstructionIntoMultiOutput( + HloInstruction* instruction_to_merge); + + // Delegates to HloFusionInstruction::FuseInstruction. + HloInstruction* FuseInstruction(HloInstruction* instruction_to_fuse); + + // Delegates to HloFusionInstruction::FuseInstructionIntoMultiOutput. + HloInstruction* FuseInstructionIntoMultiOutput( + HloInstruction* instruction_to_fuse); + + // Delegates to HloFusionInstruction::fused_instruction. + HloComputation* fused_instructions_computation() const; + + // Delegates to HloFusionInstruction::fused_expression_root. + HloInstruction* fused_expression_root() const; + + // Delegates to HloFusionInstruction::fused_instructions. + tsl::gtl::iterator_range>::const_iterator>> + fused_instructions() const; + + tsl::gtl::iterator_range< + UnwrappingIterator>::iterator>> + fused_instructions(); + + // Delegates to HloFusionInstruction::fused_instruction_count. + int64_t fused_instruction_count() const; + + // Delegates to HloFusionInstruction::fused_parameter. + HloInstruction* fused_parameter(int64_t parameter_number) const; + + // Delegates to HloFusionInstruction::fused_parameters. + const InstructionVector& fused_parameters() const; + + // Returns true if this instruction is a fusion instruction that generates + // multiple outputs. + bool IsMultiOutputFusion() const; + + // Delegates to HloFusionInstruction::fusion_kind. + FusionKind fusion_kind() const; + + // Delegates to HloFusionInstruction::set_fusion_kind. + void set_fusion_kind(FusionKind kind); + + // Delegates to HloRngInstruction::random_distribution. + RandomDistribution random_distribution() const; + + // Delegates to HloParameterInstruction::parameter_number. + int64_t parameter_number() const; + + // Delegates to + // HloParameterInstruction::set_parameter_replicated_at_leaf_buffers. + void set_parameter_replicated_at_leaf_buffers( + absl::Span parameter_replicated_at_leaf_buffers); + void set_parameter_replicated_at_leaf_buffers( + const std::vector& parameter_replicated_at_leaf_buffers); + + // Delegates to HloParameterInstruction::parameter_replicated_at_leaf_buffers. + const std::optional>& parameter_replicated_at_leaf_buffers() + const; + + // Delegates to HloGetTupleElementInstruction::tuple_index. + int64_t tuple_index() const; + + // Delegates to HloGetTupleElementInstruction::set_tuple_index. + void set_tuple_index(int64_t new_tuple_index); + + // Delegates to HloReducePrecisionInstruction::exponent_bits. + int32_t exponent_bits() const; + + // Delegates to HloReducePrecisionInstruction::mantissa_bits. + int32_t mantissa_bits() const; + + // Delegates to HloInfeedInstruction::infeed_config. + std::string infeed_config() const; + + // Delegates to HloInfeedInstruction::set_infeed_config. + void set_infeed_config(const std::string& config); + + // Returns the config for the Outfeed instruction. + const std::string& outfeed_config() const; + + // Delegates to HloOutfeedInstruction::set_outfeed_config. + void set_outfeed_config(const std::string& config); + + // Returns the shape for the Outfeed instruction. + const Shape& outfeed_shape() const; + + // Returns the mutable shape for the Outfeed instruction. + Shape* mutable_outfeed_shape(); + + // Delegates to HloCollectiveInstruction::replica_groups. + const std::vector& replica_groups() const; + + // Delegates to HloCollectivePermuteInstruction::source_target_pairs. + const std::vector>& source_target_pairs() const; + + // Returns data on the window in a windowed operation such as + // convolution. + virtual const Window& window() const { + LOG(FATAL) << "Unimplemented method."; + } + + // Sets the window data in a windowed operation such as convolution. + virtual void set_window(const Window& window) { + LOG(FATAL) << "Unimplemented method."; + } + + // Returns the unique_indices field. + virtual bool unique_indices() const { LOG(FATAL) << "Unimplemented method."; } + + // Returns data on the dimension numbers used for a convolution operation, + // which may be a kConvolution instruction or a kCustomCall that implements a + // convolution. + const ConvolutionDimensionNumbers& convolution_dimension_numbers() const; + + // Sets the convolution dimension numbers on this instruction. In general you + // shouldn't need to call this; instead, specify the convolution dimension + // numbers when you create the instruction. + void set_convolution_dimension_numbers( + const ConvolutionDimensionNumbers& dnums); + + // The number of feature groups. Must be a divisor of the input feature + // dimension and output feature dimension. + int64_t feature_group_count() const; + + void set_feature_group_count(int64_t feature_group_count); + + // The number of batch groups. Must be a divisor of the input batch dimension + int64_t batch_group_count() const; + + void set_batch_group_count(int64_t batch_group_count); + + // Delegates to HloSelectAndScatterInstruction::select. + HloComputation* select() const; + + // Delegates to HloSelectAndScatterInstruction::scatter. + HloComputation* scatter() const; + + // Delegates to HloSelectAndScatterInstruction::set_select. + void set_select(HloComputation* computation); + + // Delegates to HloSelectAndScatterInstruction::set_scatter. + void set_scatter(HloComputation* computation); + + // Delegates to HloCustomCallInstruction::custom_call_target. + const std::string& custom_call_target() const; + void set_custom_call_target(absl::string_view target); + + // Delegates to HloPadInstruction::padding_config. + const PaddingConfig& padding_config() const; + PaddingConfig* mutable_padding_config(); + + // Delegates to HloConvolutionInstruction::padding_type. + PaddingType padding_type() const; + + // Delegates to HloDynamicSliceInstruction::slice_sizes. + int64_t slice_sizes(int64_t dimension) const; + + // Delegates to HloDynamicSliceInstruction::dynamic_slice_sizes. + const std::vector& dynamic_slice_sizes() const; + + // Delegates to HloCollectivePermuteInstruction::dynamic_slice_sizes. + const std::vector>& dynamic_slice_sizes_list() const; + + // Delegates to HloGatherInstruction::gather_dimension_numbers. + const GatherDimensionNumbers& gather_dimension_numbers() const; + // Delegates to HloGatherInstruction::gather_slice_sizes. + absl::Span gather_slice_sizes() const; + + // Delegates to HloScatterInstruction::scatter_dimension_numbers(). + const ScatterDimensionNumbers& scatter_dimension_numbers() const; + + // Delegates to HloDotInstruction::dot_dimension_numbers(). + const DotDimensionNumbers& dot_dimension_numbers() const; + + // Delegates to HloDomainInstruction::operand_side_metadata(). + const DomainMetadata& operand_side_metadata() const; + + // Delegates to HloDomainInstruction::user_side_metadata(). + const DomainMetadata& user_side_metadata() const; + + // Returns true if the instruction is an async-start, async-update, or + // async-done. + bool IsAsynchronous() const; + + // Returns the computation that will executed asynchronously. + HloComputation* async_wrapped_computation() const; + + // Delagates to HloAsyncInstruction::async_wrapped_instruction(). + HloInstruction* async_wrapped_instruction() const; + + // Delagates to HloAsyncInstruction::async_wrapped_opcode(). + HloOpcode async_wrapped_opcode() const; + + // Delegates to HloAsyncInstruction::async_group_id(). + std::optional async_group_id() const; + + // Delegates to HloAsyncInstruction::set_async_group_id(). + void set_async_group_id(std::optional async_group_id); + + // Delegates to HloAsyncInstruction::async_execution_thread(). + absl::string_view async_execution_thread() const; + + // Delegates to HloAsyncInstruction::set_async_execution_thread(). + void set_async_execution_thread(absl::string_view async_execution_thread); + + // Delegates to + // HloCallableInstruction::RecursivelySetComputationsThreadName(). + void set_called_computations_execution_thread( + absl::string_view async_execution_thread, + bool skip_async_execution_thread_overwrite); + + // Delegates to HloCopyStartInstruction::is_cross_program_prefetch_index(). + std::optional cross_program_prefetch_index() const; + + // Delegates to HloCompareInstruction::direction(). + ComparisonDirection comparison_direction() const; + // Delegates to HloCompareInstruction::order(). + ComparisonOrder comparison_order() const; + + // Delegates to HloTriangularSolveInstruction::triangular_solve_options(). + const TriangularSolveOptions& triangular_solve_options() const; + + // Delegates to HloCholeskyInstruction::cholesky_options(). + const CholeskyOptions& cholesky_options() const; + + // Delegates to HloCallableInstruction::output_to_operand_aliasing(). + const std::vector>>& + output_operand_aliasing() const; + + // Appends operand to the list of operands and adds this instruction as a user + // of the operand. + void AppendOperand(HloInstruction* operand); + + // Old methods kept for smooth subclassing transition END. + + HloInstruction(const HloInstruction&) = delete; + HloInstruction& operator=(const HloInstruction&) = delete; + + protected: + // Internal constructor for a given opcode/shape, other fields must be filled + // by factory methods. + HloInstruction(HloOpcode opcode, const Shape& shape); + + void RemoveAllOperands() { operands_.clear(); } + + void RemoveOperandAt(int index) { + operands_.erase(operands_.begin() + index); + } + + // Removes a list of operands with the given indices in ascending order. + void RemoveOperandsAtAscendingIndices( + absl::Span ascending_indices); + + void AppendComputation(HloComputation* computation) { + called_computations_.push_back(computation); + } + + void DetachFrom(HloInstruction* usee) { usee->RemoveUser(this); } + + void set_called_computation(int index, HloComputation* computation) { + called_computations_[index] = computation; + } + // Indices of computations in called_computations_ for instructions which call + // multiple computations. + enum { + // kWhile computations. + kBodyComputationIndex = 0, + kConditionComputationIndex = 1, + + // kSelectAndScatter computations. + kSelectComputationIndex = 0, + kScatterComputationIndex = 1, + + // kConditional computations. + kTrueComputationIndex = 0, + kFalseComputationIndex = 1, + }; + + private: + friend class HloComputation; + // Wrapper class of string format and protobuf format of BackendConfig. + class BackendConfigRep { + public: + const tsl::protobuf::Message* GetProtoPtr() const { return proto_.get(); } + + const std::string& GetRawString() const; + + BackendConfigRep Clone() const; + + bool operator==(const BackendConfigRep& other) const; + bool operator!=(const BackendConfigRep& other) const { + return !(*this == other); + } + + bool empty() const { return proto_ == nullptr && raw_string_.empty(); } + + void clear() { + proto_.reset(); + raw_string_.clear(); + } + + BackendConfigRep& operator=(std::string raw_string); + BackendConfigRep& operator=(const tsl::protobuf::Message& proto); + void SetProto(const tsl::protobuf::Message& proto); + + private: + std::unique_ptr proto_; + // If proto_ is not null, raw_string_ is a lazy cache of its string format. + mutable std::string raw_string_; + }; + + bool IdenticalInternal( + const HloInstruction& other, + absl::FunctionRef + eq_operands, + absl::FunctionRef + eq_computations, + bool layout_sensitive, bool sharding_sensitive, + bool ignore_channel_id_values, + bool ignore_commutative_operand_order) const; + + // Implementation for non-common logic of CloneWithNewOperands. + virtual std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const { + // TODO(b/80131774): This should be pure virtual. + LOG(FATAL) << "Unimplemented method."; + } + + // Implementation for non-common logic of PrintExtraAttributes. + virtual void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const {} + + // Implementation for IsElementwise if operand_idx is nullopt and for + // IsElementwiseOnOperand if otherwise. + // + // NOTE: For all instructions other than kFusion, being elementwise on one of + // the operands is equivalent to being elementwise on all the operands. + virtual bool IsElementwiseImpl( + const std::optional& operand_idx) const; + + // Prints an operand to a string. Accessed by friend class HloInstruction. + virtual void PrintOperandsWithCanonicalNameMap( + Printer* printer, const HloPrintOptions& options, + CanonicalNameMap* canonical_name_map) const; + + // See comments on Identical(). + virtual bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const; + + // Creates an n-ary elementwise operation. + static std::unique_ptr CreateNary( + const Shape& shape, HloOpcode opcode, + absl::Span operands); + + // Adds a user for this instruction. + void AddUser(HloInstruction* user); + + // Removes a user for this instruction. + void RemoveUser(HloInstruction* user); + + // Helper for implementing backend_config(). Parses backend_config_ into the + // given proto. + Status GetBackendConfigInternal(tsl::protobuf::Message* proto) const; + + // Mark this instruction as dead. Accessed by friend class HloInstruction. + void MarkAsDead() { marked_as_dead_ = true; } + + // Has this instruction been marked as dead? Accessed by friend class + // HloInstruction. + bool IsMarkedAsDead() const { return marked_as_dead_; } + + int unique_id_; // Unique to this HloInstruction within a HloModule + + // Opcode for this instruction. + HloOpcode opcode_; + + // Instruction operands. + InstructionVector operands_; + + // The set of control predecessors of this instruction. + // Note that the order of the instructions in the vector influences the order + // computed in HloComputation::ComputeInstructionPostOrder, which may + // influence the result of the compilation by changing the scheduling. We are + // not sure if it matters. + std::vector control_predecessors_; + + // The users of this instruction. Users are HLOs where this instruction is an + // operand. The vector users_ and the map user_map_ contain identical members. + // The map enables fast membership testing and the vector enables fast, stable + // iteration. The value in the map contains the index of the instruction in + // the vector what enables fast removal. + std::vector users_; + absl::flat_hash_map user_map_; + + // The set of control successors of this instruction. + std::vector control_successors_; + + // The computation in which this instruction is contained. + HloComputation* parent_ = nullptr; + + // Result shape of this instruction. + Shape shape_; + + // The sharding, if one exists. + // Uses std::shared_ptr to allow reuse of the same sharding object between + // HloInstructions and other components as HloSharding can be very large for + // many element tuples. + std::shared_ptr sharding_; + + // Computations called by this instruction. + std::vector called_computations_; + + // The backend-specific configuration for how a backend should compile this + // HLO. See the documentation on backend_config(). + mutable BackendConfigRep backend_config_; + + // Attributes passed from the frontend to give hints to the backend about + // how to compile this HLO. + // HLO -> HLO transforms are expected to preserve these attributes on a + // "best effort" basis only. + // For example: + // x = const(10, frontend_attributes={x} + // y = const(10, frontend_attributes={y} + // z = add(x,y), frontend_attributes={y} + // Could be simplified to: + // z' = const(20), frontend_attributes={?} + FrontendAttributes frontend_attributes_; + + // Used to render an HLO graph when tracking the propagation desired values + // through it. + StatisticsViz statistics_viz_; + + // String identifier for instruction. + std::string name_; + + // Metadata for debugging. + OpMetadata metadata_; + + // This field is assigned to true when backend_config_ is assigned to + // a default configuration. + bool is_default_config_ = false; + + // True if this instruction has already been detached from its user and + // operands. + bool cleaned_up_ = false; + + // Intrusive flag used by HloComputation, whether this instruction has + // been marked as dead. + bool marked_as_dead_; +}; + +// Explicit instantiations in hlo_instruction.cc. +extern template Status HloInstruction::Accept(DfsHloVisitor*, bool, bool, bool); +extern template Status HloInstruction::Accept(ConstDfsHloVisitor*, bool, bool, + bool); +extern template Status HloInstruction::Visit(DfsHloVisitor* visitor); +extern template Status HloInstruction::Visit(ConstDfsHloVisitor* visitor); + +absl::string_view ToString(HloInstruction::FusionKind kind); +StatusOr StringToFusionKind( + absl::string_view kind_name); + +// Custom (de)stringification functions for protos that live inside +// HloInstruction. +std::string PaddingConfigToString(const PaddingConfig& padding); +std::string StatisticsVizToString(const StatisticsViz& statistics_viz); +std::string RandomAlgorithmToString(const RandomAlgorithm& algorithm); +std::string RandomDistributionToString(const RandomDistribution& distribution); +std::string PrecisionToString(const PrecisionConfig::Precision& precision); +std::string DotDimensionNumbersToString(const DotDimensionNumbers& dnums); +std::string ConvolutionDimensionNumbersToString( + const ConvolutionDimensionNumbers& dnums); +std::string ReplicaGroupsToString( + absl::Span replica_groups); + +StatusOr StringToRandomAlgorithm(const std::string& name); +StatusOr StringToRandomDistribution( + const std::string& name); +StatusOr StringToPrecision(const std::string& name); +StatusOr StringToCustomCallSchedule(absl::string_view name); +StatusOr StringToCustomCallApiVersion( + absl::string_view name); + +std::ostream& operator<<(std::ostream& os, HloInstruction::FusionKind kind); + +// Map classes that guarantee a deterministic iteration order when the key is +// an HloInstruction* or a const HloInstruction*. +// To make the iteration order over the map deterministic, the comparator +// should not be using the pointer values, but rather an intrinsic property of +// the hlo. Exception: null pointer values compare less than non-null. +struct HloPtrComparator { + bool operator()(const HloInstruction* const& lhs, + const HloInstruction* const& rhs) const; +}; + +template +using HloInstructionMap = std::map; + +template +using ConstHloInstructionMap = + std::map; + +using HloInstructionSet = std::set; +using ConstHloInstructionSet = + std::set; + +template +bool HloPredicateIsOp(const HloInstruction* instruction) { + if (instruction->opcode() == op) { + return true; + } + if constexpr (sizeof...(rest) == 0) { + return false; + } else { + return HloPredicateIsOp(instruction); + } +} + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_INSTRUCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instructions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instructions.h new file mode 100644 index 0000000000000000000000000000000000000000..b9c9889ee59b2d3f631b3337be397a6a06d7bccd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_instructions.h @@ -0,0 +1,2520 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// All HloInstruction subclasses are put in this file. + +#ifndef XLA_HLO_IR_HLO_INSTRUCTIONS_H_ +#define XLA_HLO_IR_HLO_INSTRUCTIONS_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/comparison_util.h" +#include "xla/hlo/ir/hlo_clone_context.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_domain_metadata.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/iterator_util.h" +#include "xla/layout.h" +#include "xla/literal.h" +#include "xla/printer.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/gtl/iterator_range.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep +#include "tsl/platform/status.h" + +namespace xla { + +// Base class for instructions with a dimensions vector. +class HloDimensionsInstruction : public HloInstruction { + public: + absl::Span dimensions() const override { return dimensions_; } + + std::vector* mutable_dimensions() override { return &dimensions_; } + + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + switch (hlo->opcode()) { + case HloOpcode::kBroadcast: + case HloOpcode::kConcatenate: + case HloOpcode::kReduce: + case HloOpcode::kReverse: + case HloOpcode::kSort: + case HloOpcode::kTopK: + case HloOpcode::kTranspose: + return true; + default: + return false; + } + } + + protected: + HloDimensionsInstruction(HloOpcode opcode, const Shape& shape, + absl::Span dimensions) + : HloInstruction(opcode, shape), + dimensions_(dimensions.begin(), dimensions.end()) {} + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + std::vector dimensions_; +}; + +class HloBatchNormInstruction : public HloInstruction { + public: + // Returns feature_index field associated with the instruction. The index + // represents the index of the feature dimension. + int64_t feature_index() const { return feature_index_; } + + // Returns a epsilon value associated with the instruction. The is a small + // number added to the variance to avoid divide-by-zero error. + float epsilon() const { return epsilon_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + switch (hlo->opcode()) { + case HloOpcode::kBatchNormGrad: + case HloOpcode::kBatchNormInference: + case HloOpcode::kBatchNormTraining: + return true; + default: + return false; + } + } + + protected: + explicit HloBatchNormInstruction(HloOpcode opcode, const Shape& shape, + HloInstruction* operand, + HloInstruction* scale, float epsilon, + int64_t feature_index); + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // A small float number added to the variance to avoid divide-by-zero error. + float epsilon_ = 0.0f; + + // An integer value representing the index of the feature dimension. + int64_t feature_index_ = -1; +}; + +class HloBatchNormTrainingInstruction : public HloBatchNormInstruction { + public: + explicit HloBatchNormTrainingInstruction( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* offset, float epsilon, int64_t feature_index); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kBatchNormTraining; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloBatchNormInferenceInstruction : public HloBatchNormInstruction { + public: + explicit HloBatchNormInferenceInstruction( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* offset, HloInstruction* mean, HloInstruction* variance, + float epsilon, int64_t feature_index); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kBatchNormInference; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloBatchNormGradInstruction : public HloBatchNormInstruction { + public: + explicit HloBatchNormGradInstruction( + const Shape& shape, HloInstruction* operand, HloInstruction* scale, + HloInstruction* mean, HloInstruction* variance, + HloInstruction* grad_output, float epsilon, int64_t feature_index); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kBatchNormGrad; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloFftInstruction : public HloInstruction { + public: + explicit HloFftInstruction(const Shape& shape, HloInstruction* operand, + FftType fft_type, + absl::Span fft_length); + FftType fft_type() const { return fft_type_; } + + const std::vector& fft_length() const { return fft_length_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kFft; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Describes FFT type for an FFT instruction. + FftType fft_type_ = FftType::FFT; + + // Indicates the FFT length for an FFT instruction. + std::vector fft_length_; +}; + +class HloAsyncInstruction : public HloInstruction { + public: + HloAsyncInstruction( + HloOpcode opcode, const Shape& shape, + absl::Span operands, + HloComputation* async_computation, + std::optional async_group_id = std::nullopt, + absl::string_view async_execution_thread = kMainExecutionThread); + HloAsyncInstruction( + HloOpcode opcode, const Shape& shape, HloInstruction* operand, + HloComputation* async_computation, + std::optional async_group_id = std::nullopt, + absl::string_view async_execution_thread = kMainExecutionThread); + + ~HloAsyncInstruction() override; + // When an async instruction is being destructed, remove it from the vector of + // pointers of its called computation, to avoid referencing freed memory. + void ClearAsyncComputationInstruction(); + + HloInstruction* async_wrapped_instruction() const; + HloOpcode async_wrapped_opcode() const; + + // Async group id is a unique id given to a group of async operations that + // consist of one async start, one async done, and zero or more async update + // operations. The async group participates in a single async operation. The + // async operation canonicalizer pass assigns async group ids. + std::optional async_group_id() const { return async_group_id_; } + + // Async thread name is a unique thread name for one or more async groups. + // Typically one HLO module contains a main thread as well as one or more + // parallel threads. + absl::string_view async_execution_thread() const { + return async_execution_thread_; + } + void set_async_group_id(std::optional async_group_id); + void set_async_execution_thread(absl::string_view async_execution_thread); + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + switch (hlo->opcode()) { + case HloOpcode::kAsyncStart: + case HloOpcode::kAsyncUpdate: + case HloOpcode::kAsyncDone: + return true; + default: + return false; + } + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + std::optional async_group_id_; + std::string async_execution_thread_ = kMainExecutionThread; +}; + +class HloCopyStartInstruction : public HloInstruction { + public: + explicit HloCopyStartInstruction( + const Shape& shape, HloInstruction* operand, + std::optional cross_program_prefetch_index); + + std::optional cross_program_prefetch_index() const { + return cross_program_prefetch_index_; + } + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCopyStart; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Each cross program prefetched buffer has a unique index. The indices are + // assigned contiguously starting from zero in + // AlternateMemoryBestFitHeap::AllocateCrossProgramPrefetchBuffer. This value + // is used during codegen to determine which buffer is being speculated at + // runtime. One possible implementation is to initialize an array with boolean + // values indicating whether the cross program prefetch succeeds or fails for + // each buffer. + std::optional cross_program_prefetch_index_; +}; + +class HloCompareInstruction : public HloInstruction { + public: + explicit HloCompareInstruction(const Shape& shape, HloInstruction* lhs, + HloInstruction* rhs, + ComparisonDirection direction, + std::optional type); + ComparisonDirection direction() const { return compare_.GetDirection(); } + ComparisonOrder order() const { return compare_.GetOrder(); } + Comparison::Type type() const { return compare_.GetType(); } + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCompare; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + Comparison compare_; +}; + +class HloTriangularSolveInstruction : public HloInstruction { + public: + explicit HloTriangularSolveInstruction(const Shape& shape, HloInstruction* a, + HloInstruction* b, + const TriangularSolveOptions& options); + const TriangularSolveOptions& triangular_solve_options() const { + return triangular_solve_options_; + } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kTriangularSolve; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + TriangularSolveOptions triangular_solve_options_; +}; + +class HloCholeskyInstruction : public HloInstruction { + public: + explicit HloCholeskyInstruction(const Shape& shape, HloInstruction* a, + const CholeskyOptions& options); + const CholeskyOptions& cholesky_options() const { return cholesky_options_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCholesky; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + CholeskyOptions cholesky_options_; +}; + +// Class that represents instructions that synchronize and transfer data between +// partitioned devices. Send/Recv and collective instructions (AllReduce, +// AllToAll, CollectivePermute) belong to this instruction type. A group of +// instructions (of the same opcode) with the same channel_id communicate during +// execution. +class HloChannelInstruction : public HloInstruction { + public: + // Returns the channel id associated with the instruction. The id is + // shared between each Send/Recv pair or a group of collective instructions + // and is globally unique to identify each channel. + std::optional channel_id() const { return channel_id_; } + void set_channel_id(const std::optional& channel_id); + + // Whether this instruction is identical to `other` except for the values of + // channel IDs, as long as both have channel IDs or neither has a channel ID. + virtual bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const { + return channel_id_.has_value() == other.channel_id().has_value(); + } + + static bool ClassOf(const HloInstruction* hlo); + + protected: + explicit HloChannelInstruction(HloOpcode opcode, const Shape& shape, + const std::optional& channel_id); + + HloInstructionProto ToProto() const override; + + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + + // Do not override IdenticalSlowPath(). Override + // IdenticalSlowPathIgnoringChannelIdValues() instead. + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const final; + + std::optional channel_id_; +}; + +// Class that represents a top-k instruction. +class HloTopKInstruction : public HloInstruction { + public: + HloTopKInstruction(const Shape& shape, HloInstruction* input, int64_t k, + HloComputation* compare); + + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kTopK; + } + + // Returns how many K-s does it need. + int64_t k() const { return k_; } + + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + + private: + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t k_; +}; + +class HloSendRecvInstruction : public HloChannelInstruction { + public: + // Returns whether this send/recv instruction sends data to/from the host. + bool is_host_transfer() const { return is_host_transfer_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + switch (hlo->opcode()) { + case HloOpcode::kSend: + case HloOpcode::kSendDone: + case HloOpcode::kRecv: + case HloOpcode::kRecvDone: + return true; + default: + return false; + } + } + + protected: + explicit HloSendRecvInstruction(HloOpcode opcode, const Shape& shape, + int64_t channel_id, bool is_host_transfer); + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Whether this send/recv instruction sends data to/from the host. + bool is_host_transfer_; +}; + +class HloSendInstruction : public HloSendRecvInstruction { + public: + explicit HloSendInstruction(HloInstruction* operand, HloInstruction* token, + int64_t channel_id, bool is_host_transfer); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSend; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloSendDoneInstruction : public HloSendRecvInstruction { + public: + explicit HloSendDoneInstruction(HloSendInstruction* operand, + bool is_host_transfer); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSendDone; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloRecvInstruction : public HloSendRecvInstruction { + public: + explicit HloRecvInstruction(const Shape& shape, HloInstruction* token, + int64_t channel_id, bool is_host_transfer); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kRecv; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloRecvDoneInstruction : public HloSendRecvInstruction { + public: + explicit HloRecvDoneInstruction(HloRecvInstruction* operand, + bool is_host_transfer); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kRecvDone; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloCollectiveInstruction : public HloChannelInstruction { + public: + const std::vector& replica_groups() const { + return replica_groups_; + } + + // Returns true if the layout of the AllReduce is enforced by XLA client (as + // the layout set in the shape). The only reason for the client to set the + // layout is to separately compile computations that communicate with + // AllReduce. Since this field is only set `true` by the client, the compiler + // only needs to propagate existing values (e.g., Clone, X64Rewriter) or set + // `false` for all other cases. + // + // When this is `true`, there may be communication endpoints outside the + // current compilation unit, so the compiler considers this AllReduce as + // side-effecting to disable compiler transformations. The compiler is free to + // transform unconstrained AllReduces differently across compilation units. + // It is an error for an HloModule to have a mix of constrained and + // unconstrained AllReduce instructions (checked by HloVerifier). + bool constrain_layout() const { return constrain_layout_; } + + static bool ClassOf(const HloInstruction* hlo); + + protected: + explicit HloCollectiveInstruction( + HloOpcode opcode, const Shape& shape, + absl::Span operands, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id); + + HloInstructionProto ToProto() const override; + + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + std::vector replica_groups_; + bool constrain_layout_; +}; + +class HloAllGatherInstruction : public HloCollectiveInstruction { + public: + explicit HloAllGatherInstruction( + HloOpcode opcode, const Shape& shape, + absl::Span operands, int64_t all_gather_dimension, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + // Same as HloAllReduceInstruction::use_global_device_ids. + bool use_global_device_ids() const { return use_global_device_ids_; } + + // The dimension on which data from different participants are concatenated. + int64_t all_gather_dimension() const { return all_gather_dimension_; } + absl::Span dimensions() const override { + return absl::MakeConstSpan(&all_gather_dimension_, 1); + } + + void set_all_gather_dimension(int64_t dim) { all_gather_dimension_ = dim; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kAllGather || + hlo->opcode() == HloOpcode::kAllGatherStart; + } + + protected: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + HloInstructionProto ToProto() const override; + + private: + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t all_gather_dimension_; + bool use_global_device_ids_; +}; + +// Base class for all-reduce and all-reduce scatter instructions. +class HloAllReduceInstructionBase : public HloCollectiveInstruction { + public: + explicit HloAllReduceInstructionBase( + HloOpcode opcode, const Shape& shape, + absl::Span operands, + HloComputation* reduce_computation, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids); + + // Returns true if the ids in the ReplicaGroup config represent a global id of + // (replica_id * partition_count + partition_id) instead of a replica id. + // This enables more flexible grouping of devices if this all-reduce is both + // cross-partition and cross-replica. + // + // For example with 2 replicas and 4 partitions, + // replica_groups={{0,1,4,5},{2,3,6,7}}, use_global_device_ids=true means that + // group[0] = (0,0), (0,1), (1,0), (1,1) + // group[1] = (0,2), (0,3), (1,2), (1,3) + // where each pair is (replica_id, partition_id). + bool use_global_device_ids() const { return use_global_device_ids_; } + void set_use_global_device_ids(bool value) { use_global_device_ids_ = value; } + + static bool ClassOf(const HloInstruction* hlo); + + protected: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + HloInstructionProto ToProto() const override; + + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + private: + bool use_global_device_ids_; +}; + +class HloAllReduceInstruction : public HloAllReduceInstructionBase { + public: + using HloAllReduceInstructionBase::HloAllReduceInstructionBase; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kAllReduce || + hlo->opcode() == HloOpcode::kAllReduceStart; + } + + // Returns true if the AllReduce does no communication, so it's equivalent + // to a mem copy. + bool IsNoop() const; + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloReduceScatterInstruction : public HloAllReduceInstructionBase { + public: + explicit HloReduceScatterInstruction( + const Shape& shape, absl::Span operands, + HloComputation* reduce_computation, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, bool use_global_device_ids, + int64_t scatter_dimension); + + // The dimension on which reduced data is scattered to different participants. + int64_t scatter_dimension() const { return scatter_dimension_; } + absl::Span dimensions() const override { + return absl::MakeConstSpan(&scatter_dimension_, 1); + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReduceScatter; + } + + protected: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + HloInstructionProto ToProto() const override; + + private: + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t scatter_dimension_; +}; + +class HloAllToAllInstruction : public HloCollectiveInstruction { + public: + explicit HloAllToAllInstruction( + const Shape& shape, absl::Span operands, + absl::Span replica_groups, bool constrain_layout, + const std::optional& channel_id, + const std::optional& split_dimension); + + // AllToAll can optionally take a split dimension, which means that this + // AllToAll takes a single (flattened) array operand and produces an array + // output (instead of taking a list of operands and producing a tuple). + // + // split_dimension specifies which dimension in the operand is split across + // devices in each replica_group, and also means the concatenated dimension + // on the output (i.e., input and the output shapes are the same). + std::optional split_dimension() const { return split_dimension_; } + void set_split_dimension(int64_t dim) { split_dimension_ = dim; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kAllToAll; + } + + protected: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + HloInstructionProto ToProto() const override; + + private: + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + std::optional split_dimension_; +}; + +class HloCollectivePermuteInstruction : public HloChannelInstruction { + public: + explicit HloCollectivePermuteInstruction( + HloOpcode opcode, const Shape& shape, HloInstruction* operand, + const std::vector>& source_target_pairs, + const std::optional& channel_id); + + explicit HloCollectivePermuteInstruction( + HloOpcode opcode, const Shape& shape, HloInstruction* input, + HloInstruction* output, HloInstruction* input_start_indices, + HloInstruction* output_start_indices, + absl::Span> source_target_pairs, + absl::Span> slice_sizes, + const std::optional& channel_id); + + const std::vector>& source_target_pairs() const { + return source_target_pairs_; + } + + const std::vector>& dynamic_slice_sizes_list() const { + return slice_sizes_; + } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCollectivePermute || + hlo->opcode() == HloOpcode::kCollectivePermuteStart; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPathIgnoringChannelIdValues( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + const std::vector> source_target_pairs_; + const std::vector> slice_sizes_; +}; + +inline bool HloAllReduceInstructionBase::ClassOf(const HloInstruction* hlo) { + return HloAllReduceInstruction::ClassOf(hlo) || + hlo->opcode() == HloOpcode::kReduceScatter; +} + +inline bool HloCollectiveInstruction::ClassOf(const HloInstruction* hlo) { + return HloAllReduceInstructionBase::ClassOf(hlo) || + HloAllGatherInstruction::ClassOf(hlo) || + HloAllToAllInstruction::ClassOf(hlo); +} + +inline bool HloChannelInstruction::ClassOf(const HloInstruction* hlo) { + return HloCollectiveInstruction::ClassOf(hlo) || + HloCollectivePermuteInstruction::ClassOf(hlo) || + HloSendRecvInstruction::ClassOf(hlo); +} + +class HloReverseInstruction : public HloDimensionsInstruction { + public: + explicit HloReverseInstruction(const Shape& shape, HloInstruction* operand, + absl::Span dimensions); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReverse; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloConcatenateInstruction : public HloDimensionsInstruction { + public: + explicit HloConcatenateInstruction(const Shape& shape, + absl::Span operands, + int64_t dimension); + // Accessor for the dimension in which a concatenate HLO should occur. + int64_t concatenate_dimension() const override { + return HloInstruction::dimensions(0); + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kConcatenate; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloReduceInstruction : public HloDimensionsInstruction { + public: + explicit HloReduceInstruction(const Shape& shape, + absl::Span args, + absl::Span dimensions_to_reduce, + HloComputation* reduce_computation); + + // Returns the number of input arrays (and, consequentially, the number of + // init values) this reduce has. + int64_t input_count() const { return operand_count() / 2; } + + // Returns the input tensors to be reduced. + absl::Span inputs() const { + return absl::MakeSpan(operands()).subspan(0, input_count()); + } + + // Returns the init values of the reduction. + absl::Span init_values() const { + return absl::MakeSpan(operands()).subspan(input_count(), operand_count()); + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReduce; + } + + private: + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloSortInstruction : public HloDimensionsInstruction { + public: + explicit HloSortInstruction(const Shape& shape, int64_t dimension, + absl::Span operands, + HloComputation* compare, bool is_stable); + // Returns the sort dimension for this instruction + int64_t sort_dimension() const { return HloInstruction::dimensions(0); } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + // Returns the key operand to this instruction. + const HloInstruction* keys() const { return operand(0); } + HloInstruction* mutable_keys() { return mutable_operand(0); } + // Returns the number of value operands. + int64_t values_count() const { return operand_count() - 1; } + bool is_stable() const { return is_stable_; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSort; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + bool is_stable_; +}; + +class HloTransposeInstruction : public HloDimensionsInstruction { + public: + explicit HloTransposeInstruction(const Shape& shape, HloInstruction* operand, + absl::Span dimensions); + // Returns whether this instruction does a rank-2 transposition. + bool IsRank2Transpose() const; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kTranspose; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloBroadcastInstruction : public HloDimensionsInstruction { + public: + explicit HloBroadcastInstruction( + const Shape& shape, HloInstruction* operand, + absl::Span broadcast_dimension); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kBroadcast; + } + + private: + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; +}; + +class HloDynamicReshapeInstruction : public HloInstruction { + public: + explicit HloDynamicReshapeInstruction( + const Shape& shape, HloInstruction* data_operand, + absl::Span dim_sizes); + + // Returns the input dim sizes dimensions, which is operands[1:] + absl::Span dim_sizes() const { + return absl::MakeSpan(operands()).subspan(1, operand_count()); + } + + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Returns the input dim size dimension, which is operands[1+i] + HloInstruction* dim_sizes(int64_t i) const { return operands()[i + 1]; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDynamicReshape; + } +}; + +class HloReshapeInstruction : public HloInstruction { + public: + explicit HloReshapeInstruction(const Shape& shape, HloInstruction* operand, + int64_t inferred_dimension); + int64_t inferred_dimension() const { return inferred_dimension_; } + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReshape; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + int64_t inferred_dimension_; +}; + +class HloMapInstruction : public HloInstruction { + public: + explicit HloMapInstruction(const Shape& shape, + absl::Span operands, + HloComputation* map_computation); + // Returns the dimension sizes or numbers associated with this instruction. + absl::Span dimensions() const override { return dimensions_; } + + std::vector* mutable_dimensions() override { return &dimensions_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kMap; + } + + private: + bool IsElementwiseImpl( + const std::optional& operand_idx) const override; + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + std::vector dimensions_; +}; + +class HloSliceInstruction : public HloInstruction { + public: + explicit HloSliceInstruction(const Shape& shape, HloInstruction* operand, + absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides); + + HloInstructionProto ToProto() const override; + + // Returns the start index in the given dimension for a slice node. + int64_t slice_starts(int64_t dimension) const { + return slice_starts_[dimension]; + } + const std::vector& slice_starts() const { return slice_starts_; } + std::vector* mutable_slice_starts() { return &slice_starts_; } + + // Returns the (exclusive) limit index in the given dimension for a slice + // node. + int64_t slice_limits(int64_t dimension) const { + return slice_limits_[dimension]; + } + const std::vector& slice_limits() const { return slice_limits_; } + std::vector* mutable_slice_limits() { return &slice_limits_; } + + // Returns the stride in the given dimension for a slice node. + int64_t slice_strides(int64_t dimension) const { + return slice_strides_[dimension]; + } + const std::vector& slice_strides() const { return slice_strides_; } + std::vector* mutable_slice_strides() { return &slice_strides_; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSlice; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Describes the [begin, end) index range for a slice. + std::vector slice_starts_; + std::vector slice_limits_; + std::vector slice_strides_; +}; + +class HloConstantInstruction : public HloInstruction { + public: + explicit HloConstantInstruction(Literal literal); + HloConstantInstruction(Literal literal, const Shape& shape); + HloConstantInstruction(std::shared_ptr literal, const Shape& shape); + // Used when the literal is too large and dropped. + explicit HloConstantInstruction(const Shape& shape); + // Returns the literal associated with this instruction. + const Literal& literal() const { return *literal_; } + // Returns the (mutable) literal associated with this instruction. + // Clone the literal if necessary (do not modify the shared instance). + Literal* mutable_literal() { + if (literal_.use_count() > 1) { + literal_.reset(new Literal(literal_->Clone())); + } + return literal_.get(); + } + // Returns whether there is literal associated with this instruction. + bool HasLiteral() const { return static_cast(literal_); } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + // Change the layout for an Constant Hlo instruction to match new_layout. For + // tuple shaped constants shape_index is the path to the internal array + // subshape whose layout needs to be changed. + void RelayoutConstant(const Layout& new_layout, + const ShapeIndex& shape_index = {}); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kConstant; + } + + private: + bool IsElementwiseImpl( + const std::optional& operand_idx) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + void PrintOperandsWithCanonicalNameMap( + Printer* printer, const HloPrintOptions& options, + CanonicalNameMap* canonical_name_map) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + std::shared_ptr literal_; +}; + +// Abstract class that represents an HLO instruction that "calls" a computation. +// Fusion and Call HLOs inherit from this class. +class HloCallableInstruction : public HloInstruction { + public: + HloCallableInstruction(HloOpcode opcode, const Shape& shape); + + HloCallableInstruction(HloOpcode opcode, const Shape& shape, + absl::Span operands); + + HloCallableInstruction(HloOpcode opcode, const Shape& shape, + absl::Span operands, + HloComputation* called_computation, + absl::string_view prefix = ""); + + HloCallableInstruction(HloOpcode opcode, const Shape& shape, + absl::Span operands, + absl::Span called_computations); + + ~HloCallableInstruction() override; + + // Adds a new operand to the callable instruction. + HloInstruction* AddCallOperand(HloInstruction* new_operand); + + // Appends (fuses) the given instruction into this callable instruction. + // instruction_to_append is cloned and the clone is placed in the callable + // instruction. The users of instruction_to_append will be redirected to this + // callable instruction. instruction_to_append is unchanged otherwise. When + // add_output is true, a clone of the instruction_to_append will be added as + // additional output resulting in a multi-output callable instruction. + HloInstruction* AppendInstructionIntoCalledComputation( + HloInstruction* instruction_to_append, bool add_output = false); + // Clones the given instruction_to_append and inserts the clone into this + // callable instruction. If add_output is true, a clone of + // instruction_to_append will be in the output of the this callable + // instruction (part of the tuple of the callable root). + HloInstruction* CloneAndAppendInstructionIntoCalledComputation( + HloInstruction* instruction_to_append, bool add_output = false); + + // Retrieves the called computations of an HloCallableInstruction that is + // being cloned. If the called computations have not yet been cloned, then + // they are first cloned and added to the context. + absl::InlinedVector GetOrCloneCalledComputations( + HloCloneContext* context) const; + + HloComputation* called_computation() const; + + HloInstruction* called_computation_root() const; + + // Recursively sets all nested called computation to have thread name as + // `execution_thread`. if `skip_async_execution_thread_overwrite` is true, + // skip overwrite async instruction and its comptuations thread name + // overwriting. + void RecursivelySetComputationsThreadName( + absl::string_view execution_thread, + bool skip_async_execution_thread_overwrite); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kFusion || + hlo->opcode() == HloOpcode::kCall || + hlo->opcode() == HloOpcode::kCustomCall; + } + + // Gets a list of output/operand buffer pairs that alias each other, where the + // output buffer is represented as a ShapeIndex, and the operand buffer is + // represented as the operand index and the ShapeIndex. By default this list + // is empty. + const std::vector>>& + output_to_operand_aliasing() const { + return output_to_operand_aliasing_; + } + // Sets the list of output/operand buffer pairs that alias each other. + void set_output_to_operand_aliasing( + std::vector>> + aliasing) { + output_to_operand_aliasing_ = std::move(aliasing); + } + + protected: + // Returns the default called computation name. + virtual std::string default_called_computation_name() const = 0; + + private: + // A list of output/operand buffer pairs that alias each other. See comment of + // output_to_operand_aliasing(). + std::vector>> + output_to_operand_aliasing_; +}; + +class HloFusionInstruction : public HloCallableInstruction { + public: + explicit HloFusionInstruction(const Shape& shape, FusionKind fusion_kind, + HloInstruction* fused_root); + + explicit HloFusionInstruction(const Shape& shape, FusionKind fusion_kind, + absl::Span operands, + HloComputation* fusion_computation, + absl::string_view prefix = ""); + + ~HloFusionInstruction() override; + + void ClearCalledComputations() override; + + // When a fusion instruction is being destructed, clear the back pointer of + // its fusion computation, to avoid referencing freed memory. + void ClearFusionComputationInstruction(); + + std::string ToCategory() const override; + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + // Adds a new operand the fusion instruction. + HloInstruction* AddFusionOperand(HloInstruction* new_operand); + + // Merges the fused instructions from 'instruction_to_merge' into the + // fused instruction set of 'this', updating operands as necessary. + // + // Precondition: 'instruction_to_merge' must be an operand of 'this'. + void MergeFusionInstruction(HloFusionInstruction* instruction_to_merge); + + // Merges the fused instructions from instruction_to_merge into the fused + // instruction set of 'this' and generates multioutput fusion instructions. + // All the users of instruction_to_merge will be redirected to 'this' + // instruction. instruction_to_merge will be removed from its parent + // computation. + void MergeFusionInstructionIntoMultiOutput( + HloFusionInstruction* instruction_to_merge); + + // Fuses the given instruction in this fusion instruction. instruction_to_fuse + // is cloned and the clone is placed in the fusion + // instruction. instruction_to_fuse is unchanged. Instruction is cloned rather + // than moved to cleanly handle the case where the instruction has a use + // outside the fusion instruction. Moving such an instruction into a fusion + // instruction would violate the single-result invariant of HLO instructions + // and significantly complicate code generation. + HloInstruction* FuseInstruction(HloInstruction* instruction_to_fuse) { + CHECK(instruction_to_fuse->IsFusible()) << instruction_to_fuse->ToString(); + return AppendInstructionIntoCalledComputation(instruction_to_fuse); + } + + // Fuses the given instruction in this fusion instruction and generates a + // multioutput fusion instruction. A clone of the instruction_to_fuse will + // be part of the output of fusion instructions. The users of + // instruction_to_fuse will be redirected to this fusion instructions. + // instruction_to_fuse is unchanged otherwise. + HloInstruction* FuseInstructionIntoMultiOutput( + HloInstruction* instruction_to_fuse) { + return AppendInstructionIntoCalledComputation(instruction_to_fuse, + /*add_output=*/true); + } + + // Returns the computation for this fused instruction. + HloComputation* fused_instructions_computation() const; + + // Returns the root instruction of the fused expression contained within this + // fusion instruction. + HloInstruction* fused_expression_root() const; + + // Returns the list of fused instructions inside this fusion instruction. The + // returned type is a range of HloInstruction*s. + tsl::gtl::iterator_range>::const_iterator>> + fused_instructions() const; + + tsl::gtl::iterator_range< + UnwrappingIterator>::iterator>> + fused_instructions(); + + // Gets the number of instructions inside this fusion instruction. + int64_t fused_instruction_count() const; + + // Returns the fused parameter instruction in this fusion instruction + // corresponding to the given parameter number. + HloInstruction* fused_parameter(int64_t parameter_number) const; + + // Returns the vector of fused parameters inside this fusion instruction. + const HloInstruction::InstructionVector& fused_parameters() const; + + // Returns true if this instruction is a fusion instruction that generates + // multiple outputs. + bool IsMultiOutputFusion() const { + return fused_expression_root()->opcode() == HloOpcode::kTuple; + } + + FusionKind fusion_kind() const { return fusion_kind_; } + + void set_fusion_kind(FusionKind kind) { fusion_kind_ = kind; } + + // If multiple operands are the same instruction, keeps only one of them. + Status DeduplicateFusionOperands(); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kFusion; + } + + protected: + std::string default_called_computation_name() const override { + return "fused_computation"; + } + + private: + bool IsElementwiseImpl( + const std::optional& operand_idx) const override; + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // The type of the fusion. + FusionKind fusion_kind_; +}; + +class HloCallInstruction : public HloCallableInstruction { + public: + HloCallInstruction(const Shape& shape, + HloInstruction* called_computation_root); + + HloCallInstruction(const Shape& shape, + absl::Span operands, + HloComputation* called_computation); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCall; + } + + protected: + std::string default_called_computation_name() const override { + return "called_computation"; + } +}; + +class HloRngInstruction : public HloInstruction { + public: + explicit HloRngInstruction(const Shape& shape, + RandomDistribution distribution, + absl::Span parameters); + // Returns the random distribution for this rng node. + RandomDistribution random_distribution() const { return distribution_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kRng; + } + + private: + bool IsElementwiseImpl( + const std::optional& operand_idx) const override; + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // The distribution requested for random number generation. + RandomDistribution distribution_; +}; + +class HloParameterInstruction : public HloInstruction { + public: + explicit HloParameterInstruction(int64_t parameter_number, const Shape& shape, + absl::string_view name); + int64_t parameter_number() const { return parameter_number_; } + + // Sets and gets the whether all replicas will receive the same parameter data + // for each leaf buffer in data parallelism. + void set_parameter_replicated_at_leaf_buffers( + absl::Span parameter_replicated_at_leaf_buffers) { + CHECK_EQ(ShapeUtil::GetLeafCount(shape()), + parameter_replicated_at_leaf_buffers.size()); + parameter_replicated_at_leaf_buffers_.emplace( + parameter_replicated_at_leaf_buffers.begin(), + parameter_replicated_at_leaf_buffers.end()); + } + void set_parameter_replicated_at_leaf_buffers( + const std::vector& parameter_replicated_at_leaf_buffers) { + CHECK_EQ(ShapeUtil::GetLeafCount(shape()), + parameter_replicated_at_leaf_buffers.size()); + parameter_replicated_at_leaf_buffers_ = + parameter_replicated_at_leaf_buffers; + } + const std::optional>& parameter_replicated_at_leaf_buffers() + const { + return parameter_replicated_at_leaf_buffers_; + } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kParameter; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + void PrintOperandsWithCanonicalNameMap( + Printer* printer, const HloPrintOptions& options, + CanonicalNameMap* canonical_name_map) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t parameter_number_ = 0; + + // Specifies whether each buffer has the same parameter value on all replicas + // in data parallelism. + std::optional> parameter_replicated_at_leaf_buffers_; +}; + +class HloGetTupleElementInstruction : public HloInstruction { + public: + explicit HloGetTupleElementInstruction(const Shape& shape, + HloInstruction* operand, + int64_t index); + // Returns the tuple index associated with this instruction. + int64_t tuple_index() const { return tuple_index_; } + // Sets the tuple index associated with this instruction. + void set_tuple_index(int64_t new_tuple_index) { + tuple_index_ = new_tuple_index; + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kGetTupleElement; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t tuple_index_ = -1; +}; + +class HloReducePrecisionInstruction : public HloInstruction { + public: + explicit HloReducePrecisionInstruction(const Shape& shape, + HloInstruction* operand, + int exponent_bits, int mantissa_bits); + // Returns the number of exponent bits for a reduce-precision node. + int32_t exponent_bits() const { return exponent_bits_; } + // Returns the number of mantissa bits for a reduce-precision node. + int32_t mantissa_bits() const { return mantissa_bits_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReducePrecision; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // The bit sizes for a reduce-precision operation. + int32_t exponent_bits_ = 0; + int32_t mantissa_bits_ = 0; +}; + +class HloInfeedInstruction : public HloInstruction { + public: + explicit HloInfeedInstruction(const Shape& infeed_shape, + HloInstruction* token_operand, + const std::string& config); + // Returns the infeed configuration string. The infeed configuration includes + // any metadata needed for the backend compiler (e.g., infeed buffer address) + // and is target-dependent. + std::string infeed_config() const { return infeed_config_; } + void set_infeed_config(const std::string& config) { infeed_config_ = config; } + // Returns the shape of the data received by the infeed. This is not the same + // as the shape of the infeed instruction which produces a tuple containing + // the infeed data shape and a TOKEN. + const Shape& infeed_shape() const { + TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape())); + return ShapeUtil::GetSubshape(shape(), {0}); + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kInfeed; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // The string representation of the infeed configuration. + std::string infeed_config_; +}; + +class HloOutfeedInstruction : public HloInstruction { + public: + explicit HloOutfeedInstruction(const Shape& outfeed_shape, + HloInstruction* operand, + HloInstruction* token_operand, + absl::string_view outfeed_config); + // Returns the shape for the Outfeed instruction. + const Shape& outfeed_shape() const { return outfeed_shape_; } + // Returns the mutable shape for the Outfeed instruction. + Shape* mutable_outfeed_shape() { return &outfeed_shape_; } + // Returns the config for the Outfeed instruction. + const std::string& outfeed_config() const { return outfeed_config_; } + void set_outfeed_config(const std::string& config) { + outfeed_config_ = config; + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kOutfeed; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Shape of outfeed request. + Shape outfeed_shape_; + // Outfeed configuration information, only present for kOutfeed. + std::string outfeed_config_; +}; + +class HloConvolutionInstruction : public HloInstruction { + public: + explicit HloConvolutionInstruction( + const Shape& shape, HloInstruction* lhs, HloInstruction* rhs, + int64_t feature_group_count, int64_t batch_group_count, + const Window& window, + const ConvolutionDimensionNumbers& dimension_numbers, + const PrecisionConfig& precision_config); + const Window& window() const override { return window_; } + void set_window(const Window& window) override { window_ = window; } + const ConvolutionDimensionNumbers& convolution_dimension_numbers() const { + return convolution_dimension_numbers_; + } + void set_convolution_dimension_numbers( + const ConvolutionDimensionNumbers& dnums) { + convolution_dimension_numbers_ = dnums; + } + // The number of feature groups. Must be a divisor of the input feature + // dimension and output feature dimension. + int64_t feature_group_count() const { return feature_group_count_; } + void set_feature_group_count(int64_t num_feature_groups) { + feature_group_count_ = num_feature_groups; + } + // The number of batch groups. Must be a divisor of the input batch dimension. + int64_t batch_group_count() const { return batch_group_count_; } + void set_batch_group_count(int64_t num_batch_groups) { + batch_group_count_ = num_batch_groups; + } + + // Returns the information used to tell the implementation information about + // what sort of precision is requested. The meaning of the field is backend + // specific. At the moment, it is only supported for kConvolution and kDot. + // Transformations on one kDot or kConvolution to another will preserve this + // information. Transformations to other HLOs will not preserve this + // information but it is presumed that the alternate lowering is strictly + // superior. + const PrecisionConfig& precision_config() const { return precision_config_; } + PrecisionConfig* mutable_precision_config() { return &precision_config_; } + + std::string ToCategory() const override; + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kConvolution; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + // The number of feature groups. Must be a divisor of the input feature + // dimension and output feature dimension. + int64_t feature_group_count_; + // The number of batch groups. Must be a divisor of the input batch dimension. + int64_t batch_group_count_; + // Describes the window used for a convolution. + Window window_; + // Describes the dimension numbers used for a convolution. + ConvolutionDimensionNumbers convolution_dimension_numbers_; + // Information used to communicate to the implementation about the algorithm + // used to produce results. See the documentation on precision_config(). + PrecisionConfig precision_config_; +}; + +class HloReduceWindowInstruction : public HloInstruction { + public: + explicit HloReduceWindowInstruction(const Shape& shape, + HloInstruction* operand, + HloInstruction* init_value, + const Window& window, + HloComputation* reduce_computation); + explicit HloReduceWindowInstruction( + const Shape& shape, absl::Span operands, + absl::Span init_values, const Window& window, + HloComputation* reduce_computation); + const Window& window() const override { return window_; } + void set_window(const Window& window) override { window_ = window; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + // Returns the number of input arrays (and, consequentially, the number of + // init values) this reduce has. + int64_t input_count() const { return operand_count() / 2; } + // Returns the input tensors to be reduced. + absl::Span inputs() const { + return absl::MakeSpan(operands()).subspan(0, input_count()); + } + // Returns the init values of the reduction. + absl::Span init_values() const { + return absl::MakeSpan(operands()).subspan(input_count(), operand_count()); + } + // Returns the shapes of input tensors to be reduced. + absl::InlinedVector input_shapes() const { + absl::InlinedVector shapes; + for (const auto* op : inputs()) { + shapes.push_back(&op->shape()); + } + return shapes; + } + // Returns the init values of the reduction. + absl::InlinedVector init_value_shapes() const { + absl::InlinedVector shapes; + for (const auto* op : init_values()) { + shapes.push_back(&op->shape()); + } + return shapes; + } + // Returns the shapes of the reduced output tensors. + absl::InlinedVector output_shapes() const { + absl::InlinedVector shapes; + if (shape().IsArray()) { + shapes.push_back(&shape()); + } else { + for (const Shape& tuple_element_shape : shape().tuple_shapes()) { + shapes.push_back(&tuple_element_shape); + } + } + return shapes; + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kReduceWindow; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + Window window_; +}; + +class HloSelectAndScatterInstruction : public HloInstruction { + public: + explicit HloSelectAndScatterInstruction( + const Shape& shape, HloInstruction* operand, HloComputation* select, + const Window& window, HloInstruction* source, HloInstruction* init_value, + HloComputation* scatter); + const Window& window() const override { return window_; } + void set_window(const Window& window) override { window_ = window; } + // Gets/sets the select or scatter HloComputation for SelectAndScatter. The + // setters should only be called by HloModule or HloComputation methods. + HloComputation* select() const { + return called_computations()[kSelectComputationIndex]; + } + + HloComputation* scatter() const { + return called_computations()[kScatterComputationIndex]; + } + + void set_select(HloComputation* computation) { + set_called_computation(kSelectComputationIndex, computation); + } + + void set_scatter(HloComputation* computation) { + set_called_computation(kScatterComputationIndex, computation); + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSelectAndScatter; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + Window window_; +}; + +class HloCustomCallInstruction : public HloCallableInstruction { + public: + HloCustomCallInstruction(const Shape& shape, + absl::Span operands, + absl::string_view custom_call_target, + std::string opaque, + CustomCallApiVersion api_version); + + // Constructor for a custom call with constrained layout. 'shape' and + // 'operands_with_layout' must all have layouts. + HloCustomCallInstruction(const Shape& shape, + absl::Span operands, + absl::string_view custom_call_target, + std::string opaque, + absl::Span operand_shapes_with_layout, + CustomCallApiVersion api_version); + + // Constructor for a custom call with a to_apply computation. + HloCustomCallInstruction(const Shape& shape, + absl::Span operands, + HloComputation* to_apply, + absl::string_view custom_call_target, + std::string opaque, + CustomCallApiVersion api_version); + + // Constructor for a custom call with multiple computations. + HloCustomCallInstruction( + const Shape& shape, absl::Span operands, + absl::Span called_computations, + absl::string_view custom_call_target, std::string opaque, + CustomCallApiVersion api_version); + + const Window& window() const override { + CHECK(window_ != nullptr); + return *window_; + } + + void set_window(const Window& window) override { + window_ = std::make_unique(window); + } + + const ConvolutionDimensionNumbers& convolution_dimension_numbers() const { + CHECK(convolution_dimension_numbers_ != nullptr); + return *convolution_dimension_numbers_; + } + + void set_convolution_dimension_numbers( + const ConvolutionDimensionNumbers& dnums) { + convolution_dimension_numbers_ = + std::make_unique(dnums); + } + // TODO(jpienaar): Remove this accessor in the follow up. + const std::string& opaque() const { return raw_backend_config_string(); } + const std::string& custom_call_target() const { return custom_call_target_; } + void set_custom_call_target(absl::string_view target) { + custom_call_target_ = std::string(target); + } + void set_feature_group_count(int64_t feature_group_count) { + feature_group_count_ = feature_group_count; + } + void set_batch_group_count(int64_t batch_group_count) { + batch_group_count_ = batch_group_count; + } + // Sets whether this custom call has a side-effect - by default a custom call + // has no side-effects. + void set_custom_call_has_side_effect(bool custom_call_has_side_effect) { + custom_call_has_side_effect_ = custom_call_has_side_effect; + } + int64_t feature_group_count() const { return feature_group_count_; } + int64_t batch_group_count() const { return batch_group_count_; } + bool custom_call_has_side_effect() const { + return custom_call_has_side_effect_; + } + // Returns padding type used for ops like convolution. + PaddingType padding_type() const { return padding_type_; } + + void set_padding_type(PaddingType padding_type) { + padding_type_ = padding_type; + } + + // Returns the literal associated with this instruction. + const Literal& literal() const { return *literal_; } + // Set the value of literal to a new one. + void set_literal(Literal&& literal) { literal_.emplace(std::move(literal)); } + // Returns whether there is literal associated with this instruction. + bool HasLiteral() const { return literal_.has_value(); } + + const PrecisionConfig& precision_config() const { return precision_config_; } + PrecisionConfig* mutable_precision_config() { return &precision_config_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + // Returns whether the result and operand layouts are constrained. + bool layout_constrained() const { return layout_constrained_; } + + // Returns the shapes (with layout) of the operands. CHECKs if this custom + // call does not have constrained layouts. + const std::vector& operand_shapes_with_layout() const { + CHECK(layout_constrained()); + return operand_shapes_with_layout_; + } + void set_custom_call_schedule(CustomCallSchedule custom_call_schedule) { + custom_call_schedule_ = custom_call_schedule; + } + CustomCallSchedule custom_call_schedule() const { + return custom_call_schedule_; + } + void set_api_version(CustomCallApiVersion api_version) { + api_version_ = api_version; + } + CustomCallApiVersion api_version() const { return api_version_; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kCustomCall; + } + + protected: + std::string default_called_computation_name() const override { + return "custom_call_computation"; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + // Name of a global symbol to call. + std::string custom_call_target_; + // Describes the window in a windowed operation such as convolution. + std::unique_ptr window_; + // Describes the dimension numbers used for a convolution. + std::unique_ptr convolution_dimension_numbers_; + // The number of feature groups. This is used for grouped convolutions. + int64_t feature_group_count_; + int64_t batch_group_count_; + // Whether the result and operand layouts are constrained. + bool layout_constrained_; + // Information used to communicate to the implementation about the algorithm + // used to produce results for convolution instructions. + PrecisionConfig precision_config_; + // Describes the padding type for convolution instructions. + PaddingType padding_type_; + // For layout-constrained custom calls, this vector holds the shape with + // layout for each operand. + std::vector operand_shapes_with_layout_; + // Whether this custom call has a side-effect. + bool custom_call_has_side_effect_; + std::optional literal_; + // A custom-call schedule hint. + CustomCallSchedule custom_call_schedule_; + // The version of the API used by the custom call function. + // TODO(b/189822916): Remove this field when all clients are migrated to the + // status-returning API. + CustomCallApiVersion api_version_; +}; + +class HloPadInstruction : public HloInstruction { + public: + explicit HloPadInstruction(const Shape& shape, HloInstruction* operand, + HloInstruction* padding_value, + const PaddingConfig& padding_config); + // Returns the padding configuration for a pad node. + const PaddingConfig& padding_config() const { return padding_config_; } + PaddingConfig* mutable_padding_config() { return &padding_config_; } + // Returns the operand being padded. + const HloInstruction* padded_operand() const { return operand(0); } + HloInstruction* mutable_padded_operand() { return mutable_operand(0); } + // Returns the padding value. + const HloInstruction* padding_value() const { return operand(1); } + HloInstruction* mutable_padding_value() { return mutable_operand(1); } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kPad; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // The padding configuration that describes the edge padding and interior + // padding of this pad instruction. + PaddingConfig padding_config_; +}; + +class HloDynamicIndexInstruction : public HloInstruction { + public: + explicit HloDynamicIndexInstruction(HloOpcode opcode, const Shape& shape) + : HloInstruction(opcode, shape) {} + virtual int64_t first_index_operand_number() const = 0; + + // Returns a subspan of operands which represent the start indices. + absl::Span index_operands() const { + return absl::MakeSpan(operands()).subspan(first_index_operand_number()); + } + + // Returns the shapes of the index operands. + std::vector index_shapes() const { + std::vector shapes; + auto indices = index_operands(); + for (const HloInstruction* index : indices) { + shapes.push_back(index->shape()); + } + return shapes; + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDynamicSlice || + hlo->opcode() == HloOpcode::kDynamicUpdateSlice; + } +}; + +class HloDynamicSliceInstruction : public HloDynamicIndexInstruction { + public: + explicit HloDynamicSliceInstruction(const Shape& shape, + HloInstruction* operand, + HloInstruction* start_indices, + absl::Span slice_sizes); + explicit HloDynamicSliceInstruction( + const Shape& shape, HloInstruction* operand, + absl::Span start_indices, + absl::Span slice_sizes); + // Old methods kept for smooth subclassing transition END. + // Returns the size of the slice in the given dimension for a dynamic + // slice node. + int64_t slice_sizes(int64_t dimension) const { + return dynamic_slice_sizes_[dimension]; + } + const std::vector& dynamic_slice_sizes() const { + return dynamic_slice_sizes_; + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + int64_t first_index_operand_number() const override { return 1; } + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDynamicSlice; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Describes the [start, start + size) range size for a dynamic slice + // ('start' is specified dynamically in the second operand of the operation). + std::vector dynamic_slice_sizes_; +}; + +class HloDynamicUpdateSliceInstruction : public HloDynamicIndexInstruction { + public: + explicit HloDynamicUpdateSliceInstruction(const Shape& shape, + HloInstruction* operand, + HloInstruction* update, + HloInstruction* start_indices); + explicit HloDynamicUpdateSliceInstruction( + const Shape& shape, HloInstruction* operand, HloInstruction* update, + absl::Span start_indices); + + int64_t first_index_operand_number() const override { return 2; } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDynamicUpdateSlice; + } +}; + +class HloGatherInstruction : public HloInstruction { + public: + explicit HloGatherInstruction( + const Shape& shape, HloInstruction* operand, + HloInstruction* start_indices, + const GatherDimensionNumbers& gather_dim_numbers, + absl::Span slice_sizes, bool indices_are_sorted); + const GatherDimensionNumbers& gather_dimension_numbers() const { + CHECK(gather_dimension_numbers_ != nullptr); + return *gather_dimension_numbers_; + } + absl::Span gather_slice_sizes() const { + return gather_slice_sizes_; + } + bool indices_are_sorted() const { return indices_are_sorted_; } + void set_indices_are_sorted(bool indices_are_sorted) { + indices_are_sorted_ = indices_are_sorted; + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + // Creates an instance of GatherDimensionNumbers. + static GatherDimensionNumbers MakeGatherDimNumbers( + absl::Span offset_dims, + absl::Span collapsed_slice_dims, + absl::Span start_index_map, int64_t index_vector_dim); + // Returns the dump string of the given gather dimension numbers. + static std::string GatherDimensionNumbersToString( + const GatherDimensionNumbers& dim_numbers); + // Prints the dump string of the given gather dimension numbers. + static void PrintGatherDimensionNumbers( + Printer* printer, const GatherDimensionNumbers& dim_numbers); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kGather; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + std::unique_ptr gather_dimension_numbers_; + std::vector gather_slice_sizes_; + bool indices_are_sorted_; +}; + +class HloScatterInstruction : public HloInstruction { + public: + explicit HloScatterInstruction( + const Shape& shape, absl::Span args, + HloComputation* update_computation, + const ScatterDimensionNumbers& scatter_dim_numbers, + bool indices_are_sorted, bool unique_indices); + const ScatterDimensionNumbers& scatter_dimension_numbers() const { + CHECK(scatter_dimension_numbers_ != nullptr); + return *scatter_dimension_numbers_; + } + bool indices_are_sorted() const { return indices_are_sorted_; } + void set_indices_are_sorted(bool indices_are_sorted) { + indices_are_sorted_ = indices_are_sorted; + } + bool unique_indices() const override { return unique_indices_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + int64_t scatter_operand_count() const { return operand_count() / 2; } + absl::Span scatter_operands() const { + return absl::MakeConstSpan(operands()).first(scatter_operand_count()); + } + absl::Span scatter_updates() const { + return absl::MakeConstSpan(operands()).last(scatter_operand_count()); + } + const HloInstruction* scatter_indices() const { + return operand(scatter_operand_count()); + } + HloInstruction* scatter_indices() { + return mutable_operand(scatter_operand_count()); + } + + // Creates an instance of ScatterDimensionNumbers. + static ScatterDimensionNumbers MakeScatterDimNumbers( + absl::Span update_window_dims, + absl::Span inserted_window_dims, + absl::Span scatter_dims_to_operand_dims, + int64_t index_vector_dim); + // Returns the dump string of the given scatter dimension numbers. + static std::string ScatterDimensionNumbersToString( + const ScatterDimensionNumbers& dim_numbers); + // Prints the dump string of the given scatter dimension numbers. + static void PrintScatterDimensionNumbers( + Printer* printer, const ScatterDimensionNumbers& dim_numbers); + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kScatter; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + std::unique_ptr scatter_dimension_numbers_; + bool indices_are_sorted_; + bool unique_indices_; +}; + +class HloIotaInstruction : public HloInstruction { + public: + explicit HloIotaInstruction(const Shape& shape, int64_t iota_dimension); + + // Returns the dimension sizes or numbers associated with this instruction. + int64_t iota_dimension() const { return iota_dimension_; } + absl::Span dimensions() const override { + return absl::MakeConstSpan(&iota_dimension_, 1); + } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kIota; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t iota_dimension_; +}; + +class HloDotInstruction : public HloInstruction { + public: + // Creates a dot op with operands 'lhs' and 'rhs' with contracting and batch + // dimensions specified in 'dimension_numbers'. + explicit HloDotInstruction(const Shape& shape, HloInstruction* lhs, + HloInstruction* rhs, + const DotDimensionNumbers& dimension_numbers, + const PrecisionConfig& precision_config); + + // Returns data on the dimension numbers used for a dot operation. + const DotDimensionNumbers& dot_dimension_numbers() const { + return dot_dimension_numbers_; + } + + // Sets dimension numbers used for a dot operation. + DotDimensionNumbers* mutable_dot_dimension_numbers() { + return &dot_dimension_numbers_; + } + + // Returns the information used to tell the implementation information about + // what sort of precision is requested. The meaning of the field is backend + // specific. At the moment, it is only supported for kConvolution and kDot. + // Transformations on one kDot or kConvolution to another will preserve this + // information. Transformations to other HLOs will not preserve this + // information but it is presumed that the alternate lowering is strictly + // superior. + const PrecisionConfig& precision_config() const { return precision_config_; } + PrecisionConfig* mutable_precision_config() { return &precision_config_; } + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDot; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + // Describes the dimension numbers used for a dot. + DotDimensionNumbers dot_dimension_numbers_; + + // Information used to communicate to the implementation about the algorithm + // used to produce results. See the documentation on precision_config(). + PrecisionConfig precision_config_; +}; + +class HloDomainInstruction : public HloInstruction { + public: + explicit HloDomainInstruction( + const Shape& shape, HloInstruction* operand, + std::unique_ptr operand_side_metadata, + std::unique_ptr user_side_metadata); + + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + // Retrieves the operand side metadata of a kDomain instruction. + const DomainMetadata& operand_side_metadata() const { + return *operand_side_metadata_; + } + // Retrieves the user side metadata of a kDomain instruction. + const DomainMetadata& user_side_metadata() const { + return *user_side_metadata_; + } + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kDomain; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + std::unique_ptr operand_side_metadata_; + std::unique_ptr user_side_metadata_; +}; + +class HloGetDimensionSizeInstruction : public HloInstruction { + public: + explicit HloGetDimensionSizeInstruction(const Shape& shape, + HloInstruction* operand, + int64_t dimension); + + // Returns the dimension sizes or numbers associated with this instruction. + int64_t dimension() const { return dimension_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kGetDimensionSize; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t dimension_; +}; + +class HloSetDimensionSizeInstruction : public HloInstruction { + public: + explicit HloSetDimensionSizeInstruction(const Shape& shape, + HloInstruction* operand, + HloInstruction* val, + int64_t dimension); + + // Returns the dimension sizes or numbers associated with this instruction. + int64_t dimension() const { return dimension_; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kSetDimensionSize; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t dimension_; +}; + +class HloRngGetAndUpdateStateInstruction : public HloInstruction { + public: + explicit HloRngGetAndUpdateStateInstruction(const Shape& shape, + int64_t delta); + + // Returns the delta value. + int64_t delta() const { return delta_; } + void set_delta(int64_t delta) { delta_ = delta; } + // Returns a serialized representation of this instruction. + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kRngGetAndUpdateState; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + // Implementation for non-common logic of CloneWithNewOperands. + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + int64_t delta_; +}; + +class HloRngBitGeneratorInstruction : public HloInstruction { + public: + HloRngBitGeneratorInstruction(const Shape& shape, HloInstruction* state, + RandomAlgorithm algorithm); + + RandomAlgorithm algorithm() const { return algorithm_; } + HloInstructionProto ToProto() const override; + + static bool ClassOf(const HloInstruction* hlo) { + return hlo->opcode() == HloOpcode::kRngBitGenerator; + } + + private: + void PrintExtraAttributesImpl(AttributePrinter& printer, + const HloPrintOptions& options) const override; + bool IdenticalSlowPath( + const HloInstruction& other, + absl::FunctionRef + eq_computations) const override; + std::unique_ptr CloneWithNewOperandsImpl( + const Shape& shape, absl::Span new_operands, + HloCloneContext* context) const override; + + RandomAlgorithm algorithm_; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_INSTRUCTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module.h new file mode 100644 index 0000000000000000000000000000000000000000..c448cfa76a261d60c7b72dd9ec0a4c4405b620c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module.h @@ -0,0 +1,732 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_MODULE_H_ +#define XLA_HLO_IR_HLO_MODULE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/cord.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/dynamic_parameter_binding.h" +#include "xla/hlo/ir/hlo_clone_context.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_input_output_alias_config.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module_metadata.h" +#include "xla/hlo/ir/hlo_schedule.h" +#include "xla/iterator_util.h" +#include "xla/printer.h" +#include "xla/service/compilation_environments.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/name_uniquer.h" +#include "xla/xla.pb.h" +#include "tsl/lib/gtl/iterator_range.h" +#include "tsl/platform/logging.h" + +namespace xla { + +using LayoutCanonicalizationCallback = + std::function, Shape>>( + const HloModule& module)>; + +// Describes a compilation unit at the HLO level. +// +// HloModule is the top-level unit in the HLO IR. It corresponds to a whole +// "program". Running a module, from beginning to end, is the only way to run +// an XLA program. +// +// A module contains one "entry computation"; this HloComputation is like main() +// in a C program. The result of running the module is the result of running +// this computation. +// +// A module also contains some number of "nested computations". Each nested +// computation is attached to an HloInstruction within some other computation. +// The meaning of the nested computation depends on the instruction it's +// attached to. +class HloModule { + public: + // Constructor. + HloModule(const std::string& name, HloModuleConfig config); + // REQUIRED: + // - comp_envs must not be null. + HloModule(const std::string& name, HloModuleConfig config, + std::unique_ptr comp_envs); + virtual ~HloModule() = default; + + // Adds an entry computation to the module. A module can only have one entry + // computation. Returns a pointer to the newly added computation. + HloComputation* AddEntryComputation( + std::unique_ptr computation); + + // Same as the AddEntryComputation function above but the module's + // entry_computation_layout is updated to match the layout of the new entry + // computation. + HloComputation* AddEntryComputationWithLayouts( + std::unique_ptr computation); + + // Replaces the current entry computation with another computation. + // The new entry computation must be a computation that is already in the + // module. + void ReplaceEntryComputation(HloComputation* entry_computation); + + // Adds an embedded computation to the module. + HloComputation* AddEmbeddedComputation( + std::unique_ptr computation); + + // Removes an embedded computation. + Status RemoveEmbeddedComputation(HloComputation* to_remove); + + // Removes unused computations. + Status RemoveUnusedComputations(); + + // Marks duplicate fusions with the same name to be able to group them for + // analysis purposes (e.g. through Xprof). + void MarkFusionDuplications( + const absl::flat_hash_map& + replacements); + + // Replaces all uses of computations that are keys of 'replacements' with + // the corresponding values in 'replacements'. Replaces the entry computation, + // if applicable. + // + // This function iterates over all instructions in the module to find + // computations to replace. We could speed it up by keeping track of users of + // computations. + // + // N.B.: This function does not update the computations_ field of the + // HloModule with the newly added compututations. Therefore, along with + // invoking this function, if a replacement computation is not already present + // in module, it should be separately added into the module using + // `AddEmbeddedComputation`. + void ReplaceComputations( + const absl::flat_hash_map& + replacements); + + const std::string& name() const { return name_; } + void set_name(std::string name) { name_ = std::move(name); } + + // Move computations from the input module to this one, while ensuring that + // the names of instructions within the computations are unchanged. + void MoveComputationsFrom(HloModule* module, bool make_names_unique = false); + + // Returns a deep copy of this module including all computations. + std::unique_ptr Clone(const std::string& suffix = "clone") const; + std::unique_ptr Clone(const HloModuleConfig& config, + const std::string& suffix = "clone") const; + + // Performs a deep clone of the computation, by recursively cloning all + // the called computations as well. If the clone context is specified, it + // will be populated with the cloned object mappings. + HloComputation* DeepCloneComputation(HloComputation* computation, + HloCloneContext* context = nullptr); + + // Return a pointer to the entry computation of the module. + HloComputation* entry_computation() const { + CHECK_NE(nullptr, entry_computation_); + return entry_computation_; + } + + bool has_entry_computation() const { return entry_computation_ != nullptr; } + + // Returns the root instruction shape of entry computation. + // + // Precondition: entry_computation_ is not nullptr. + const Shape& result_shape() const { + CHECK_NE(nullptr, entry_computation_); + return entry_computation()->root_instruction()->shape(); + } + + // Creates the ComputationLayout which describes the current status of the HLO + // module entry computation. + ComputationLayout compute_computation_layout() const { + return ComputationLayout(entry_computation()->ComputeProgramShape(), + /*ignore_layouts=*/false); + } + + ComputationLayout* mutable_entry_computation_layout() { + return config_.mutable_entry_computation_layout(); + } + + const ComputationLayout& entry_computation_layout() const { + return config_.entry_computation_layout(); + } + + void set_frontend_attributes(FrontendAttributes frontend_attributes) { + frontend_attributes_ = std::move(frontend_attributes); + } + + void add_frontend_attributes(FrontendAttributes frontend_attributes) { + frontend_attributes_.mutable_map()->insert( + frontend_attributes.map().begin(), frontend_attributes.map().end()); + } + + const FrontendAttributes& frontend_attributes() const { + return frontend_attributes_; + } + + void set_use_auto_spmd_partitioning(bool use) { + use_auto_spmd_partitioning_ = use; + } + + bool use_auto_spmd_partitioning() const { + return use_auto_spmd_partitioning_; + } + + // Based on module's entry_computation sharded shapes, + // layout_canonicalization_callback_ computes and + // returns for module's entry computation. + // argument_layouts is std::vector and results_layout is Shape. + // layout_canonicalization_callback_ is used only when + // use_auto_spmd_partitioning_ = true. + void set_layout_canonicalization_callback( + LayoutCanonicalizationCallback callback) { + layout_canonicalization_callback_ = std::move(callback); + } + + LayoutCanonicalizationCallback layout_canonicalization_callback() const { + return layout_canonicalization_callback_; + } + + // Generates a hash value of an HLO module. Hash considers + // information on opcode, shape, operands, and typically a root instruction. + // This function returns the same hash value for equivalent HLO modules, + // with respect to HloInstruction::Identical() method. + template + friend H AbslHashValue(H h, const HloModule& module) { + h = H::combine(std::move(h), module.entry_computation_layout()); + // Use MakeComputationSorted() instead of MakeComputationPostOrder() + // because naming may affect the order of MakeComputationPostOrder() but not + // MakeComputationSorted(). + auto computations = module.MakeComputationSorted(); + for (auto* computation : computations) { + h = H::combine(std::move(h), *computation); + } + return H::combine(std::move(h), computations.size()); + } + + // Gets the computations in this module. + // + // Returns a view of HloComputation*s, so you can iterate over this in the + // natural way: + // + // for (HloComputation* c : module->computations()) { ... } + // + tsl::gtl::iterator_range>::const_iterator>> + computations() const { + return {MakeUnwrappingIterator(computations_.begin()), + MakeUnwrappingIterator(computations_.end())}; + } + tsl::gtl::iterator_range>::iterator>> + computations() { + return {MakeUnwrappingIterator(computations_.begin()), + MakeUnwrappingIterator(computations_.end())}; + } + + // Similar as above, but return a filtered view of computations for specified + // `execution_threads`. Empty `execution_threads` list means all execution + // threads are included. + tsl::gtl::iterator_range>::const_iterator, + std::function>> + computations( + const absl::flat_hash_set& execution_threads) const { + // Pass execution_threads by value to the predicate to ensure it lives + // beyond this function. + std::function pred = + [execution_threads](const HloComputation* computation) { + if (execution_threads.empty()) { + return true; + } + return execution_threads.contains(computation->execution_thread()); + }; + return MakeFilteringUnwrappingIteratorRange(computations_.begin(), + computations_.end(), pred); + } + + // Returns the computation in this module that has the name `name`. Returns + // null if there is no such computation. + HloComputation* GetComputationWithName(absl::string_view name); + + // Gets the number of computations in this module. + int64_t computation_count() const { return computations_.size(); } + + // Returns the mutable computation for the given index. + HloComputation* mutable_computation(int64_t idx) { + CHECK(idx >= 0 && idx < computations_.size()); + return computations_[idx].get(); + } + + // Gets the number of instructions in this module. + int64_t instruction_count() const; + + // Deallocate removed instructions in each computation. + void Cleanup() { + for (auto& comp : computations_) { + comp->Cleanup(); + } + } + + // Compute and return a post order of all computations in the module. The sort + // is defined like so: if computation A has an instruction which calls + // computation B, then A will appear after B in the sort. + std::vector MakeComputationPostOrder() const { + return MakeComputationPostOrder({}); + } + // Similar as above but only returns computations with specified + // `execution_threads`. Empty `execution_threads` list means all execution + // threads are included. + std::vector MakeComputationPostOrder( + const absl::flat_hash_set& execution_threads) const; + // Same as MakeComputationPostOrder() but only returns the computations that + // are on specified `execution_threads` and are also found in the passed in + // allowList. Empty `execution_threads` list means all execution threads are + // included. + std::vector MakeComputationPostOrder( + const absl::flat_hash_set& execution_threads, + const absl::flat_hash_set& allow_list) const; + + // If config().content_aware_computation_sorting() is true, sorts computations + // by their contents, otherwise returns MakeComputationPostOrder(). + std::vector MakeComputationSorted() const { + return MakeComputationSorted({}); + } + // Same as above but only for specified `execution_threads`. Empty + // `execution_threads` list means all execution threads are included. + std::vector MakeComputationSorted( + const absl::flat_hash_set& execution_threads) const; + + // Gets the computations in this module which aren't for fusion nodes. + // + // Postcondition: All computations in the returned list have + // !IsFusionComputation(). + // + // Note: Callers can and do rely on the return value here being a *snapshot* + // of the module's non-fusion computations -- that is, it's OK to add or + // remove computations from a module while iterating over + // MakeNonfusionComputations(). + std::vector MakeNonfusionComputations() const { + return MakeNonfusionComputations({}); + } + // Same as above but only for specified `execution_threads`. Empty + // `execution_threads` list means all execution threads are included. + std::vector MakeNonfusionComputations( + const absl::flat_hash_set& execution_threads) const; + + // Same as MakeNonfusionComputations() but sorting computations by content. + std::vector MakeNonfusionComputationsSorted() const { + return MakeNonfusionComputationsSorted({}); + } + // Same as above but only for specified `execution_threads`. Empty + // `execution_threads` list means all execution threads are included. + std::vector MakeNonfusionComputationsSorted( + const absl::flat_hash_set& execution_threads) const; + + HloModuleConfig& config() { return config_; } + const HloModuleConfig& config() const { return config_; } + void set_config(const HloModuleConfig& config) { config_ = config; } + + bool is_dynamic() const { return is_dynamic_; } + void set_is_dynamic(bool is_dynamic) { is_dynamic_ = is_dynamic; } + + // Prints a string representation of the module. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + void Print(Printer* printer) const { + return Print(printer, HloPrintOptions::Default()); + } + void Print(Printer* printer, const HloPrintOptions& options) const; + + // Return a string representation of the module. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + std::string ToString() const { return ToString(HloPrintOptions::Default()); } + std::string ToString(const HloPrintOptions& options) const; + + // Returns a Cord representation of the module. + // + // (We express the default options using an overload rather than a default + // param because gdb ignores default params, but does resolve overloads.) + absl::Cord ToCord() const { return ToCord(HloPrintOptions::Default()); } + absl::Cord ToCord(const HloPrintOptions& options) const; + + // Convert an HloModule to or from a proto. + HloModuleProto ToProto() const; + static StatusOr> CreateFromProto( + const HloModuleProto& proto, const HloModuleConfig& module_config, + bool prohibit_empty_literal = true); + + // Convert an HloModule to or from a proto that includes module configuration + StatusOr ToProtoWithConfig() const; + static StatusOr> CreateFromProtoWithConfig( + const HloModuleProtoWithConfig& proto, + bool prohibit_empty_literal = true); + + // Creates and returns an HloModuleConfig with an appropriate program shape + // for the HLO module in the given proto. + static StatusOr CreateModuleConfigFromProto( + const HloModuleProto& module, const DebugOptions& debug_options, + const ExecutionOptions* execution_options = nullptr); + + // Creates and returns an HloModuleConfig with an appropriate program shape + // for the HLO module in the given proto. + static StatusOr CreateModuleConfigFromShape( + const ProgramShape& program_shape, const DebugOptions& debug_options, + const ExecutionOptions* execution_options = nullptr); + + // Outlines the given expression from the given computation. + // instructions_to_outline contains the instructions that form the expression. + // + // Precondition: instructions in instructions_to_outline are in topological + // order (root of outlined instructions last). TODO(jingyue): takes a set of + // instructions and topologically sorts them. + HloInstruction* OutlineExpressionFromComputation( + absl::Span instructions_to_outline, + const std::string& outlined_computation_name, + HloComputation* computation); + + // Returns a randomly generated uint64_t. + uint64_t RandomNew64() const; + + // Returns the NameUniquer for uniquing instruction names in this module. + NameUniquer& instruction_name_uniquer() { return instruction_name_uniquer_; } + + // Assign a new unique dense id for an instruction + int NewUniqueInstructionId() { + int result = next_unique_id_; + next_unique_id_++; + return result; + } + + // input_output_alias_config indicates the list of aliased buffers that are + // expected from the module. + HloInputOutputAliasConfig& input_output_alias_config() { + return input_output_alias_config_; + } + const HloInputOutputAliasConfig& input_output_alias_config() const { + return input_output_alias_config_; + } + + // buffer_donor_config_ indicates the set of input buffer donors that are + // expected from the module. + HloBufferDonorConfig& buffer_donor_config() { return buffer_donor_config_; } + const HloBufferDonorConfig& buffer_donor_config() const { + return buffer_donor_config_; + } + + // Returns an id that is unique to this module across all modules created over + // the lifetime of this process. + int unique_id() const { return unique_id_; } + + // Sets the schedule of the module to the given schedule. + Status set_schedule(HloSchedule schedule); + + // Clears the schedule of the module. + void clear_schedule() { schedule_.reset(); } + + // Returns true if the module has a schedule set. + bool has_schedule() const { return schedule_.has_value(); } + + // Returns the schedule of the module. CHECK fails if no schedule is set. + const HloSchedule& schedule() const { return *schedule_; } + HloSchedule& schedule() { return *schedule_; } + + HloComputation* AddComputationAndUnifyNamesAndIds( + std::unique_ptr computation, bool is_entry) { + computation->ClearUniqueIdInternal(); + for (auto* instruction : computation->instructions()) { + instruction->ClearUniqueIdInternal(); + } + return AddComputationInternal(std::move(computation), is_entry, + /*uniquify_identifiers=*/true, + /*preserve_entry_layouts=*/true); + } + + void SetAndUniquifyInstrName(HloInstruction* instr, absl::string_view name) { + instr->SetAndSanitizeName(name); + instr->UniquifyName(&instruction_name_uniquer_); + } + + Status CheckUniqueNamesAndIdsForComputationsAndInstructions() const; + + // Checks if this config has a list of entry parameters' HLO shardings for + // SPMD. + bool has_spmd_parameters_shardings() const { + return spmd_parameters_shardings_.has_value(); + } + + // Getter and setter for the list of entry parameters' HLO shardings for SPMD. + const std::vector& spmd_parameters_shardings() const { + CHECK(spmd_parameters_shardings_.has_value()); + return *spmd_parameters_shardings_; + } + void set_spmd_parameters_shardings( + const std::vector& shardings) { + spmd_parameters_shardings_ = shardings; + } + + // Checks if this config has the entry computation output's HLO sharding for + // SPMD. + bool has_spmd_output_sharding() const { + return spmd_output_sharding_.has_value(); + } + + // Getter and setter for the entry computation output's HLO shardings for + // SPMD. + const HloSharding& spmd_output_sharding() const { + CHECK(spmd_output_sharding_.has_value()); + return *spmd_output_sharding_; + } + void set_spmd_output_sharding(const HloSharding& sharding) { + spmd_output_sharding_ = sharding; + } + + // Describes a buffer to be used for cross program prefetching. + struct CrossProgramPrefetchInfo { + // The parameter to prefetch. + int64_t parameter; + // Index of the buffer within a tuple-typed parameter. + ShapeIndex index; + // Offset into alt memory where the cross program pretched buffer will be + // stored. + std::optional alt_memory_offset; + }; + + // Add a program argument to be prefetched across programs. + void AddCrossProgramPrefetch( + int64_t parameter, const ShapeIndex& index, + std::optional alt_memory_offset = std::nullopt) { + cross_program_prefetches_.emplace_back( + CrossProgramPrefetchInfo{parameter, index, alt_memory_offset}); + } + + Status SetCrossProgramPrefetchOffset(int64_t prefetch_index, int64_t offset) { + TF_RET_CHECK(prefetch_index < cross_program_prefetches_.size()); + auto& [parameter, index, optional_offset] = + cross_program_prefetches_[prefetch_index]; + TF_RET_CHECK(!optional_offset.has_value()); + optional_offset = offset; + return OkStatus(); + } + + // Get the list of program arguments to be prefetch across programs. + absl::Span CrossProgramPrefetches() const { + return cross_program_prefetches_; + } + + const HloModuleMetadata& metadata() const { return metadata_; } + HloModuleMetadata* metadata() { return &metadata_; } + + // Moves (not copies) metadata from this HloModule to `module`. To be used + // in cases like HloModuleGroup::ReplaceModule when metadata should be + // transferred out of a module before it's destroyed. + void MoveMetadataToModule(HloModule* module) { + module->metadata_ = std::move(metadata_); + } + + int64_t profile_version() const { return profile_version_; } + + void set_profile_version(int64_t profile_version) { + profile_version_ = profile_version; + } + + void add_profile_info(const HloModuleProto::ProfileInfo& profile_info) { + profile_info_list_.push_back(profile_info); + } + + void set_profile_info( + const std::vector& profile_info) { + profile_info_list_ = profile_info; + } + + const std::vector& profile_info() const { + return profile_info_list_; + } + + void set_autofdo_profile_key(HloModuleProto::ProfileType profile_type, + absl::string_view profile_key) { + autofdo_profile_keys_[profile_type] = std::string(profile_key); + } + + void set_autofdo_profile_keys( + const absl::flat_hash_map& + profile_keys) { + for (const auto& [profile_type, profile_key] : profile_keys) { + autofdo_profile_keys_[profile_type] = profile_key; + } + } + + const absl::flat_hash_map& + autofdo_profile_keys() const { + return autofdo_profile_keys_; + } + + bool has_module_autofdo_profiles() const { + return !autofdo_profile_keys_.empty(); + } + + void set_relative_speedup(double relative_speedup) { + relative_speedup_ = relative_speedup; + } + + // Sets the **unoptimized** fingerprint for the module. This fingerprint is + // prior to any optimizations. + void set_autofdo_fingerprint(absl::string_view fingerprint) { + autofdo_fingerprint_ = std::string(fingerprint); + } + + absl::string_view autofdo_fingerprint() const { return autofdo_fingerprint_; } + + CompilationEnvironments& comp_envs() const { return *comp_envs_; } + + // Get 128-bit fingerprint of the module by printing it using the given print + // options. + std::string GetFingerprint128(const HloPrintOptions& options = + HloPrintOptions::ModuleFingerprint()) const; + + // Describes a stack frame. + struct StackFrame { + std::string_view file_name; + std::string_view function_name; + int line = 0; + int column = 0; + + // 1-based index of the parent frame. + // 0 value indicates that the current frame is the root. + int parent_frame_id = 0; + + bool empty() const { + return line == 0 && column == 0 && file_name.empty() && + function_name.empty(); + } + }; + + // Getter for the specific stack frame. Argument is a 1-based index. + StackFrame get_stack_frame(int id) const; + + private: + HloComputation* AddComputationInternal( + std::unique_ptr computation, bool is_entry, + bool uniquify_identifiers, bool preserve_entry_layouts); + + std::string name_; + HloModuleConfig config_; + HloComputation* entry_computation_ = nullptr; + std::vector> computations_; + + // Random number generator engine to use when generating random numbers per + // HloModule compilation. + // TODO(b/25995601): Replace with better seed setting or dev/random for + // where we don't need deterministic execution. + mutable std::mt19937_64 rng_{42}; + mutable absl::Mutex rng_mutex_; + + // Unique name generator for computation and instruction names, which are + // unique per module. + NameUniquer computation_name_uniquer_{/*separator=*/"."}; + NameUniquer instruction_name_uniquer_{/*separator=*/"."}; + int next_unique_id_ = 0; + + // Used to keep track of the next unique module id that should be assigned. + static std::atomic next_unique_module_id_; + // A unique id to label modules with. + const int unique_id_; + + // The HloSchedule of the module. The schedule if it exists contains a + // sequential order of instructions for each non-fusion computation in the + // module. + std::optional schedule_; + + // alias_config indicates the alias information of input/output buffers that + // are expected from the module. + HloInputOutputAliasConfig input_output_alias_config_; + + // buffer_donor_config_ indicates the donor information of input buffers that + // are expected from the module. + HloBufferDonorConfig buffer_donor_config_; + + // Attributes passed from the frontend to give hints to the backend about + // how to compile this HLO. + FrontendAttributes frontend_attributes_; + + // The HLO shardings of the entry computation's parameters for + // SPMD-partitioned programs. + std::optional> spmd_parameters_shardings_; + + // The HLO sharding of the entry computation's output (root) for + // SPMD-partitioned programs. + std::optional spmd_output_sharding_; + + // Arguments to be prefetched across programs. + std::vector cross_program_prefetches_; + + // Metadata for this module, such as its canonical id and the HLO passes run. + HloModuleMetadata metadata_; + + // True if the module contains dynamic computation. + bool is_dynamic_ = false; + + // Optional compilation profile handle. + int64_t profile_version_ = 0; + + // An array of ProfileInfo specifying what optimization profiles this module + // contains, along with the relative speedups. + std::vector profile_info_list_; + + // Relative speedup of best config compared to default config. + double relative_speedup_; + + // The unoptimized module fingerprint. + std::string autofdo_fingerprint_; + + // The keys used to retrieve the optimization profiles this module is compiled + // with, per profile type. + absl::flat_hash_map + autofdo_profile_keys_; + + bool use_auto_spmd_partitioning_ = false; + + // Layout canonicalization callback, used only when + // use_auto_spmd_partitioning_ = true. + LayoutCanonicalizationCallback layout_canonicalization_callback_; + + // Compilation environments (protos that carry command line flags and + // environment variables). + std::unique_ptr comp_envs_ = + std::make_unique(); + + // Stack frame indexes flat representation. + std::optional stack_frame_index_; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_MODULE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_group.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_group.h new file mode 100644 index 0000000000000000000000000000000000000000..c9afd22ec44e6010795eebd097be18492004581f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_group.h @@ -0,0 +1,117 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_MODULE_GROUP_H_ +#define XLA_HLO_IR_HLO_MODULE_GROUP_H_ + +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo.pb.h" + +namespace xla { + +// An abstraction representing a ordered set of HLO module built to run +// concurrently across different devices. +class HloModuleGroup { + public: + // Construct an empty module group. + explicit HloModuleGroup(absl::string_view name) : name_(name) {} + + // Construct a module group containing a single module. + explicit HloModuleGroup(std::unique_ptr module); + + // Construct a module group containing any number of modules. + HloModuleGroup(absl::string_view name, + absl::Span> modules); + HloModuleGroup(absl::string_view name, + std::vector>&& modules); + + // Returns the modules contained in the group. + const std::vector& modules() const { return module_ptrs_; } + + // Returns a module at a particular index. + HloModule& module(int index) const { return *module_ptrs_.at(index); } + + // Add a module to the back of vector of modules in the group. + void push_back(std::unique_ptr module); + + // Replaces the existing module at the given index with the given module. The + // existing module is discarded. + void ReplaceModule(int index, std::unique_ptr module); + + // Moves all modules from the group into the returned vector. After this + // method runs, the module group will be empty. + std::vector> ConsumeModules(); + + std::string name() const { return name_; } + + std::string ToString() const; + + // Deallocate removed instructions in each module. + void Cleanup() { + for (auto& module : modules_) { + module->Cleanup(); + } + } + + template + friend H AbslHashValue(H h, const HloModuleGroup& group) { + for (auto& module : group.modules_) { + h = H::combine(std::move(h), *module); + } + return H::combine(std::move(h), group.modules_.size()); + } + + // Serialize the module group to/from a proto. + HloModuleGroupProto ToProto() const; + static StatusOr CreateFromProto( + const HloModuleGroupProto& proto, + absl::Span module_configs); + + // Returns the number of modules in the module group. + int size() const { return modules_.size(); } + + // Returns true if there are no modules in the module group. + bool empty() const { return modules_.empty(); } + + absl::string_view cache_key() const { return cache_key_; } + void set_cache_key(absl::string_view cache_key) { + cache_key_ = std::string(cache_key); + } + + private: + std::string name_; + + // Vector of modules as std::unique_ptrs. + std::vector> modules_; + + // Vector of modules as normal pointers. This vector is kept in sync with + // modules_ as modules are added to the group with push_back. + std::vector module_ptrs_; + + std::string cache_key_; +}; + +std::ostream& operator<<(std::ostream& out, const HloModuleGroup& group); + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_MODULE_GROUP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..27fcc5361348e52a5b07b9122e88a15d43858ee5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_module_metadata.h @@ -0,0 +1,134 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_MODULE_METADATA_H_ +#define XLA_HLO_IR_HLO_MODULE_METADATA_H_ + +#include +#include +#include +#include + +#include "xla/service/hlo.pb.h" +#include "xla/status_macros.h" +#include "xla/util.h" +#include "tsl/platform/env.h" + +namespace xla { + +// Wrapper class for HloModuleMetadataProto to avoid allowing callers to mutate +// arbitrary fields. Specifically, callers cannot set timestamps or ids or +// set the fields of any pass not currently running. +class HloModuleMetadata { + public: + explicit HloModuleMetadata(tsl::Env* env) : env_(env) {} + + const HloModuleMetadataProto& proto() const { return module_metadata_; } + + // Creates a new HloPassMetadata. All calls to RecordPassStart should be + // matched by a later call to RecordPassEnd. + void RecordPassStart(); + + // Marks the currently running pass as finished. Returns NotFound if metadata + // for the currently running pass cannot be found. + Status RecordPassEnd(); + + const std::optional& prepartitioning_metadata() + const { + return prepartitioning_metadata_; + } + void set_prepartitioning_metadata( + const HloModuleMetadata& prepartitioning_metadata); + + // Setters for HloModuleMetadataProto. + void set_module_group_name(const std::string& name) { + module_metadata_.set_module_group_name(name); + } + void set_canonical_module_id(int64_t id) { + module_metadata_.set_canonical_module_id(id); + } + void add_partitioned_module_id(int64_t id) { + module_metadata_.add_partitioned_module_ids(id); + } + + StatusOr current_pass_id() { + TF_ASSIGN_OR_RETURN(HloPassMetadata * pass_metadata, + GetCurrentHloPassMetadata()); + return pass_metadata->pass_id(); + } + + // Setters for the current HloPassMetadata. + Status set_current_pass_name(const std::string& pass_name) { + return MutateCurrentHloPassMetadata( + [&pass_name](HloPassMetadata* pass_metadata) { + pass_metadata->set_pass_name(pass_name); + }); + } + Status set_current_pass_pipeline_name(const std::string& pipeline_name) { + return MutateCurrentHloPassMetadata( + [&pipeline_name](HloPassMetadata* pass_metadata) { + pass_metadata->set_pipeline_name(pipeline_name); + }); + } + Status add_current_pass_dump_filename(const std::string& dump_filename) { + return MutateCurrentHloPassMetadata( + [&dump_filename](HloPassMetadata* pass_metadata) { + pass_metadata->add_dump_filenames(dump_filename); + }); + } + Status set_current_pass_module_changed(bool module_changed) { + return MutateCurrentHloPassMetadata( + [&module_changed](HloPassMetadata* pass_metadata) { + pass_metadata->set_module_changed(module_changed); + }); + } + Status set_current_pass_module_id(int64_t module_id) { + return MutateCurrentHloPassMetadata( + [&module_id](HloPassMetadata* pass_metadata) { + pass_metadata->set_module_id(module_id); + }); + } + Status add_current_pass_module_group_module_id(int64_t module_id) { + return MutateCurrentHloPassMetadata( + [&module_id](HloPassMetadata* pass_metadata) { + pass_metadata->add_module_group_module_ids(module_id); + }); + } + + private: + // Gets mutable metadata for the currently running pass. If passes are nested, + // finds the deepest one still running. Returns NotFound if metadata for the + // currently running pass cannot be found. + StatusOr GetCurrentHloPassMetadata(); + + Status MutateCurrentHloPassMetadata( + absl::FunctionRef mutator); + + HloModuleMetadataProto module_metadata_; + tsl::Env* env_; + int64_t next_pass_id_ = 1; + + // Stack of metadata for passes that are currently running. Size > 1 iff + // passes are nested. + std::vector running_passes_; + + // Metadata from before the module was partitioned, if applicable. + std::optional prepartitioning_metadata_ = + std::nullopt; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_MODULE_METADATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_op_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_op_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..ebf7f51e597d2133a7a3d7bd64c187f63549aa73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_op_metadata.h @@ -0,0 +1,27 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_OP_METADATA_H_ +#define XLA_HLO_IR_HLO_OP_METADATA_H_ + +#include + +#include "xla/xla_data.pb.h" + +namespace xla { +std::string OpMetadataToString(const OpMetadata& metadata); +} // namespace xla + +#endif // XLA_HLO_IR_HLO_OP_METADATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_opcode.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_opcode.h new file mode 100644 index 0000000000000000000000000000000000000000..0bf4751cd5bc6b38954c269879a8bc168a958736 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_opcode.h @@ -0,0 +1,232 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_OPCODE_H_ +#define XLA_HLO_IR_HLO_OPCODE_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// High-level optimizer instruction opcodes -- these are linear-algebra level +// opcodes. They are a flattened form of the UnaryOp, BinaryOp, ... opcodes +// present in the XLA service protobuf. +// +// See the XLA documentation for the semantics of each opcode. +// +// Each entry has the format: +// (enum_name, opcode_name, arity) +// +// Note: Do not use ':' in opcode names. It is used as a special character +// in these places: +// - In extended opcode strings (HloInstruction::ExtendedOpcodeString()), to +// separate the opcode from the fusion kind +// - In fully qualified names (HloInstruction::FullyQualifiedName()), to +// separate the qualifiers (name of the computation and potentially the +// fusion instruction) from the name +// +// If you change one of these opcodes, please make the corresponding change to +// the MHLO opset to keep both opsets synchronized. +// LINT.IfChange +#define HLO_OPCODE_LIST(V) \ + /* go/keep-sorted start */ \ + V(kAbs, "abs", 1) \ + V(kAdd, "add", 2) \ + V(kAddDependency, "add-dependency", 2) \ + V(kAfterAll, "after-all", kHloOpcodeIsVariadic) \ + V(kAllGather, "all-gather", kHloOpcodeIsVariadic) \ + V(kAllGatherDone, "all-gather-done", 1) \ + V(kAllGatherStart, "all-gather-start", kHloOpcodeIsVariadic) \ + V(kAllReduce, "all-reduce", kHloOpcodeIsVariadic) \ + V(kAllReduceDone, "all-reduce-done", 1) \ + V(kAllReduceStart, "all-reduce-start", kHloOpcodeIsVariadic) \ + V(kAllToAll, "all-to-all", kHloOpcodeIsVariadic) \ + V(kAnd, "and", 2) \ + V(kAsyncDone, "async-done", 1) \ + V(kAsyncStart, "async-start", kHloOpcodeIsVariadic) \ + V(kAsyncUpdate, "async-update", 1) \ + V(kAtan2, "atan2", 2) \ + V(kBatchNormGrad, "batch-norm-grad", 5) \ + V(kBatchNormInference, "batch-norm-inference", 5) \ + V(kBatchNormTraining, "batch-norm-training", 3) \ + V(kBitcast, "bitcast", 1) \ + V(kBitcastConvert, "bitcast-convert", 1) \ + V(kBroadcast, "broadcast", 1) \ + V(kCall, "call", kHloOpcodeIsVariadic) \ + V(kCbrt, "cbrt", 1) \ + V(kCeil, "ceil", 1) \ + V(kCholesky, "cholesky", 1) \ + V(kClamp, "clamp", 3) \ + V(kClz, "count-leading-zeros", 1) \ + V(kCollectivePermute, "collective-permute", kHloOpcodeIsVariadic) \ + V(kCollectivePermuteDone, "collective-permute-done", 1) \ + V(kCollectivePermuteStart, "collective-permute-start", kHloOpcodeIsVariadic) \ + V(kCompare, "compare", 2) \ + V(kComplex, "complex", 2) \ + V(kConcatenate, "concatenate", kHloOpcodeIsVariadic) \ + V(kConditional, "conditional", kHloOpcodeIsVariadic) \ + V(kConstant, "constant", 0) \ + V(kConvert, "convert", 1) \ + V(kConvolution, "convolution", 2) \ + V(kCopy, "copy", 1) \ + V(kCopyDone, "copy-done", 1) \ + V(kCopyStart, "copy-start", 1) \ + V(kCos, "cosine", 1) \ + V(kCustomCall, "custom-call", kHloOpcodeIsVariadic) \ + V(kDivide, "divide", 2) \ + V(kDomain, "domain", 1) \ + V(kDot, "dot", 2) \ + V(kDynamicReshape, "dynamic-reshape", kHloOpcodeIsVariadic) \ + V(kDynamicSlice, "dynamic-slice", kHloOpcodeIsVariadic) \ + V(kDynamicUpdateSlice, "dynamic-update-slice", kHloOpcodeIsVariadic) \ + V(kExp, "exponential", 1) \ + V(kExpm1, "exponential-minus-one", 1) \ + V(kFft, "fft", 1) \ + V(kFloor, "floor", 1) \ + V(kFusion, "fusion", kHloOpcodeIsVariadic) \ + V(kGather, "gather", 2) \ + V(kGetDimensionSize, "get-dimension-size", 1) \ + V(kGetTupleElement, "get-tuple-element", 1) \ + V(kImag, "imag", 1) \ + V(kInfeed, "infeed", 1) \ + V(kIota, "iota", 0) \ + V(kIsFinite, "is-finite", 1) \ + V(kLog, "log", 1) \ + V(kLog1p, "log-plus-one", 1) \ + V(kLogistic, "logistic", 1) \ + V(kMap, "map", kHloOpcodeIsVariadic) \ + V(kMaximum, "maximum", 2) \ + V(kMinimum, "minimum", 2) \ + V(kMultiply, "multiply", 2) \ + V(kNegate, "negate", 1) \ + V(kNot, "not", 1) \ + V(kOptimizationBarrier, "opt-barrier", 1) \ + V(kOr, "or", 2) \ + V(kOutfeed, "outfeed", 2) \ + V(kPad, "pad", 2) \ + V(kParameter, "parameter", 0) \ + V(kPartitionId, "partition-id", 0) \ + V(kPopulationCount, "popcnt", 1) \ + V(kPower, "power", 2) \ + V(kReal, "real", 1) \ + V(kRecv, "recv", 1) \ + V(kRecvDone, "recv-done", 1) \ + V(kReduce, "reduce", kHloOpcodeIsVariadic) \ + V(kReducePrecision, "reduce-precision", 1) \ + V(kReduceScatter, "reduce-scatter", kHloOpcodeIsVariadic) \ + V(kReduceWindow, "reduce-window", kHloOpcodeIsVariadic) \ + V(kRemainder, "remainder", 2) \ + V(kReplicaId, "replica-id", 0) \ + V(kReshape, "reshape", 1) \ + V(kReverse, "reverse", 1) \ + V(kRng, "rng", kHloOpcodeIsVariadic) \ + V(kRngBitGenerator, "rng-bit-generator", 1) \ + V(kRngGetAndUpdateState, "rng-get-and-update-state", 0) \ + V(kRoundNearestAfz, "round-nearest-afz", 1) \ + V(kRoundNearestEven, "round-nearest-even", 1) \ + V(kRsqrt, "rsqrt", 1) \ + V(kScatter, "scatter", kHloOpcodeIsVariadic) \ + V(kSelect, "select", 3) \ + V(kSelectAndScatter, "select-and-scatter", 3) \ + V(kSend, "send", 2) \ + V(kSendDone, "send-done", 1) \ + V(kSetDimensionSize, "set-dimension-size", 2) \ + V(kShiftLeft, "shift-left", 2) \ + V(kShiftRightArithmetic, "shift-right-arithmetic", 2) \ + V(kShiftRightLogical, "shift-right-logical", 2) \ + V(kSign, "sign", 1) \ + V(kSin, "sine", 1) \ + V(kSlice, "slice", 1) \ + V(kSort, "sort", kHloOpcodeIsVariadic) \ + V(kSqrt, "sqrt", 1) \ + V(kStochasticConvert, "stochastic-convert", 2) \ + V(kSubtract, "subtract", 2) \ + V(kTan, "tan", 1) \ + V(kTanh, "tanh", 1) \ + V(kTopK, "topk", 1) \ + V(kTranspose, "transpose", 1) \ + V(kTriangularSolve, "triangular-solve", 2) \ + V(kTuple, "tuple", kHloOpcodeIsVariadic) \ + V(kWhile, "while", 1) \ + V(kXor, "xor", 2) \ + /* go/keep-sorted end */ +// LINT.ThenChange(../../mlir_hlo/mhlo/IR/hlo_ops.td) + +enum class HloOpcode { +#define DECLARE_ENUM(enum_name, opcode_name, ...) enum_name, + HLO_OPCODE_LIST(DECLARE_ENUM) +#undef DECLARE_ENUM +}; + +// Arity value that denotes that an operator is variadic. +enum { + kHloOpcodeIsVariadic = -1, +}; + +// Returns a string representation of the opcode. +absl::string_view HloOpcodeString(HloOpcode opcode); + +// Retrieves the opcode enum by name if the opcode exists. +StatusOr StringToHloOpcode(absl::string_view opcode_name); + +inline std::ostream& operator<<(std::ostream& os, HloOpcode opcode) { + return os << HloOpcodeString(opcode); +} + +// Returns true iff the given opcode is a comparison operation. +bool HloOpcodeIsComparison(HloOpcode opcode); + +// Returns true iff the given opcode has variadic operands. +bool HloOpcodeIsVariadic(HloOpcode opcode); + +// Returns the arity of opcode. If the opcode is variadic, +// returns nullopt. +std::optional HloOpcodeArity(HloOpcode opcode); + +// Returns true if the given opcode is one of kAsyncStart, kAsyncUpdate, or +// kAsyncDone. +bool HloOpcodeIsAsync(HloOpcode opcode); + +// True if the op takes two arguments and order doesn't matter. +inline bool HloOpcodeIsBinaryCommutative(HloOpcode opcode) { + switch (opcode) { + case HloOpcode::kAdd: + case HloOpcode::kMultiply: + case HloOpcode::kMaximum: + case HloOpcode::kMinimum: + case HloOpcode::kAnd: + case HloOpcode::kOr: + case HloOpcode::kXor: + return true; + default: + return false; + } +} + +// Returns the number of HloOpcode values. +inline constexpr uint32_t HloOpcodeCount() { +#define HLO_COUNT_ONE(...) +1 +#define HLO_XLIST_LENGTH(list) list(HLO_COUNT_ONE) + return HLO_XLIST_LENGTH(HLO_OPCODE_LIST); +} + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_OPCODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_reachability.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_reachability.h new file mode 100644 index 0000000000000000000000000000000000000000..bdceed946180dc3af7dd1a70127587737f072ad2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_reachability.h @@ -0,0 +1,211 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_REACHABILITY_H_ +#define XLA_HLO_IR_HLO_REACHABILITY_H_ + +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/types.h" + +namespace xla { + +// A class for representing reachability between HloInstructions. +// +// It has an adjacency matrix and it is up to the user of the class to set the +// adjacency matrix such that it represents reachability, i.e. such that it is +// transitive. That the graph be transitive is thus not an invariant of this +// class, but it is required for the name of the class and its methods to make +// sense. +class HloReachabilityMap { + public: + using Index = size_t; + + // Sets up a graph with no edges and where the nodes correspond to the given + // instructions. + explicit HloReachabilityMap( + absl::Span instructions); + + // Computes and returns the reachability between HLO instructions in the + // computation. The returned HloReachabilityMap is constructed such that + // HloReachabilityMap::IsReachable(a, b) returns true iff there exists a + // directed path (from producer to consumer) from 'a' to 'b'. Both data + // dependencies (operands) and control dependencies are considered for + // reachability. Trivially an instruction is reachable from itself. + static std::unique_ptr Build( + const HloComputation* computation); + + // Similar to the above Build operation except that it tries to identify + // paths between instructions that do not contain control instructions + // and multiple operands, i.e., b is_reachable a == true iff + // b = f(f(f(f(f(a), constant), constant), constant). + // Further, the only ops allowed in a path are basic math operations such + // as add, sub, mul, div. + static std::unique_ptr BuildWithRestrictions( + const HloComputation* computation, + absl::FunctionRef*)> + add_dependencies); + + // Set the reachability set of 'instruction' to the union of the reachability + // sets of 'inputs'. Upon return, IsReachable(x, instruction) where + // 'x' is not 'instruction' will return true iff IsReachable(x, input) is true + // for some 'input' in 'inputs'. Also sets 'instruction' to be reachable from + // itself. Returns whether the reachability set of 'instruction' changed. + // + // !!! THIS FUNCTION DOES NOT COMPUTE REACHABILITY !!! It sets the adjacency + // vector in the internal graph of this HloReachabilityMap for the given + // instruction and does not transitively update any other part of the + // adjacency matrix. + bool SetReachabilityToUnion(absl::Span inputs, + const HloInstruction* instruction); + + // As above, but faster because it does not check if the reachability changed. + void FastSetReachabilityToUnion( + absl::Span inputs, + const HloInstruction* instruction); + // As above, but use Index instead if it's already looked up which is even + // faster since no hash map lookup will occur. + void FastSetReachabilityToUnion(absl::Span input_indices, + Index index); + + Index GetIndex(const HloInstruction* instruction) const { + return indices_.at(GetKey(instruction)); + } + + // Sets entry so that IsReachable(a, b) will return true + // + // !!! THIS FUNCTION DOES NOT COMPUTE REACHABILITY !!! It sets the adjacency + // matrix in the internal graph of this HloReachabilityMap to have an edge + // from a to b and does not transitively update any other part of the + // adjacency matrix. + void SetReachable(const HloInstruction* a, const HloInstruction* b) { + SetReachable(GetIndex(a), GetIndex(b)); + } + void SetReachable(Index a, Index b) { bit_sets_[b].Set(a); } + + // Updates the given reachability map after the immediate predecessor set + // (operands and control predecessors) of 'instruction' has changed. + void UpdateReachabilityThroughInstruction(const HloInstruction* instruction); + + // Returns true if "b" is reachable from "a" + // + // Note that this function only correctly answers queries about reachability + // if the set of edges that have been provided to this class are transitive. + bool IsReachable(const HloInstruction* a, const HloInstruction* b) const { + return IsReachable(GetIndex(a), GetIndex(b)); + } + bool IsReachable(Index a, Index b) const { return bit_sets_[b].Get(a); } + + // Returns true if "b" is reachable from "a" or "a" is reachable from "b" + // + // Note that this function only correctly answers queries about reachability + // if the set of edges that have been provided to this class are transitive. + bool IsConnected(const HloInstruction* a, const HloInstruction* b) const { + return IsConnected(GetIndex(a), GetIndex(b)); + } + bool IsConnected(Index a, Index b) const { + return IsReachable(a, b) || IsReachable(b, a); + } + + // Checks if an instruction is in the Reachability map. + bool IsPresent(const HloInstruction* instruction) const { + return indices_.contains(GetKey(instruction)); + } + + // Replace the instruction "original" with "replacement" in the reachability + // map. + void Replace(const HloInstruction* original, + const HloInstruction* replacement); + + private: + // A dynamically sized bit-set implementation specialized for this use case + // providing fast bitwise OR (not available in tsl::gtl::BitMap). + class BitSet { + public: + BitSet() = default; + explicit BitSet(size_t size) + : size_(size), vector_((size + kBits - 1) / kBits, 0) {} + + // Returns the bit at the given index. + bool Get(Index index) const { + DCHECK(index >= 0 && index < size_); + return vector_[index / kBits] & (1ull << (index % kBits)); + } + + // Sets the bit at the given index. + void Set(Index index) { + DCHECK(index >= 0 && index < size_); + vector_[index / kBits] |= 1ull << (index % kBits); + } + + // Sets this bit-set to union of this bit-set and `other`. + void operator|=(const BitSet& other) { + for (size_t i = 0; i < vector_.size(); ++i) { + vector_[i] |= other.vector_[i]; + } + } + + // Sets the bitvector to all zeros. + void SetToZero() { absl::c_fill(vector_, 0); } + + bool operator==(const BitSet& other) const { + return vector_ == other.vector_; + } + bool operator!=(const BitSet& other) const { return !(*this == other); } + + private: + using Word = uint64_t; + static constexpr size_t kBits = 64; + + size_t size_; // Number of bits in the set. + std::vector vector_; + }; + + using Key = std::pair; // module ID, instruction ID. + static Key GetKey(const HloInstruction* instruction) { + return {instruction->GetModule()->unique_id(), instruction->unique_id()}; + } + + // Helper for SetReachabilityToUnion/FastSetReachabilityToUnion. + void SetReachabilityToUnionHelper( + absl::Span inputs, Index index); + void SetReachabilityToUnionHelper(absl::Span input_indices, + Index index); + + // Map from instruction to index. The index is used for bit_set_ and the bits + // within a BitSet. + absl::flat_hash_map indices_; + + // Bit-sets holding the reachability to each instruction. The bit-set for + // instruction X includes ones for each instruction which X is reachable from. + std::vector bit_sets_; + + // A temporary used by SetReachabilityToUnion to avoid an allocation with each + // call to the method. + BitSet tmp_bit_set_; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_REACHABILITY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_schedule.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_schedule.h new file mode 100644 index 0000000000000000000000000000000000000000..597ed2881a9eb5de0df8b328a733d6502476df89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_schedule.h @@ -0,0 +1,221 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_SCHEDULE_H_ +#define XLA_HLO_IR_HLO_SCHEDULE_H_ + +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/status.h" + +namespace xla { + +class HloModule; + +// Class representing a sequence of HLO instructions such as the sequential +// execution order of an HLO computation. +class HloInstructionSequence { + public: + HloInstructionSequence() = default; + explicit HloInstructionSequence( + absl::Span instructions) { + for (HloInstruction* instruction : instructions) { + push_back(instruction); + } + } + + // Adds the instruction to the end of the sequence. + void push_back(HloInstruction* instruction) { + instruction_sequence_.push_back(instruction); + id_sequence_.push_back(instruction->unique_id()); + } + + // Removes the instruction from the sequence. + void remove_instruction(HloInstruction* instruction) { + auto instruction_it = std::find(instruction_sequence_.begin(), + instruction_sequence_.end(), instruction); + if (instruction_it != instruction_sequence_.end()) { + auto id_it = std::find(id_sequence_.begin(), id_sequence_.end(), + instruction->unique_id()); + instruction_sequence_.erase(instruction_it); + id_sequence_.erase(id_it); + } + } + + // Replaces the old instruction with the new instruction in the sequence. + void replace_instruction(HloInstruction* old_instruction, + HloInstruction* new_instruction) { + auto instruction_it = + std::find(instruction_sequence_.begin(), instruction_sequence_.end(), + old_instruction); + auto id_it = std::find(id_sequence_.begin(), id_sequence_.end(), + old_instruction->unique_id()); + CHECK(instruction_it != instruction_sequence_.end()) + << "Do not find instruction id " << old_instruction->unique_id(); + CHECK(id_it != id_sequence_.end()); + *instruction_it = new_instruction; + *id_it = new_instruction->unique_id(); + } + + // Clears the sequence of all instructions. + void clear() { + instruction_sequence_.clear(); + id_sequence_.clear(); + } + + int64_t size() const { return instruction_sequence_.size(); } + + // Returns the sequence of HLO instructions. + const std::vector& instructions() const { + return instruction_sequence_; + } + + // Returns the unique IDs of the instructions in the sequence (in order). + const std::vector& ids() const { return id_sequence_; } + + private: + // The sequence as HloInstructions. + std::vector instruction_sequence_; + + // The sequence of HLO instructions, represented by their unique IDs. The + // sequence is stored as both HloInstructions and unique IDs because the + // sequence may be referenced after transformations to the HLO graph and HLO + // pointers can be invalidated or recycled in this process (see + // HloSchedule::Update). + std::vector id_sequence_; +}; + +// A class representing a sequential schedule of instructions for an HLO +// module. A complete HLO schedule contains an instruction sequence for every +// non-fusion computation in the HLO module. +class HloSchedule { + public: + explicit HloSchedule(const HloModule* module) : module_(module) {} + + // (De)Serialize an HloSchedule to/from a HloScheduleProto. + static StatusOr CreateFromProto(const HloModule* module, + const HloScheduleProto& proto); + StatusOr ToProto() const; + + // Returns a reference to the sequence for the given computation. + const HloInstructionSequence& sequence( + const HloComputation* computation) const; + + // Returns the sequence for the given computation. An empty sequence is + // created if none exists for the computation. + HloInstructionSequence& GetOrCreateSequence( + const HloComputation* computation); + + // Sets the sequence for the given computation to the given sequence. + void set_sequence(const HloComputation* computation, + absl::Span sequence); + void set_sequence(const HloComputation* computation, + HloInstructionSequence sequence); + + // Returns a map from HloComputation unique ID to instruction sequence. The + // map contains all sequences in the schedule. + const absl::flat_hash_map& sequences() + const { + return sequences_; + } + + absl::flat_hash_map num_sequences_by_execution_thread() + const; + + // Returns true if the schedule has a sequence for the given computation. + bool is_computation_scheduled(const HloComputation* computation) const { + return sequences_.contains(computation->unique_id()); + } + + // Removes the computation from the sequences. + void remove_computation(const HloComputation* computation) { + auto it = sequences_.find(computation->unique_id()); + CHECK(it != sequences_.end()); + sequences_.erase(it); + execution_threads_.erase(computation->unique_id()); + } + + // Removes the instruction from the computation's sequence. + void remove_instruction(const HloComputation* computation, + HloInstruction* instruction) { + sequences_[computation->unique_id()].remove_instruction(instruction); + } + + // Replaces the old instruction with the new instruction in the computation's + // sequence. + void replace_instruction(const HloComputation* computation, + HloInstruction* old_instruction, + HloInstruction* new_instruction) { + sequences_[computation->unique_id()].replace_instruction(old_instruction, + new_instruction); + } + + // Updates the schedule for specified threads such that it is (again) a valid + // schedule for the module. This is used to update a schedule after the HLO + // module has been transformed in some way. In general, the only + // transformations to the module for which a schedule can be updated is the + // addition or removal of instructions and computations. + // + // Instructions in the module which also exist in the given schedule will + // remain in the same order in the updated schedule. Instructions which exist + // in the module but not in the given schedule will be placed as early as + // possible in the updated schedule. + Status Update( + const absl::flat_hash_set& execution_threads = {}); + + // Verifies that the given schedule is valid for the given module. + // Specifically, the schedule contains exactly the instructions in the + // non-fusion computations in the module and every dependency in the module is + // satisfied in the schedule. + Status Verify() const; + + std::string ToString() const; + + bool empty() const { return sequences_.empty(); } + + const HloModule* module() const { return module_; } + + private: + // Updates the instruction sequence for the given computation. + Status UpdateComputationSchedule(const HloComputation* computation); + + const HloModule* module_; + + // A map from computation unique ID to instruction sequence. Unique IDs are + // used rather than HloComputation pointers because HLO pointers are not + // unique across HLO transformations because pointers may be recycled. + absl::flat_hash_map sequences_; + + // A corresponding map of `sequences_`, mapping the computation unique ID + // included in the shedule to execution threads. We need to store this since + // sometimes, computation could be removed while we still need the execution + // thread info for the remaining sequences. + absl::flat_hash_map execution_threads_; +}; + +std::ostream& operator<<(std::ostream& out, const HloSchedule& schedule); + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_SCHEDULE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding.h new file mode 100644 index 0000000000000000000000000000000000000000..430f95799a7badecbb45ab33c0a5d2209c2350d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding.h @@ -0,0 +1,662 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// HLO shardings describe how an HLO instruction is split across multiple +// computations. + +#ifndef XLA_HLO_IR_HLO_SHARDING_H_ +#define XLA_HLO_IR_HLO_SHARDING_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/types/span.h" +#include "xla/array.h" +#include "xla/hlo/ir/tile_assignment.h" // IWYU pragma: export +#include "xla/shape_tree.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// HLO shardings describe how an HLO instruction is split across multiple +// computations. +class HloSharding { + public: + // Creates a trivial sharding that replicates a maximal tile across all + // devices. + static HloSharding Replicate(absl::Span metadata = {}) { + return HloSharding(/*manual=*/false, /*replicated=*/true, /*unknown=*/false, + metadata); + } + + // Creates a sharding that represents the op is manually partitioned. + static HloSharding Manual(absl::Span metadata = {}) { + return HloSharding(/*manual=*/true, /*replicated=*/false, /*unknown=*/false, + metadata); + } + + // Creates a sharding that represents the op has a placeholder sharding. + static HloSharding Unknown(absl::Span metadata = {}) { + return HloSharding(/*manual=*/false, /*replicated=*/false, /*unknown=*/true, + metadata); + } + + // Creates a sharding that emulates device placement; a tile shape equal to + // the input shape (one tile) assigned to a single device. + static HloSharding AssignDevice(int64_t device_id, + absl::Span metadata = {}); + + // Creates a new sharding which splits a shape into tiles amongst the devices + // specified by `tile_assignment`. + static HloSharding Tile(TileAssignment tile_assignment, + absl::Span metadata = {}) { + return HloSharding(tile_assignment, /*replicate_on_last_tile_dim=*/false, + metadata); + } + static HloSharding Tile(Array tile_assignment, + absl::Span metadata = {}) { + return HloSharding(TileAssignment(std::make_shared>( + std::move(tile_assignment))), + /*replicate_on_last_tile_dim=*/false, metadata); + } + // Similar to `Tile` but use IotaTileAssignment format. + static HloSharding IotaTile(absl::Span tile_assignment_dims, + absl::Span metadata = {}) { + return HloSharding(TileAssignment(tile_assignment_dims), + /*replicate_on_last_tile_dim=*/false, metadata); + } + static HloSharding IotaTile(absl::Span tile_assignment_dims, + absl::Span reshape_dims, + absl::Span transpose_perm, + absl::Span metadata = {}) { + return HloSharding( + TileAssignment(tile_assignment_dims, reshape_dims, transpose_perm), + /*replicate_on_last_tile_dim=*/false, metadata); + } + + // Creates a partially replicated tiled sharding with device-level tile + // assignment, where the last dimension is the additional replication + // dimension. Replication group members will be sorted. + static HloSharding PartialTile( + const TileAssignment& tile_assignment_last_dim_replicate, + absl::Span metadata = {}); + static HloSharding PartialTile( + Array tile_assignment_last_dim_replicate, + absl::Span metadata = {}) { + return PartialTile(TileAssignment(std::make_shared>( + std::move(tile_assignment_last_dim_replicate))), + metadata); + } + + // Creates a subgroup sharding with device-level tile assignment, the + // sharding type of each subgroup is defined by subgroup_types. When creating + // the HloSharding, subgroup dims of the same type will be merged. + static HloSharding Subgroup(const TileAssignment& tile_assignment, + absl::Span subgroup_types, + absl::Span metadata = {}); + static HloSharding Subgroup(Array tile_assignment, + absl::Span subgroup_types, + absl::Span metadata = {}) { + return Subgroup( + TileAssignment(std::make_shared>(tile_assignment)), + subgroup_types, metadata); + } + + // Creates a new sharding which splits a one-dimensional input shape into + // `num_tiles` tiles. + static HloSharding Tile1D(const Shape& input_shape, int64_t num_tiles, + absl::Span metadata = {}); + + // Creates a new sharding for a tuple type. The given ShapeTree must have + // elements for every leaf shape contained in the tuple. + static HloSharding Tuple(const ShapeTree& sub_shardings); + + // Creates a new sharding for a tuple type. The number of elements in + // shardings must match the number of leaf nodes in tuple_shape. For + // empty tuples, the shardings array must have one element. + static HloSharding Tuple(const Shape& tuple_shape, + absl::Span shardings); + + // Creates a new sharding for a tuple type, with a single input sharding + // repeated on each leaf. + static HloSharding SingleTuple(const Shape& tuple_shape, + const HloSharding& sharding); + + // If shape is an array, returns sharding, otherwise returns the tuple shaped + // sharding with all the leaf nodes having the same input sharding. + static HloSharding Single(const Shape& shape, const HloSharding& sharding); + + // Create a new sharding from a protobuf OpSharding. + static StatusOr FromProto(const OpSharding& proto); + + // Checks whether device is a reserved device number. A reserved device number + // has usually a special meaning, with dedicated handling logic. + static bool IsReservedDevice(int64_t device) { return device < 0; } + + OpSharding ToProto() const; + + // Prints the string representation of this sharding.Note that this string + // canonically has outer curly braces, e.g. "{replicated}". + void Print(Printer* printer, bool include_metadata = false) const; + + // Returns the content printed by Print as a string. + std::string ToString(bool include_metadata = false) const; + + // Validate that this sharding can be applied to a tensor with shape `shape`. + Status Validate(const Shape& shape, + std::optional num_devices = {}) const; + + // Returns true if the sharding has tuple type. + bool IsTuple() const { return tuple_; } + + // Returns true if the sharding is trivial: replicate on all devices. + bool IsReplicated() const { + if (!IsTuple()) { + return replicated_; + } + return absl::c_all_of( + tuple_elements_, [](const HloSharding& s) { return s.IsReplicated(); }); + } + + // Returns true if the tile size is the same as the input size. + bool IsTileMaximal() const { + if (!IsTuple()) { + return maximal_; + } + return absl::c_all_of(tuple_elements_, [](const HloSharding& s) { + return s.IsTileMaximal(); + }); + } + + // Returns whether the sharding represents manual partitioning. + bool IsManual() const { + if (!IsTuple()) { + return manual_; + } + return absl::c_all_of(tuple_elements_, + [](const HloSharding& s) { return s.IsManual(); }); + } + + // Returns whether the sharding represents a placeholder sharding. + bool IsUnknown() const { + if (!IsTuple()) { + return unknown_; + } + return absl::c_all_of(tuple_elements_, + [](const HloSharding& s) { return s.IsUnknown(); }); + } + + bool IsShardGroup() const { + if (!IsTuple()) { + return shard_group_.shard_group_id != -1 && + (shard_group_.shard_like || shard_group_.shard_as); + } + return !tuple_elements_.empty() && + absl::c_all_of(tuple_elements_, [](const HloSharding& s) { + return s.IsShardGroup(); + }); + } + + bool IsShardAs() const { + if (!IsTuple()) { + return shard_group_.shard_group_id != -1 && shard_group_.shard_as; + } + return !tuple_elements_.empty() && + absl::c_all_of(tuple_elements_, + [](const HloSharding& s) { return s.IsShardAs(); }); + } + + bool IsShardLike() const { + if (!IsTuple()) { + return shard_group_.shard_group_id != -1 && shard_group_.shard_like; + } + return !tuple_elements_.empty() && + absl::c_all_of(tuple_elements_, + [](const HloSharding& s) { return s.IsShardLike(); }); + } + + // Returns whether the sharding represents manual subgroup sharding. + bool IsManualSubgroup() const { + if (!IsTuple()) { + return absl::c_linear_search(subgroup_types_, OpSharding::MANUAL); + } + return absl::c_all_of(tuple_elements_, [](const HloSharding& s) { + return s.IsManualSubgroup(); + }); + } + + // Returns weather the sharding represents a tiled sharding where the mapping + // between devices and tiles is represented through 'tile_assignment()'. + bool IsTiled() const { + return !IsTileMaximal() && !IsManual() && !IsUnknown(); + } + + // Returns if the sharding has partial replication and partial sharding. If + // true, data is sharded according to other dimensions of tile_assignment(), + // but replicated across devices along the last dimension. + bool ReplicateOnLastTileDim() const { return replicate_on_last_tile_dim_; } + + // Returns whether there is any partial replication. This can be using + // ReplicateOnLastTileDim or subgroups with REPLICATED. + bool HasPartialReplication() const { + return replicate_on_last_tile_dim_ || + absl::c_linear_search(subgroup_types_, OpSharding::REPLICATED); + } + + // Returns true if the sharding defines an operation on the given device. + bool UsesDevice(int64_t device) const; + + // Retrieves a histogram of the devices used by the sharding. The returned + // map has the device number as key, and the occurrence count as value. + // If a sharding does not have a device, it will not be included in the + // histogram. The count argument, if not nullptr, will receive the total + // number of elements this sharding is made of (one for array, N leaves for + // tuples). + std::map UsedDevices(int64_t* count) const; + + // Returns the tile that should be executed on the given device. + // REQUIRES: !IsTuple() + std::vector TileIndexForDevice(int64_t device) const; + + // Returns the device that should execute the given tile. + // It is an error to call this if is_replicated() is true. + // When ReplicateOnLastTileDim() == true, if index.size() == data rank, it + // returns the first device in that replicated subgroup; otherwise, + // index.size() should be the same as tile_assignment()'s rank and specifies + // the member of the replication subgroup. + // REQUIRES: !IsTuple() + int64_t DeviceForTileIndex(absl::Span index) const; + + // Given a device ID, returns the offset within the specified shape of the + // tile that should be executed on the given core. This returns the lower + // extent of the tile in the input space. + // REQUIRES: !IsTuple() + std::vector TileOffsetForDevice(const Shape& shape, + int64_t device) const; + + // Given a device ID, returns the limit within the specified shape of the + // tile that should be executed on the given core. This returns the upper + // extent of the tile in the input space. + // REQUIRES: !IsTuple() + std::vector TileLimitForDevice(const Shape& shape, + int64_t device) const; + + // Returns the single device this op operates on. If the sharding does not + // span a single device, the return value will be empty. + // In order for a sharding to span a single device, every leaf sharding must + // be maximal and not replicated, and the used device must match. + std::optional UniqueDevice() const; + + // Retrieves the unique device or fails with a CHECK. + int64_t GetUniqueDevice() const; + + // Returns true if this op only uses a single device. + bool HasUniqueDevice() const { return UniqueDevice().has_value(); } + + // Returns the ShapeTree containing the shardings for each element of this + // tuple, if IsTuple, or a ShapeTree with a single element containing this + // sharding. Only the leaf elements are populated. This creates a new + // ShapeTree object so is not cheap. + StatusOr> AsShapeTree(const Shape& shape) const; + ShapeTree GetAsShapeTree(const Shape& shape) const { + return AsShapeTree(shape).value(); + } + + // Retrieves the sub sharding at a given index, out of a tuple sharding. + // REQUIRES: IsTuple() + HloSharding GetSubSharding(const Shape& shape, const ShapeIndex& index) const; + + // If the current sharding is a tuple sharding, return itself as result. + // Otherwise returns a tuple sharding for the input shape, with all the leaves + // having this object sharding. + StatusOr GetTupleSharding(const Shape& shape) const; + + // If the shape is tuple and the current sharding is not a tuple, attempt to + // construct a sharding that is compatible with the shape by replicating the + // current sharding across all tuple elements. Note that the returned + // sharding is not guaranteed to be compatible with the input shape. + HloSharding NormalizeTupleSharding(const Shape& shape) const; + + // Extracts the sharding that is common within the current sharding. + // If the current sharding is not a tuple sharding, the current sharding will + // be returned. If it is a tuple, and all the tuple elements are common, the + // common element will be returned. Otherwise the optional will contain no + // value. + std::optional ExtractSingleSharding() const; + + // Returns a copy of the sharding with no metadata. If sharding is of tuple + // type, sub shardings will have no metadata. + HloSharding WithoutMetadata() const; + + // Returns a copy of the sharding with specified metadata. If metadata is + // already present, that metadata will not be replaced unless `overwrite` is + // set to true. If sharding is of tuple type, sub shardings metadata will be + // assigned instead. + HloSharding WithMetadata(absl::Span metadata, + bool overwrite) const; + + bool operator==(const HloSharding& other) const { + return replicated_ == other.replicated_ && maximal_ == other.maximal_ && + manual_ == other.manual_ && unknown_ == other.unknown_ && + tile_assignment_ == other.tile_assignment_ && + tuple_elements_ == other.tuple_elements_ && + replicate_on_last_tile_dim_ == other.replicate_on_last_tile_dim_ && + subgroup_types_ == other.subgroup_types_ && + shard_group_ == other.shard_group_; + } + bool operator!=(const HloSharding& other) const { return !(*this == other); } + + template + friend H AbslHashValue(H h, const HloSharding& sharding) { + if (sharding.tuple_) { + return H::combine(std::move(h), sharding.tuple_elements_); + } + return H::combine(std::move(h), sharding.replicated_, sharding.manual_, + sharding.unknown_, sharding.tile_assignment_.array(), + sharding.replicate_on_last_tile_dim_, + sharding.shard_group_.ToString()); + } + + // Gets the tile assignment tensor. + // REQUIRES: !IsReplicated() && !IsTuple() + const TileAssignment& tile_assignment() const { return tile_assignment_; } + + // Gets the subgroup types array. + // REQUIRES: !IsTuple() + const std::vector& subgroup_types() const { + return subgroup_types_; + } + + // Returns the flattened list of all the leaf shardings in a tuple shape, by + // pre-order walk (ShapeTree iterator order). + // REQUIRES: IsTuple(). + std::vector& tuple_elements() { return tuple_elements_; } + const std::vector& tuple_elements() const { + return tuple_elements_; + } + + // Gets the tile shape. + // REQUIRES: !IsTuple() + Shape TileShape(const Shape& shape) const; + + // Gets the tile shape on the device. + // REQUIRES: !IsTuple() + Shape TileShape(const Shape& shape, int64_t device) const; + + // Gets the total number of tiles including subgroups and partial replication. + int64_t TotalNumTiles() const; + // Gets the number of tiles. If it has partial replication, this will not + // equal the device count. + int64_t NumTiles() const; + // Like NumTiles() but considers only some specific dimensions passed as + // argument + int64_t NumTiles(absl::Span dims) const; + + // Gets metadata from sharding. + std::vector& metadata() { return metadata_; } + const std::vector& metadata() const { return metadata_; } + + // Returns the replication subgroup dim, or -1 if it doesn't exist. + int64_t SubgroupReplicationDim() const { + auto it = absl::c_find(subgroup_types_, OpSharding::REPLICATED); + if (it != subgroup_types_.end()) { + return (it - subgroup_types_.begin()) + TiledDataRank(); + } + if (replicate_on_last_tile_dim_) { + return tile_assignment_.num_dimensions() - 1; + } + return -1; + } + + // Returns the manual subgroup dim, or -1 if it doesn't exist. + int64_t SubgroupManualDim() const { + auto it = absl::c_find(subgroup_types_, OpSharding::MANUAL); + if (it != subgroup_types_.end()) { + return (it - subgroup_types_.begin()) + TiledDataRank(); + } + return -1; + } + + // Returns the data rank for tiled sharding. It doesn't include subgroup dims. + int64_t TiledDataRank() const { + CHECK(IsTiled()); + int64_t rank = tile_assignment_.num_dimensions(); + if (ReplicateOnLastTileDim()) { + rank--; + } + rank -= subgroup_types_.size(); + return rank; + } + + // Returns the number of tuple_elements_ entries to fit the shape. + static int64_t RequiredLeaves(const Shape& shape); + + struct ShardGroup { + ShardGroup(int64_t shard_group_id, bool shard_as, bool shard_like) + : shard_group_id(shard_group_id), + shard_as(shard_as), + shard_like(shard_like) {} + + bool operator==(const ShardGroup& rhs) const { + return shard_group_id == rhs.shard_group_id && shard_as == rhs.shard_as && + shard_like == rhs.shard_like; + } + + std::string ToString() const { + std::ostringstream result; + if (shard_as) { + result << "shard_as " << shard_group_id; + } else if (shard_like) { + result << "shard_like " << shard_group_id; + } + return result.str(); + } + + int64_t shard_group_id = 0; + bool shard_as; + bool shard_like; + }; + static ShardGroup NotShardGroup() { + return ShardGroup( + /*shard_group_id=*/-1, + /*shard_as=*/false, + /*shard_like=*/false); + } + + static ShardGroup ShardAs(int64_t shard_group_id) { + return ShardGroup(shard_group_id, + /*shard_as=*/true, + /*shard_like=*/false); + } + + static ShardGroup ShardLike(int64_t shard_group_id) { + return ShardGroup(shard_group_id, + /*shard_as=*/false, + /*shard_like=*/true); + } + + HloSharding& SetShardGroup(const ShardGroup& shard_group) { + shard_group_ = shard_group; + return *this; + } + + HloSharding& SetShardGroupFromProto(const OpSharding& proto) { + ShardGroup shard_group = NotShardGroup(); + if (proto.is_shard_group()) { + if (proto.shard_group_type() == OpSharding::AS) { + shard_group = ShardAs(proto.shard_group_id()); + } else { + shard_group = ShardLike(proto.shard_group_id()); + } + } + SetShardGroup(shard_group); + return *this; + } + + HloSharding& ClearShardGroup() { + shard_group_ = NotShardGroup(); + return *this; + } + + const ShardGroup& GetShardGroup() const { return shard_group_; } + + private: + explicit HloSharding(bool manual, bool replicated, bool unknown, + absl::Span metadata) + : metadata_(metadata.begin(), metadata.end()), + replicated_(replicated), + maximal_(replicated), + tuple_(false), + manual_(manual), + unknown_(unknown), + replicate_on_last_tile_dim_(false) {} + // device_id values: + // -2: magic number to mean unassigned device, used by spatial partitioning + // -1: the id of the host + // 0 or positive: the id of a device + // NOTE(dimvar): -1 is needed for outside compilation. It can be removed once + // we have fully switched to the side-effect tokens. + explicit HloSharding(int64_t device_id, absl::Span metadata) + : tile_assignment_(device_id), + metadata_(metadata.begin(), metadata.end()), + replicated_(false), + maximal_(true), + tuple_(false), + manual_(false), + unknown_(false), + replicate_on_last_tile_dim_(false) {} + explicit HloSharding(TileAssignment tile_assignment, + bool replicate_on_last_tile_dim, + absl::Span metadata = {}) + : tile_assignment_(std::move(tile_assignment)), + metadata_(metadata.begin(), metadata.end()), + replicated_(false), + maximal_(false), + tuple_(false), + manual_(false), + unknown_(false), + replicate_on_last_tile_dim_(replicate_on_last_tile_dim) {} + explicit HloSharding(TileAssignment tile_assignment, + absl::Span subgroup_types, + absl::Span metadata = {}) + : tile_assignment_(std::move(tile_assignment)), + metadata_(metadata.begin(), metadata.end()), + subgroup_types_(subgroup_types.begin(), subgroup_types.end()), + replicated_(false), + maximal_(false), + tuple_(false), + manual_(false), + unknown_(false), + replicate_on_last_tile_dim_(false) {} + explicit HloSharding(const std::vector& tuple_shardings) + : tuple_elements_(tuple_shardings), + replicated_(false), + maximal_(false), + tuple_(true), + manual_(false), + unknown_(false), + replicate_on_last_tile_dim_(false) {} + + // Test-only constructor for sharding format code coverage. Copies the + // original sharding with provided tile assignment. + explicit HloSharding(const HloSharding& other, TileAssignment tile_assignment) + : tile_assignment_(std::move(tile_assignment)), + tuple_elements_(other.tuple_elements_), + metadata_(other.metadata_), + subgroup_types_(other.subgroup_types_), + replicated_(other.replicated_), + maximal_(other.maximal_), + tuple_(other.tuple_), + manual_(other.manual_), + unknown_(other.unknown_), + replicate_on_last_tile_dim_(other.replicate_on_last_tile_dim_) { + CHECK(tile_assignment_ == other.tile_assignment_) + << tile_assignment_.ToString() << " v.s. " + << other.tile_assignment_.ToString(); + } + friend class HloShardingTestHelper; + + // Checks that the number of elements in tuple_elements_ is consistent with + // the tuple shape passes as argument. + Status CheckLeafCount(const Shape& shape) const; + + // Internal helper to validate a tuple sharding. + Status ValidateTuple(const Shape& shape, + std::optional num_devices) const; + + // Internal helper to validate a non-tuple (leaf) sharding. + Status ValidateNonTuple(const Shape& shape, + std::optional num_devices) const; + + // This field is only used if replicated_ is false. If maximal_ is true, then + // the field contains a rank 1 array with a single element, which is the + // device the HLO is assigned to. If maximal_ is false, the field contains an + // array with the same rank as the corresponding HLO. The dimension sizes of + // the array describe the number of ways the HLO is partitioned along each + // dimension. The values of the array specify which device each tile of + // the HLO is assigned to. The index of each value determines which tile it + // takes. + // For example, {{{2, 3}}, {{5, 7}}} (whose ToString representation is + // "{devices=[2,1,2]2,3,5,7}"), means that dimension 1 is split two way and + // dimension 3 is split 2 way. Core 5, whose index is [2,1,1] will take the + // tile that contains the 2nd half of dimension 1 and the 1st half of + // dimension 3. + TileAssignment tile_assignment_; + // Only non-empty when tuple_ is true. If a tuple is empty then one entry is + // present for the root. This is a flattened list of all the leaf shardings in + // a tuple shape, by pre-order walk (ShapeTree iterator order). + std::vector tuple_elements_; + // This field is used to track the source of this sharding, usually derived + // from instructions. Multiple metadata may be populated if sharding is + // combined with other shardings. Metadata are to not be populated when + // tuple_ == true and instead metadata should be set on individual tuple + // elements. + std::vector metadata_; + // This field is used to represented the sharding type of each subgroup. + // For example, sharding={devices=[2,2,2,2]0,1,2,...,15 last_tile_dims={ + // replicate, manual, unreduced}} means that each of the last 3 dimensions + // in [2,2,2,2] represents a subgrouping in replicate, manual. + // When creating HloSharding, subgroup dims of the same type will be merged, + // so that there is at most one dim with a given type. + std::vector subgroup_types_; + bool replicated_; + bool maximal_; + bool tuple_; + bool manual_; + bool unknown_; + // This flag is to support partial replication and partial sharding. If it is + // true, tile_assignment_ will have an extra dimension in addition to the data + // shape rank, and the added last dimension represents the subgroups of + // replications, i.e., elements in slice [..., :] will be replicated. + bool replicate_on_last_tile_dim_; + // This field is used to store the shard group information. Instructions + // within the same shard group(i.e. under the same shard_group_id) will be + // sharded alike or exactly the same as each other. + ShardGroup shard_group_ = NotShardGroup(); +}; + +std::ostream& operator<<(std::ostream& out, const HloSharding& sharding); + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_SHARDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding_metadata.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..7fa15698e586e5b214efeb5b61fd3e4dfbc5cd3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/hlo_sharding_metadata.h @@ -0,0 +1,110 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_HLO_SHARDING_METADATA_H_ +#define XLA_HLO_IR_HLO_SHARDING_METADATA_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_domain_metadata.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "tsl/platform/status.h" + +namespace xla { + +// A DomainMetadata implementation that internally wraps a sharding attribute. +class ShardingMetadata : public DomainMetadata { + public: + explicit ShardingMetadata(std::shared_ptr sharding) + : sharding_(std::move(sharding)) {} + + std::unique_ptr Clone() const override; + + absl::string_view Kind() const override { return KindName(); } + + bool Matches(const DomainMetadata& other) const override; + + template + friend H AbslHashValue(H h, const ShardingMetadata& sharding_metadata) { + const bool has_sharding = sharding_metadata.sharding_ != nullptr; + if (has_sharding) { + h = H::combine(std::move(h), *sharding_metadata.sharding_); + } + return H::combine(std::move(h), has_sharding); + } + + size_t Hash() const override { return absl::HashOf(*this); } + + std::string ToString() const override; + + const HloSharding* sharding() const { return sharding_.get(); } + + static absl::string_view KindName() { return "sharding"; } + + static StatusOr ToShardingMetadata( + const DomainMetadata* metadata); + + // Apply the specified domain metadata onto the specified domain. If no + // metadata is specified then apply sharding heuristics and normalize the + // instructions whose sharding deviates from the one which is inferred as to + // be the original one. Policy wise, HLO passes are allowed to create new + // unassigned instructions, but if they do create assigned ones, they have to + // conform to the ones around. + static Status NormalizeShardingDomain(const DomainMetadata::Domain& domain, + const DomainMetadata* metadata); + + private: + std::shared_ptr sharding_; +}; + +// If the sharding between root and instruction changes then returns a +// ShardingMetadata based kDomain instruction what can be used to separate +// operand and instruction. +// Returns nullptr if there is no need for a domain separation. +class ShardingDomainCreator { + public: + HloInstruction* operator()(HloInstruction* instruction, HloInstruction* root, + HloInstruction* operand); + + private: + // Map from instruction and user sharding to domain users to CSE identical + // domains. + struct DomainCseMapKey { + const HloInstruction* instruction; + std::shared_ptr sharding; + + bool operator==(const DomainCseMapKey& other) const; + + template + friend H AbslHashValue(H h, const DomainCseMapKey& key) { + h = H::combine(std::move(h), key.instruction); + const bool has_sharding = key.sharding != nullptr; + if (has_sharding) { + h = H::combine(std::move(h), *key.sharding); + } + return H::combine(std::move(h), has_sharding); + } + }; + absl::flat_hash_map domain_cse_map_; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_HLO_SHARDING_METADATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/tile_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/tile_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..871b6e6aeabb383c852e154456eae5c356b5ef71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/ir/tile_assignment.h @@ -0,0 +1,270 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_IR_TILE_ASSIGNMENT_H_ +#define XLA_HLO_IR_TILE_ASSIGNMENT_H_ + +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/types/span.h" +#include "xla/array.h" +#include "xla/printer.h" + +namespace xla { + +class TileAssignment; + +// Describes a TileAssignment with a device array generated from reshaping and +// transposing an iota array, a.k.a. HloShardingV2. This is a more scalable +// format for large number of devices since it does not materialize the full +// list of devices, while being less general since it cannot represent +// arbitrary sequence of devices. It is however sufficient to represent the +// most commonly generated SPMD shardings from ML frameworks that arrange +// devices using mesh axes. +class IotaTileAssignment { + public: + // Create a trivial (i.e. the device array is a trivial iota without reshape + // and transpose) IotaTileAssignment with given dimensions. + static IotaTileAssignment Create(absl::Span dims); + // Creates an IotaTileAssignment canonicalizing `reshape_dims` and + // `transpose_perm`. More specifically the tile assignment array is as if it + // is produced by the following numpy code: + // numpy.arange(math.prod(dims)).reshape(reshape_dims) + // .transpose(transpose_perm).reshape(math.prod(dims)) + // where: + // `dims`: is the dimensions of the tile assignment array. + // `reshape_dims`: is the dimensions the 1D iota array is reshaped to. + // `transpose_perm`: is the dimension permutation to transpose `reshape_dims`. + // + // e.g. dims=[8,8,8] reshape_dims=[4,2,2], transpose_perm=[0,1,2] (no + // transpose) corresponds to [8,8,8]<=[16] which in full array V1 format is + // [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. + // e.g. dims=[8,8,8] reshape_dims=[4,2,2], transpose_perm=[1,0,2] (swap dim 0 + // and dim 1) corresponds to [8,8,8]<=[4,2,2]T(1,0,2) which in full array V1 + // format is [0,1,4,5,8,9,12,13,2,3,6,7,10,11,14,15]. + static IotaTileAssignment Create(absl::Span dims, + absl::Span reshape_dims, + absl::Span transpose_perm); + + ~IotaTileAssignment() = default; + IotaTileAssignment(const IotaTileAssignment& other); + IotaTileAssignment(IotaTileAssignment&& other) = default; + IotaTileAssignment& operator=(const IotaTileAssignment& other); + IotaTileAssignment& operator=(IotaTileAssignment&& other) = default; + + bool operator==(const IotaTileAssignment& other) const { + return dims() == other.dims() && reshape_dims() == other.reshape_dims() && + transpose_perm() == other.transpose_perm(); + } + + int64_t value_at(absl::Span index) const; + + int64_t ndims() const { return ndims_; } + + absl::Span dims() const { + return absl::MakeSpan(dims_ptr(), ndims_); + } + + int64_t dim(int n) const { return dims_ptr()[n]; } + + absl::Span reshape_dims() const { + return absl::MakeSpan(reshape_dims_ptr(), reshape_ndims_); + } + + absl::Span transpose_perm() const { + return absl::MakeSpan(transpose_perm_ptr(), reshape_ndims_); + } + + int64_t num_elements() const { + return absl::c_accumulate(dims(), 1LL, std::multiplies()); + } + + // TODO(b/281892190): This should really not return optional, when we are + // sure we can handle all cases. + std::optional Transpose(absl::Span perm) const; + + void Print(Printer* printer) const; + + std::string ToString() const; + + private: + friend class TileAssignment; + static constexpr int kPerDimBytes = sizeof(int64_t); + static constexpr int kPerReshapeDimBytes = sizeof(int64_t) + sizeof(int); + + explicit IotaTileAssignment(absl::Span dims, + absl::Span reshape_dims, + absl::Span transpose_perm); + + explicit IotaTileAssignment(int ndims, int reshape_ndims); + + int64_t* dims_ptr() { return reinterpret_cast(storage_.get()); } + const int64_t* dims_ptr() const { + return reinterpret_cast(storage_.get()); + } + const int64_t* reshape_dims_ptr() const { return dims_ptr() + ndims_; } + int64_t* reshape_dims_ptr() { + return const_cast( + const_cast(this)->reshape_dims_ptr()); + } + const int* transpose_perm_ptr() const { + return reinterpret_cast(reshape_dims_ptr() + reshape_ndims_); + } + int* transpose_perm_ptr() { + return const_cast( + const_cast(this)->transpose_perm_ptr()); + } + + int size_bytes() const { + return ndims_ * kPerDimBytes + reshape_ndims_ * kPerReshapeDimBytes; + } + + bool next_index(absl::Span index) const { + DCHECK_EQ(index.size(), ndims_); + for (int64_t i = ndims_ - 1; i >= 0; --i) { + index[i]++; + if (index[i] < dims_ptr()[i]) { + return true; + } + index[i] = 0; + } + return false; + } + int32_t ndims_; + int32_t reshape_ndims_; + // Contiguous buffer storing `int64_t dims[]`, `int64_t reshape_dims[]`, + // `int transpose_perm[]` in order. + std::unique_ptr storage_; +}; + +// Internal class that represents how an ordered list of device IDs are sharded +// along different dimensions. It manages full or compact representation of the +// device IDs without having callers worry about what underlying format is used. +// This class is meant to be included ONLY by HloSharding so it does not return +// error status on invalid arguments but rather assert preconditions in its +// implementation, assuming it should always get valid data. +// NOTE: This class is immutable. +class TileAssignment { + public: + TileAssignment() : array_(ReplicatedArray()) {} + explicit TileAssignment(std::shared_ptr> array) + : shared_array_(std::move(array)), array_(shared_array_.get()) {} + explicit TileAssignment(int64_t device_id) + : TileAssignment(std::make_shared>( + std::initializer_list{1}, device_id)) {} + explicit TileAssignment(IotaTileAssignment iota) : iota_(std::move(iota)) {} + explicit TileAssignment(absl::Span dims) + : iota_(IotaTileAssignment::Create(dims)) {} + explicit TileAssignment(absl::Span dims, + absl::Span reshape_dims, + absl::Span transpose_perm) + : iota_(IotaTileAssignment::Create(dims, reshape_dims, transpose_perm)) {} + + bool operator==(const TileAssignment& other) const; + bool operator!=(const TileAssignment& other) const { + return !operator==(other); + } + // Methods that mirrors those of xla::Array. + template + typename std::enable_if_t::value, + int64_t> + operator()(Dims... dims) const { + DCHECK_EQ(sizeof...(dims), num_dimensions()); + std::array indexes{ + {static_cast(dims)...}}; + return operator()(indexes); + } + int64_t operator()(absl::Span indexes) const; + + absl::Span dimensions() const; + int64_t num_dimensions() const; + int64_t dim(int64_t n) const; + int64_t num_elements() const; + int64_t first() const; + + void Each( + absl::FunctionRef, int64_t)> f) const; + + Status EachStatus( + absl::FunctionRef, int64_t)> f) const; + + // Returns a tile assignment reshaped to the given dimensions. + // REQUIRES: new shape has the same number of elements. + [[nodiscard]] TileAssignment Reshape( + absl::Span new_dimensions) const; + + // Returns a tile assignment transposd using the given dimension permutations. + // REQUIRES: `perm` must a an array of num_dimensions elements, with unique + // values within [0, num_dimensions). + [[nodiscard]] TileAssignment Transpose(absl::Span perm) const; + + void Print(Printer* printer) const; + + std::string ToString() const; + + bool UsesDevice(int64_t device) const; + + // Returns non-nullopt iota tile assignment iff it holds that format. + const std::optional& iota() const { return iota_; } + // Returns reference to the full array representation. If it holds iota + // format, reference to a lazily materialized array is returned. + const Array& array() const; + // Similar to array() but returns the underlying shared_ptr to avoid deep + // copy. + const std::shared_ptr>& shared_array() const; + // Makes a deep copy of shared_array(). + std::shared_ptr> shared_array_clone() const; + + template + friend H AbslHashValue(H h, const TileAssignment& tile) { + // TODO(b/281892190): Ideally hashing a TileAssignment should not force iota + // -> full array conversion, but a requirement is that they should have + // equivalence. Consider providing a faster hash function for iota tile + // assignment. + return H::combine(std::move(h), tile.array()); + } + + private: + friend class HloSharding; + // TODO(b/281892190): Consider changing int64_t to int32_t since it's unlikely + // to have so many devices to overflow int32_t in practice. + explicit TileAssignment(IotaTileAssignment iota, + std::shared_ptr> shared_array) + : iota_(std::move(iota)), + shared_array_(std::move(shared_array)), + array_(shared_array_.get()) {} + + void MaybeMaterializeFullArray() const; + + static const Array* ReplicatedArray() { + static auto* array = new Array({0}); + return array; + } + + std::optional iota_; + // If iota_ is set, shared_array_ is a lazy cache of the materialized array. + mutable std::shared_ptr> shared_array_; + // Pointer to the storage of the fully materialized array format. + mutable const Array* array_ = nullptr; +}; + +} // namespace xla + +#endif // XLA_HLO_IR_TILE_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/transforms/hlo_constant_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/transforms/hlo_constant_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..50ac60671235a84876a9d4de1db0d38672e72b9b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/transforms/hlo_constant_splitter.h @@ -0,0 +1,49 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_TRANSFORMS_HLO_CONSTANT_SPLITTER_H_ +#define XLA_HLO_TRANSFORMS_HLO_CONSTANT_SPLITTER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Splits the constant instructions such that they have a single user. +// This is typically used before domain placement, to make sure a shared +// constant does not short-circuit domains. It is also used before sharding +// propagation to prevent unintended propagation of sharding due to shared used +// of constants. +// +// CSE passes after domain placements will ensure that all the sharable +// constants within the same domain, will be rejoined back. +// +// This pass may generate dead instructions. Thus, HloDCE is recommended after +// this pass. +class HloConstantSplitter : public HloModulePass { + public: + explicit HloConstantSplitter(bool split_expressions = false) + : split_expressions_(split_expressions) {} + absl::string_view name() const override { return "hlo-constant-splitter"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool split_expressions_; +}; + +} // namespace xla + +#endif // XLA_HLO_TRANSFORMS_HLO_CONSTANT_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_live_range.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_live_range.h new file mode 100644 index 0000000000000000000000000000000000000000..62a2f0d19abd54970af815f8a64265e15e6b2d3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_live_range.h @@ -0,0 +1,234 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations under +the License. +==============================================================================*/ +#ifndef XLA_HLO_UTILS_HLO_LIVE_RANGE_H_ +#define XLA_HLO_UTILS_HLO_LIVE_RANGE_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/dfs_hlo_visitor.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_alias_analysis.h" +#include "xla/service/hlo_buffer.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_ordering.h" +#include "xla/service/hlo_value.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "tsl/platform/status.h" + +namespace xla { + +// Class which computes live range of the output buffers of HLOs and their +// interference by flattening all computations. The live range is only available +// when all global computations (while, if, call, etc) have total order +// sequential orders. +class HloLiveRange { + public: + // Constructs a hlo live range object for the given module and computation + // assuming the given HLO instruction ordering. + static StatusOr> Run( + const HloSchedule& schedule, const HloAliasAnalysis& alias_analysis, + const HloComputation* computation, bool module_scoped_analysis = true); + + // LogicalTime represents the time in a virtual clock. Each instruction has + // one monotonically increasing logical time assigned according to the + // schedule. + using LogicalTime = int64_t; + + struct TimeBound { + LogicalTime start; + LogicalTime end; + // The buffer can hold multiple instructions during its life time (each + // tenant exclusively owns the buffer at any given time). `end_instruction` + // represents the last instruction that the buffer holds. + HloPosition end_position; + + bool friend operator==(const TimeBound& a, const TimeBound& b) { + return a.start == b.start && a.end == b.end; + } + bool friend operator!=(const TimeBound& a, const TimeBound& b) { + return !(a == b); + } + }; + + std::string ToString() const; + + const HloInstructionSequence& flattened_instruction_sequence() const { + return flattened_instruction_sequence_; + } + + // Returns the map from instruction to the end time of that instruction. + const absl::flat_hash_map& + instruction_schedule() const { + return instruction_schedule_; + } + + // Returns the map from a hlo value to the definition time of that hlo value. + const absl::flat_hash_map& buffer_live_ranges() + const { + return buffer_live_ranges_; + } + + absl::flat_hash_map& buffer_live_ranges() { + return buffer_live_ranges_; + } + + // Returns the map from a computation and its time span in the schedule. + const absl::flat_hash_map& + computation_span_times() const { + return computation_span_times_; + } + + // Returns the time stamp of the end of the program. + LogicalTime schedule_end_time() const { + return flattened_instruction_sequence_.size(); + } + + // Returns whether hlo live range is available on this entire module. Hlo live + // range is not available if the module is partially ordered. + bool total_order_scheduled() const { return total_order_scheduled_; } + + private: + explicit HloLiveRange(const HloSchedule& schedule, + const HloAliasAnalysis& alias_analysis, + bool module_scoped_analysis) + : schedule_(schedule), + alias_analysis_(alias_analysis), + module_scoped_analysis_(module_scoped_analysis) {} + + // FlattenSchedule walks through the instructions in `computation`, and + // recurse into each called computations in module_scoped_analysis mode. As it + // walks it also tracks down the ordinal number of each instruction in the + // schedule and store it in the `instruction_schedule` and + // 'flattened_instruction_sequence`. async_context contains the asynchronous + // computation that this computation is in, if any. When this value is + // non-null, it means that this computation is called by an async op or + // another op in an asynchronous context. + void FlattenSchedule(const HloComputation& computation, + const HloComputation* async_context = nullptr); + + // Returns the last position of a value. + TimeBound GetLastPosition(const HloValue& value, + LogicalTime definition_end_time) const; + + // Returns the time of the last use of a value. + LogicalTime GetLastUsageTime(const HloValue& value) const; + + // Based on the flattened schedule, calculate the start and end of each + // buffer. + void CalculateBufferStartEndMap(); + + // The aliased buffers could have overlapping live ranges. + // NormalizeAliasedBuffers normalizes the buffer such that each alias buffer + // has disjoint live range while keeping the live range union the same. This + // avoid double counting aliased buffer sizes. + // + // Before(buffer1 and 2 are aliased): + // + // +----+ live range of buffer1 + // +------------------+ live range of buffer2 + // + // After: + // + // +----------+ live range of buffer1 + // +-------+ live range of buffer2 + // + // Before(buffer1 and 2 are aliased): + // + // +----------+ live range of buffer1 + // +------------+ live range of buffer2 + // + // After: + // + // +----------+ live range of buffer1 + // +-------+ live range of buffer2 + // + // Before(buffer1 and 2 are aliased): + // + // +----------+ live range of buffer1 + // +---+ live range of buffer2 + // + // After(unchanged): + // + // +----------+ live range of buffer1 + // +---+ live range of buffer2 + // + // As another example, imagine we have the following code sequence with live + // ranges of each while-aliased buffers: + // + // a p1 p2 e b + // a = ... + + // | + // { | + // p1 = param | + + // ROOT true | | + // } | + + // { // body | + // p2 = param + + + // c = p2 + 1 + + // d = c + 1 + // ROOT e = d + 1 + + // } | + // | + // b = while (a) + + + // | + // f = b + 1 + + // + // After normalization it becomes: + // + // a p1 p2 e b + // a = ... + + // | + // { | + // p1 = param + + + // ROOT true | + // } | + // { // body | + // p2 = param + + + // c = p2 + 1 + + // d = c + 1 + // ROOT e = d + 1 + + // } | + // | + // b = while (a) + + + // | + // f = b + 1 + + // + // Note there is no overlap of live ranges after normalization. + void NormalizeAliasedBuffers(); + + LogicalTime ComputePeakMemoryMoment() const; + + const HloSchedule& schedule_; + const HloAliasAnalysis& alias_analysis_; + bool module_scoped_analysis_; + bool total_order_scheduled_ = true; + + HloInstructionSequence flattened_instruction_sequence_; + absl::flat_hash_map instruction_schedule_; + absl::flat_hash_map computation_span_times_; + absl::flat_hash_map buffer_live_ranges_; + absl::flat_hash_map + computations_in_async_context_; +}; + +} // namespace xla + +#endif // XLA_HLO_UTILS_HLO_LIVE_RANGE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_query.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_query.h new file mode 100644 index 0000000000000000000000000000000000000000..e166cbe9c9c0976d794356ef29543d8a8a07d31f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_query.h @@ -0,0 +1,126 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_UTILS_HLO_QUERY_H_ +#define XLA_HLO_UTILS_HLO_QUERY_H_ + +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_opcode.h" + +namespace xla { + +// Helper interface for making queries about the HLO IR. +namespace hlo_query { + +// Returns whether the given opcode is a collective communications operation +// that is represented as HloCollectiveInstruction. +bool IsCollectiveCommunicationOp(HloOpcode op); + +// Returns whether the given opcode represents the start operation for a +// collective communication, may include send & recv operations. +bool IsAsyncCollectiveStartOp(HloOpcode op, bool include_send_recv = false); +// Returns whether the given opcode represents the done operation for a +// collective communication, may include send & recv operations. +bool IsAsyncCollectiveDoneOp(HloOpcode op, bool include_send_recv = false); + +// Returns whether the instruction provided is a constant rank-0 float32, and +// if so, places the constant value into out. +// Precondition: out != nullptr +bool IsConstantR0F32(HloInstruction* instruction, float* out); + +// Returns whether all of an instruction's operands are of the types constants +// and parameters. +bool AllOperandsAreParametersOrConstants(const HloInstruction& instruction); + +// Returns whether all of an instruction's operands are of the type constant +// or parameter and the instruction is their only user. +bool AllOperandsAreParametersOrConstantsWithSingleUser( + const HloInstruction& instruction); + +// Returns whether all of an instruction's operands are parameters. +bool AllOperandsAreParameters(const HloInstruction& instruction); + +// Returns whether all of an instruction's operands are constants. +bool AllOperandsAreConstants(const HloInstruction& instruction); + +// Returns whether the instruction is a scalar constant. +bool IsScalarConstant(const HloInstruction* instruction); + +// Returns whether the `instr` is either a constant, a scalar, or a +// broadcasted constant/scalar. +bool IsBroadcastedConstantOrScalar(const HloInstruction& instr); + +// Returns whether the `instr` is a broadcast and its input is a +// scalar constant. +bool IsBroadcastOfScalarConstant(const HloInstruction& instr); + +// Returns first HLO of the computation with the opcode, otherwise nullptr. +HloInstruction* GetFirstInstructionWithOpcode(const HloComputation& computation, + HloOpcode opcode); + +// Determines whether the given computation contains an instruction with one of +// the given opcodes. Checks both comp's instructions and the instructions of +// any computations nested within it. +bool ContainsInstrWithOpcode(const HloComputation* comp, + const absl::flat_hash_set& opcodes); + +// Returns an operand of an instruction with the given opcode. If there are +// multiple matching operands, then the first matching operand is returned. If +// there are no matching operands then nullptr is returned. +HloInstruction* GetMatchingOperand(const HloPredicate& matcher, + HloInstruction* instruction); + +// Returns whether a binary instruction has a matching operand. Sets +// matching_operand to the matching operand and the other operand to +// other_operand. Note: in the case where both operands match, the first operand +// of the instruction is returned. +bool MatchBinaryInstructionOperand(const HloPredicate& matcher, + HloInstruction* instruction, + HloInstruction** matching_operand, + HloInstruction** other_operand); + +// Returns whether a binary instruction has a operand with a given opcode. +// This is a special case of MatchingBinaryInstructionOperand. +bool MatchBinaryInstructionOperandOpcode(HloOpcode opcode, + HloInstruction* instruction, + HloInstruction** matching_operand, + HloInstruction** other_operand); + +// Returns whether the module contains the given collective communication +// instructions with constrained layout. +bool ContainsLayoutConstrainedCollective(const HloModule& module, HloOpcode op); + +// Returns whether the module contains all-reduce instructions with constrained +// layout. +inline bool ContainsLayoutConstrainedAllReduce(const HloModule& module) { + return ContainsLayoutConstrainedCollective(module, HloOpcode::kAllReduce); +} + +// Returns the next available channel id that can be used in the given module +// (for HloChannelInstructions). +int64_t NextChannelId(const HloModule& module); + +// Returns whether the module contains host send/recv with X64 data type. +// This function is called after X64Rewriter, so X64 host transfers are already +// rewritten into tuple shaped transfers. +bool HasX64TransformedHostTransfer(const HloModule& module); + +} // namespace hlo_query +} // namespace xla + +#endif // XLA_HLO_UTILS_HLO_QUERY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_sharding_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_sharding_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d953f0cc5323341e85d3fb05d126e17f365d6dc0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/hlo/utils/hlo_sharding_util.h @@ -0,0 +1,473 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_HLO_UTILS_HLO_SHARDING_UTIL_H_ +#define XLA_HLO_UTILS_HLO_SHARDING_UTIL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/call_graph.h" + +namespace xla { +namespace hlo_sharding_util { + +struct GatherScatterParallelDims { + absl::InlinedVector indices_parallel_dims; + absl::InlinedVector operand_parallel_dims; + std::vector index_parallel_in_dim; +}; + +// Determines if the first operand 'potential_subsharding' is a subsharding of +// the second operand 'sharding'. Subsharding means that the tiles in +// 'potential_subsharding' define tiles that have a subset or the same data that +// the tiles in 'sharding' define. +bool IsSubTilingOrEqualSharding(const Shape& shape, + const HloSharding& potential_subsharding, + const HloSharding& sharding); + +// Returns true if the lhs sharding is preferable over the rhs sharding. +// The most specific sharding is tile maximal followed by single device tile +// maximal and finally replicated. This order aims to primarily reduce memory +// usage and secondly reduce total compute. +// Note: This does NOT provide a total ordering as we can have 2 different +// sharding with same preference level. +bool IsShardingMoreSpecific(const HloSharding& lhs, const HloSharding& rhs); + +// Tries to refine `to_merge` by combining with `old`. Returns if the final +// `to_merge` is more specific than `old`. +bool MergeSharding(const HloSharding& to_merge, HloSharding* dst, + bool may_combine_partial_sharding); + +// Merges `to_merge` into `dst` only if they are compatible, and the merged +// sharding has >= minimum_tiles tiles. Returns if merging happened. +bool MergeShardingIfCompatible(const HloSharding& to_merge, + int64_t minimum_tiles, HloSharding* dst); + +// Find a reasonable common sharding for a list of shardings. The reasonable +// sharding should incur little(the least) amount of total resharding cost when +// resharding all the shardings to this common sharding. +HloSharding FindCommonSharding(absl::Span shardings); + +// Given a map, selects the device with higher +// occurrence count (if any). If top_count in not nullptr, it will receive the +// count of the dominant device returned. +std::optional SelectDominantDevice( + const std::map& device_map, int64_t* top_count); + +// Assigns all the instructions of a computation, to a given device. +// This API does not recurse into called computations, and does not assign +// instructions which already have sharding. +void AssignComputationDevice(HloComputation* computation, int64_t device); + +// Given an instruction container, returns the device which is most commonly +// occurring among the instructions. +std::optional GetMostOccurringDevice( + absl::Span instructions); + +// Given a set of computations, tries to extract the dominant device. A device +// is dominant if the combined occurrence among all the instructions of the +// input computations, is greater/equal than/to dominant_factor (real number +// from 0 to 1). +// This API does not recurse into called computations. +// If no device exists that satisfies the condition, the returned optional will +// hold no value. +std::optional GetDominantDevice( + absl::Span computations, double dominant_factor); + +// Returns the HloSharding with the tile dimensions and tile assignment +// transposed based on the specified dimension numbers. In case of a tile +// maximal sharding returns the original sharding. +HloSharding TransposeSharding(const HloSharding& sharding, + absl::Span dimensions); + +// Returns the HloSharding with the tile shape reshaped based on the source and +// target shapes and the tile assignment adjusted to correspond to the new tile +// shape or std::nullopt if the resulting reshape would create an invalid +// sharding (non continuous or non uniformly sized tiles). In case of a tile +// maximal sharding returns the original sharding. +std::optional ReshapeSharding(const Shape& source_shape, + const Shape& target_shape, + const HloSharding& sharding); + +// Propagates sharding through reshape. It tries to find partial matches on +// subsets of dimensions that could satisfy ReshapeSharding() constraints, then +// combine them. It doesn't require all dimensions to satisfy the constraints +// of ReshapeSharding(). +HloSharding PropagateShardingThroughReshape(const Shape& source_shape, + const Shape& target_shape, + const HloSharding& sharding); + +// Returns the HloSharding with the tile dimensions and tile assignment +// reversed based on the specified dimension numbers. In case of a tile +// maximal sharding returns the original sharding. +HloSharding ReverseSharding(const HloSharding& sharding, + absl::Span dimensions); + +// Returns a sharding tiled on unique dimension dim by reshaping the tile +// assignment of the sharding argument. Only dimensions in the dims span +// argument are considered for reshaping, the others are ignored. +// Assumptions: sharding is tile sharded, and dim must be included in dims. +HloSharding ReshapeToTileDimension(const HloSharding& sharding, int64_t dim, + absl::Span dims); + +// Returns true if the provided module includes one or more instructions with +// a tile sharding. +bool ContainsTileSharding(const HloModule& module); + +// Returns the preferred output sharding for a gather op based on the sharding +// of the indces. +HloSharding GatherOutputShardingFromIndexIndexPassthroughDimensions( + const HloSharding& index_sharding, const HloInstruction* hlo); + +// Returns the preferred index sharding for a gather op based on the sharding +// of the output. +HloSharding GatherIndexShardingFromOutputIndexPassthroughDimensions( + const HloSharding& output_sharding, const HloInstruction* hlo); + +// Returns a new HloSharding for a gather op so that only non offset dimensions +// are sharded. Assume "result" is returned by this function. It is ensured that +// "GetIndexSharding(result, hlo)" will have the same number of elements as +// "result". +HloSharding GatherEffectiveOutputSharding(const HloInstruction& hlo); + +// Returns the preferred index sharding for a scatter op based on the sharding +// of the data. +HloSharding ScatterIndexShardingFromUpdateIndexPassthroughDimensions( + const HloSharding& update_sharding, const HloScatterInstruction* scatter); + +// Returns the preferred data sharding for a scatter op based on the sharding +// of the index. +HloSharding ScatterUpdateShardingFromIndexIndexPassthroughDimensions( + const HloSharding& index_sharding, const HloScatterInstruction* scatter); + +// Returns a new index sharding for a scatter op so that we only shard on first +// "number of scatter_window_dims" dimensions. Assume "result" is returned by +// this function. It is ensured that +// "ScatterUpdateShardingFromIndexIndexPassthroughDimensions(result, hlo)" will +// have the same number of elements as "result". +HloSharding ScatterEffectiveIndexSharding(const HloSharding& index_sharding, + const HloScatterInstruction& scatter); + +// Returns a new data sharding for a scatter op so that we only shard on +// scatter_window_dims. Assume "result" is returned by this function. It is +// ensured that +// "ScatterIndexShardingFromUpdateIndexPassthroughDimensions(result, hlo)" will +// have the same number of elements as "result". +HloSharding ScatterEffectiveDataSharding(const HloSharding& data_sharding, + const HloScatterInstruction& scatter); + +// Returns an output sharding of gather by passing through the data operand's +// sharding. +std::optional +GatherOutputShardingFromOperandOperandPassthroughDimensions( + const HloSharding& operand_sharding, const HloInstruction& hlo); + +// Returns an output sharding of gather by passing through the data operand's +// sharding. +std::optional +GatherOutputShardingFromOperandOperandPassthroughDimensions( + const Shape& operand_shape, const HloSharding& operand_sharding, + const HloInstruction& hlo, absl::Span slice_sizes); + +// Returns an output sharding of gather by passing through the data operand's +// sharding on index parallel dimensions +std::optional GatherOperandShardingFromOutputParallelDimensions( + const HloSharding& output_sharding, const HloScatterInstruction& scatter, + const CallGraph& call_graph); + +// Returns a data operand sharding of gather by passing through the output's +// sharding. +std::optional GatherOperandShardingFromOutput( + const HloSharding& output_sharding, const HloInstruction& hlo, + const CallGraph& call_graph); + +// Returns the slice size for a scatter with given operand and update shapes. +std::vector GetScatterSliceSize(const Shape& operand_shape, + const Shape& update_shape, + const ScatterDimensionNumbers& dnums); + +// Returns an output sharding of scatter by passing through the update operand's +// sharding. +std::optional ScatterOutputShardingFromUpdate( + const HloSharding& update_sharding, const HloScatterInstruction& scatter); + +// Returns an update operand sharding of scatter by passing through the output's +// sharding. +std::optional ScatterUpdateShardingFromOutput( + const HloSharding& per_output_sharding, + const HloScatterInstruction& scatter, const CallGraph& call_graph); + +// Returns an update operand sharding of scatter by passing through the output's +// sharding on operand pass-through dimensions. +std::optional +ScatterUpdateShardingFromOutputOperandPassthroughDimensions( + const HloSharding& output_sharding, const HloInstruction& hlo); + +// Returns an update operand sharding of scatter by passing through the output's +// sharding on operand pass-through dimensions. +std::optional +ScatterUpdateShardingFromOutputOperandPassthroughDimensions( + const Shape& output_shape, const HloSharding& output_sharding, + const HloInstruction& hlo, absl::Span slice_sizes); + +// Returns an update operand sharding of scatter by passing through the output's +// sharding on index parallel dimensions. +std::optional ScatterUpdateShardingFromOutputParallelDimensions( + const HloSharding& output_sharding, const HloScatterInstruction& scatter, + const CallGraph& call_graph); + +// Returns an output sharding of gather or update operand sharding of scatter by +// passing through the indices' sharding on index parallel dimensions. +HloSharding GatherOutputOrScatterUpdateShardingFromIndicesParallelDimensions( + const HloSharding& indices_sharding, + const int64_t output_or_update_shape_rank, + absl::Span indices_parallel_dims, + absl::Span output_or_update_parallel_dims); + +// Returns an identity value and an HloOpcode for reduce computation of scatter +// instruction. +// - If computation is add/or, return 0/false with corresponding op code; +// - If computation is multiply/and, return 1/true with corresponding op code. +// - If computation is min/max, return max value/min value with corresponding op +// code. +// - Otherwise, return error status. +StatusOr, HloOpcode>> +IdentityValueAndHloOpcodeForScatterReduceComputation( + const HloScatterInstruction& scatter); + +// Given a sharding and a list of devices in the topology, return a +// list of the devices that `sharding` applies to. +std::vector DevicesForSharding( + const HloSharding& sharding, absl::Span available_devices); + +// Returns a sharding that replicates data across devices along the given +// dimensions in the original sharding. +HloSharding PartiallyReplicateTiledShardingOnDims( + const HloSharding& sharding, absl::Span dims_to_replicate); + +// Returns a sharding that replicates data across devices along all dimensions +// but the given ones to keep in the original sharding. +HloSharding PartiallyReplicateTiledShardingOnAllDimsExcept( + const HloSharding& sharding, absl::Span dims_to_keep); + +// Returns a sharding that replicates all data dimensions, but keep manual +// subgroups. If data_rank is provided >= 0, the result sharding's data rank +// will be set to it. +HloSharding ReplicateAllDataDims(const HloSharding& sharding, + int64_t data_rank = -1); + +// Returns a sharding the removes given tile dimensions. +// +// Precondition: if not tile maximal, the size of each tile dimension must be 1. +HloSharding RemoveShapeDimensions(const HloSharding& sharding, + absl::Span dims_to_remove); + +// Similar to TransposeSharding(), but allows removing/adding non-partitioned +// dimensions. In src_to_tgt and tgt_to_src, -1 represents a non-existing +// dimension. +std::optional TransposeShardingWithCollapsedDims( + const HloSharding& source, absl::Span src_to_tgt, + absl::Span tgt_to_src); + +// Returns the iota dimension if maybe_iota is an kIota instruction or +// equivalent to kIota. +std::optional GetDimensionForIota(const HloInstruction* maybe_iota, + const CallGraph& call_graph); + +// Returns identified parallel dimensions of operands and indices for Gather. +std::optional GetGatherParallelBatchDims( + const HloInstruction& hlo, const CallGraph& call_graph); + +// Returns identified parallel dimensions of operands and indices for Scatter. +std::optional GetScatterParallelBatchDims( + const HloInstruction& hlo, const CallGraph& call_graph); + +// Returns the parallel dimensions of the output of a gather based on the +// parallel dimensions of the operands and indices. +absl::InlinedVector GetGatherParallelOutputDims( + const HloInstruction& hlo, const GatherScatterParallelDims& parallel_dim); + +// Returns the parallel dimensions of the update of a scatter based on the +// parallel dimensions of the operands and indices. +absl::InlinedVector GetScatterParallelUpdateDims( + const HloInstruction& hlo, const GatherScatterParallelDims& parallel_dim); + +// Returns the operand pass-through dimensions for gather operand. +absl::InlinedVector GetGatherOperandPassthroughOperandDims( + const Shape& operand_shape, const HloSharding& operand_sharding, + const HloInstruction& hlo, absl::Span slice_sizes); + +// Returns the operand pass-through dimensions for scatter operand(s). +absl::InlinedVector GetScatterOperandPassthroughOperandDims( + const Shape& operand_shape, const HloSharding& operand_sharding, + const HloInstruction& hlo, absl::Span slice_sizes); + +absl::InlinedVector GetGatherOperandPassthroughOutputDims( + const Shape& output_shape, const Shape& operand_shape, + const HloSharding& operand_sharding, const HloInstruction& hlo, + absl::Span slice_sizes); + +absl::InlinedVector GetScatterOperandPassthroughUpdateDims( + const Shape& update_shape, const Shape& operand_shape, + const HloSharding& operand_sharding, const HloInstruction& hlo, + absl::Span slice_sizes); + +// Returns the index pass-through dimensions for gather/scatter indices. +absl::InlinedVector GetGatherScatterIndexPassthroughIndexDims( + const int64_t indices_rank, const int64_t index_vector_dim); + +// Returns the index pass-through dimensions for gather output/scatter update. +absl::InlinedVector +GetGatherScatterIndexPassthroughOutputOrUpdateDims( + const int64_t output_or_update_rank, + absl::Span offset_or_window_dims); + +// Returns the parallel dimensions of the data operand of a gather/scatter with +// the order of the parallel dimensions matching that of the parallel dimensions +// of the indices. +absl::InlinedVector IndexAlignedOperandParallelDims( + const GatherScatterParallelDims& parallel_dims); + +// Represents grouping devices in a tiled sharding along certain dimensions. +// Elements in group dimensions define different device groups, and the sharding +// represents the in-group sharding. +struct GroupedSharding { + GroupedSharding(std::vector> device_groups, + std::vector group_dims, + std::vector group_dim_sizes, int64_t data_rank, + HloSharding grouped_sharding, bool subgroup_manual = false) + : device_groups(std::move(device_groups)), + group_dims(std::move(group_dims)), + group_dim_sizes(std::move(group_dim_sizes)), + data_rank(data_rank), + sharding(std::move(grouped_sharding)), + subgroup_manual(subgroup_manual) {} + std::string ToString() const; + std::vector> device_groups; + std::vector group_dims; + std::vector group_dim_sizes; + int64_t data_rank; + HloSharding sharding; + bool subgroup_manual; +}; + +// Creates a GroupedSharding for a tiled sharding with group dim shard sizes. +GroupedSharding GroupShardingOnDims(const HloSharding& sharding, + absl::Span group_dims, + absl::Span group_dim_shards, + bool subgroup_manual = false); + +// Creates a GroupedSharding for a tiled sharding. +GroupedSharding GroupShardingOnDims(const HloSharding& sharding, + absl::Span group_dims, + bool subgroup_manual = false); + +// Same as above, but exclude group dims instead. +GroupedSharding GroupShardingOnAllDimsExcept( + const HloSharding& sharding, absl::Span non_group_dims, + bool subgroup_manual = false); + +// Creates a GroupedSharding by trying to do the following in sequence: +// +// 1. Group on partially replicated dimensions, which preserves the existing +// tiled sharding in the group. +// 2. If option 1 doesn't have enough dimensions, try borrowing dimensions from +// replicable_dims in order, until it has enough dimensions. This partly +// preserves the existing tiled sharding in the group. (e.g. if we need 4 +// groups, while our sharding is {[4,8,2]<=[64] last_tile_dim_replicate}, and if +// we borrow 2 dimensions from the first dimension(i.e. the 4-way partition), +// combined with the partially replicated 2, we will be able to group the +// sharding into 4 groups, and we have grouped sub-sharding [2,8]<=[16] instead. +// 3. Otherwise replicate the whole thing. +// +// This does not guarantee the consistency of the ordering of the tile +// assignment, and should be used with AlignGroup where its tile assignment +// doesn't matter and will always align to some other tile assignment. +GroupedSharding GroupShardingOnReplicatedDim( + const HloSharding& sharding, int64_t num_groups, int64_t num_tiles, + int64_t data_rank, absl::Span replicable_dims = {}); + +// Get group sharding for replicated sharding. +GroupedSharding GetGroupedReplicatedSharding(const int64_t num_groups, + const int64_t num_tiles, + const int64_t data_rank); + +// Get group sharding for each manual subgroup. +GroupedSharding GetManualSubgroupSharding(const HloSharding& sharding); + +// Create a group sharding over the partially replicated dimension re-using an +// existing device group subdivision to avoid unexpected devices reordering. +std::optional +PartialReplicatedGroupShardingWithAssignedDeviceGroups( + const HloSharding& sharding, int64_t num_shards, + const std::vector>& device_groups); + +// Reconstructs the ungrouped sharding from a GroupedSharding. +HloSharding UngroupSharding(const GroupedSharding& grouped_sharding); + +// Check if the device groups are match for the LHS or RHS group shardings. +bool DeviceGroupsAreMatch(GroupedSharding& lhs, GroupedSharding& rhs, + bool ignore_group_order = true); + +// Spawns a new dimension by splitting an existing dimension and generating a +// new dimension to its right of the passed down size. The original dimension +// will be of size "original_dim_size / new_dim_size". The original dimension +// size needs to be divisible by new_dim_size. +HloSharding SplitShardingDimension(const HloSharding& sharding, + int64_t dimension, int64_t new_dim_size); + +// Merges a dimension +// to its left. The new dimension will be of size +// dimensions[dimension] * dimensions[dimension+1}. +HloSharding MergeShardingDimension(const HloSharding& sharding, + int64_t dimension); + +// Creates a tuple sharding by combining sharding on the elements of the tuple. +// If none of the elements have a sharding, return nullptr. +std::shared_ptr CreateTupleSharding( + const Shape& shape, absl::Span elements); + +// Tests whether the sort operand is sharded along the sort dimension and there +// exists a free (i.e., unsharded) dimension to move the sharding into. +bool IsSortOperandShardingMovable(const HloInstruction* sort_operand, + int64_t sort_dim); + +// Returns a set of parallel dimensions for Gather/Scatter instructions given +// the parameters for the op. +std::optional GetGatherScatterBatchParallelDims( + const HloInstruction* indices, absl::Span slice_sizes, + int64_t index_vector_dim, absl::Span index_map, + const CallGraph& call_graph); + +// Returns the sharding of an output of an instruction. Some instructions have +// special handling like Outfeed and this function takes care of those. +std::optional GetOutputSharding(const HloInstruction* instruction); + +} // namespace hlo_sharding_util +} // namespace xla + +#endif // XLA_HLO_UTILS_HLO_SHARDING_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/index_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/index_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e096b93c00c4816014d13515b11c9ee9a2d91a2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/index_util.h @@ -0,0 +1,159 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Utility functions related to layouts of Shapes. + +#ifndef XLA_INDEX_UTIL_H_ +#define XLA_INDEX_UTIL_H_ + +#include + +#include "absl/types/span.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Namespaced collection of (static) utilities related to indexing into +// multidimensional arrays. +class IndexUtil { + public: + // Converts a multidimensional index (eg {x, y, z}) into a linear index based + // on the shape and its layout. The first index in the multi_index is + // dimension 0. + static inline int64_t MultidimensionalIndexToLinearIndex( + const Shape& shape, absl::Span multi_index) { + return MultidimensionalIndexToLinearIndex( + shape, LayoutUtil::MinorToMajor(shape), multi_index); + } + + // Converts a multidimensional index (eg {x, y, z}) into a linear index based + // on the shape and its layout. The first index in the multi_index is + // dimension 0. + // + // This version can be used when the caller already has the minor_to_major + // array for shape available (and can therefore be faster). + // + // REQUIRES: minor_to_major provided is equal to + // shape.layout().minor_to_major() + static inline int64_t MultidimensionalIndexToLinearIndex( + const Shape& shape, absl::Span minor_to_major, + absl::Span multi_index) { + // Let the array be sized like so for dimensions i from 0 to n-1: + // + // [D{n-1} x D{n-2} x .. x D{0}] + // + // Let the order of the dimensions in the minor_to_major field in + // Layout be: + // + // L(0), L(1), ... , L(n-1) + // + // where L(0) is the most-minor dimension and L(n-1) the most-major. The + // multidimensional index: + // + // [I{0}, I{1}, ... , I{n-1}] + // + // then corresponds to the following linear index: + // + // linear_index = + // ((( ... + I{L(2)}) * D{L(1)} + I{L(1)}) * D{L(0)} + I{L(0)} + // + // or equivalently: + // + // linear_index = + // I{L(n-1)} * (D{L(n-2)} * D{L(n-3)} * D{L(n-4)} * .... D{L(0)}) + + // I{L(n-2)} * (D{L(n-3)} * D{L(n-4)} * .... D{L(0)}) + + // I{L(n-3)} * (D{L(n-4)} * .... D{L(0)}) + + // ... + + // I{L(2)} * (D{L(1)} * D{L(0)}) + + // I{L(1)} * D{L(0)} + + // I{L(0)} + // + // We compute the linear index value by accumulating the terms above from + // I{L(0)} up to I{L(n-1)}. Scale accumulates the product term D{L(0}} * + // D{L(1)} * ... + + // Scale factor holding the growing product of D{L(i)} terms. + for (size_t i = 0; i < multi_index.size(); ++i) { + DCHECK_GE(multi_index[i], 0); + DCHECK_LT(multi_index[i], shape.dimensions(i)) + << "indexing beyond extent in dimension " << i << ":" + << "\n\tindex: " << absl::StrJoin(multi_index, ",") + << "\n\tshape: " << ShapeUtil::HumanString(shape); + } + if (minor_to_major.empty()) { + return 0; + } + int64_t linear_index = multi_index[minor_to_major[0]]; + int64_t scale = 1; + for (int i = 1; i < minor_to_major.size(); ++i) { + scale *= shape.dimensions(minor_to_major[i - 1]); + linear_index += scale * multi_index[minor_to_major[i]]; + } + return linear_index; + } + + // Converts a linear index into multidimensional index (eg {x, y, z}) based on + // the shape and its layout. The first index in the returned multidimensional + // index is dimension 0. + static std::vector LinearIndexToMultidimensionalIndex( + const Shape& shape, int64_t linear_index); + + // Bumps a sequence of indices; e.g. {0,0,0,0} up by one index value; e.g. to + // {0,0,0,1}. This is akin to std::next_permutation. If the index hits a limit + // for the provided shape, the next most significant index is bumped, in a + // counting-up process. + // + // E.g. for shape f32[2,3] + // {0,0}=>{0,1} + // {0,1}=>{0,2} + // {0,2}=>{1,0} + // etc. + // + // This is useful for traversing the indices in a literal. + // + // Returns true iff the indices were successfully bumped; false if we've hit + // the limit where it can no longer be bumped in-bounds. + static bool BumpIndices(const Shape& shape, absl::Span indices); + + // Calculates the stride size (in number of elements, not byte size) of a + // given logical shape dimension (from 0 to rank-1). + // Example: + // GetDimensionStride(F32[5,8,10,4]{3,2,1,0}, 1) == + // sizeof(dimension(3)) * sizeof(dimension(2)) == 4 * 10 + static int64_t GetDimensionStride(const Shape& shape, int64_t dimension); + + // Returns true iff the given multi-index is contained in the bounds for the + // shape. + static bool IndexInBounds(const Shape& shape, + absl::Span index); + + // Compares the given indices in lexicographic order. lhs[0] and rhs[0] are + // compared first, and lhs[rank-1] and rhs[rank-1] last. If lhs is larger, + // then -1 is returned. If rhs is larger, then 1 is returned. Otherwise, 0 is + // returned. + static int CompareIndices(absl::Span lhs, + absl::Span rhs); + + private: + IndexUtil(const IndexUtil&) = delete; + IndexUtil& operator=(const IndexUtil&) = delete; +}; + +} // namespace xla + +#endif // XLA_INDEX_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/iterator_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/iterator_util.h new file mode 100644 index 0000000000000000000000000000000000000000..23367890adcc7f89f3e038d55fc9771a8097964e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/iterator_util.h @@ -0,0 +1,178 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_ITERATOR_UTIL_H_ +#define XLA_ITERATOR_UTIL_H_ + +#include +#include +#include + +#include "tsl/lib/gtl/iterator_range.h" + +namespace xla { + +// UnwrappingIterator is a transforming iterator that calls get() on the +// elements it returns. +// +// Together with tsl::gtl::iterator_range, this lets classes which +// contain a collection of smart pointers expose a view of raw pointers to +// consumers. For example: +// +// class MyContainer { +// public: +// tsl::gtl::iterator_range< +// UnwrappingIterator>::iterator>> +// things() { +// return {MakeUnwrappingIterator(things_.begin()), +// MakeUnwrappingIterator(things_.end())}; +// } +// +// tsl::gtl::iterator_range>::const_iterator>> +// things() const { +// return {MakeUnwrappingIterator(things_.begin()), +// MakeUnwrappingIterator(things_.end())}; +// } +// +// private: +// std::vector> things_; +// }; +// +// MyContainer container = ...; +// for (Thing* t : container.things()) { +// ... +// } +// +// For simplicity, UnwrappingIterator is currently unconditionally an +// input_iterator -- it doesn't inherit any superpowers NestedIterator may have. +template +class UnwrappingIterator { + public: + using iterator_category = std::input_iterator_tag; + using value_type = decltype(std::declval()->get()); + using difference_type = ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; + + explicit UnwrappingIterator(NestedIter iter) : iter_(std::move(iter)) {} + + auto operator*() -> value_type { return iter_->get(); } + UnwrappingIterator& operator++() { + ++iter_; + return *this; + } + UnwrappingIterator operator++(int) { + UnwrappingIterator temp(iter_); + operator++(); + return temp; + } + + friend bool operator==(const UnwrappingIterator& a, + const UnwrappingIterator& b) { + return a.iter_ == b.iter_; + } + + friend bool operator!=(const UnwrappingIterator& a, + const UnwrappingIterator& b) { + return !(a == b); + } + + private: + NestedIter iter_; +}; + +template +UnwrappingIterator MakeUnwrappingIterator(NestedIter iter) { + return UnwrappingIterator(std::move(iter)); +} + +// An iterator that filters out values where the predicate(value) evaluates to +// false. An unwrapping iterator can be nested inside a filtering iterator to +// also unwrap smart pointers. +template +class FilteringIterator { + public: + using iterator_category = std::input_iterator_tag; + using value_type = decltype(*std::declval()); + using difference_type = ptrdiff_t; + using pointer = value_type*; + using reference = value_type&; + + FilteringIterator(NestedIter iter, NestedIter end_iter, UnaryPredicate pred) + : iter_(std::move(iter)), + end_iter_(std::move(end_iter)), + pred_(std::move(pred)) { + if (iter_ != end_iter_ && !pred_(**this)) { + ++*this; + } + } + + auto operator*() -> value_type { return *iter_; } + FilteringIterator& operator++() { + do { + ++iter_; + } while (iter_ != end_iter_ && !pred_(**this)); + return *this; + } + FilteringIterator operator++(int) { + FilteringIterator temp(iter_, end_iter_, pred_); + operator++(); + return temp; + } + + friend bool operator==(const FilteringIterator& a, + const FilteringIterator& b) { + return a.iter_ == b.iter_; + } + + friend bool operator!=(const FilteringIterator& a, + const FilteringIterator& b) { + return !(a == b); + } + + private: + NestedIter iter_; + NestedIter end_iter_; + UnaryPredicate pred_; +}; + +template +using FilteringUnwrappingIterator = + FilteringIterator, UnaryPredicate>; + +// Create and return a filtering unwrapping iterator. +template +FilteringUnwrappingIterator +MakeFilteringUnwrappingIterator(NestedIter iter, NestedIter end_iter, + UnaryPredicate pred) { + return FilteringUnwrappingIterator( + MakeUnwrappingIterator(iter), MakeUnwrappingIterator(end_iter), + std::move(pred)); +} + +// Create and return a filtering unwrapping iterator range. +template +tsl::gtl::iterator_range< + FilteringUnwrappingIterator> +MakeFilteringUnwrappingIteratorRange(NestedIter begin_iter, NestedIter end_iter, + UnaryPredicate pred) { + return {MakeFilteringUnwrappingIterator(begin_iter, end_iter, pred), + MakeFilteringUnwrappingIterator(end_iter, end_iter, pred)}; +} + +} // namespace xla + +#endif // XLA_ITERATOR_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout.h new file mode 100644 index 0000000000000000000000000000000000000000..c64806c0b2644d0abe490ff9c86dd727f3964e88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout.h @@ -0,0 +1,411 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_LAYOUT_H_ +#define XLA_LAYOUT_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "xla/printer.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +namespace xla { + +class Shape; + +// Describes a tile used in tiling-based layout. Refer to +// g3doc/third_party/tensorflow/compiler/xla/g3doc/tiled_layout.md for +// details. +class Tile { + public: + Tile() = default; + explicit Tile(absl::Span dimensions) + : dimensions_(dimensions.begin(), dimensions.end()) {} + + // De/Serialize a Tile to and from a TileProto. + static Tile CreateFromProto(const TileProto& tile_proto) { + return Tile(tile_proto.dimensions()); + } + TileProto ToProto() const; + + bool operator==(const Tile& other) const { + return dimensions() == other.dimensions(); + } + bool operator!=(const Tile& other) const { return !(*this == other); } + + void Print(Printer* printer) const; + + std::string ToString() const; + + // Returns the bound of the tile in the given dimension index. + int64_t dimension(int i) const { return dimensions_.at(i); } + + // Returns the dimensions of the tile. + absl::Span dimensions() const { return dimensions_; } + + Tile& add_dimensions(int64_t value) { + dimensions_.push_back(value); + return *this; + } + + Tile& clear_dimensions() { + dimensions_.clear(); + return *this; + } + + // This dimension size means the corresponding dimension in the shape is + // combined with the next minor dimension before tiling is applied. + static constexpr int64_t kCombineDimension = + std::numeric_limits::min(); + + template + friend H AbslHashValue(H h, const Tile& t) { + return H::combine(std::move(h), t.dimensions_); + } + + private: + // The bounds of the tile. + absl::InlinedVector dimensions_; +}; + +using TileVector = absl::InlinedVector; + +// TODO: Rename the `dim_level_types` field to `lvl_types`, so that it +// matches `mlir::sparse_tensor::SparseTensorEncodingAttr`. +class Layout { + public: + Layout(); + Layout(const Layout& other); + Layout(Layout&& other); + ~Layout(); + + // Constructs a dense layout with the given minor-to-major order. + explicit Layout(absl::Span minor_to_major); + + // Constructs a dense tiled layout with the given minor-to-major order, dim + // level types, and tiles. + explicit Layout(absl::Span minor_to_major, + absl::Span dim_level_types, + absl::Span dim_unique, + absl::Span dim_ordered, + absl::Span tiles, + PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID, + PrimitiveType element_primitive_type = PRIMITIVE_TYPE_INVALID, + int64_t element_size_in_bits = 0, int64_t memory_space = 0, + std::unique_ptr physical_shape = nullptr, + int64_t dynamic_shape_metadata_prefix_bytes = 0); + + Layout& operator=(const Layout& other); + Layout& operator=(Layout&& other); + + // Construct a shape from a LayoutProto. + static Layout CreateFromProto(const LayoutProto& proto); + + // Returns a LayoutProto representation of the Layout. + LayoutProto ToProto() const; + + // Prints a human-readable string that represents this layout. + void Print(Printer* printer) const; + + // Returns a human-readable string that represents this layout. + std::string ToString() const; + + // Equal is a configurable functor to check the equality of two layouts. + // + // Examples: + // + // - Comparing two layouts ignoring their difference in tiles: + // Equal().IgnoreTiles()(layout1, layout2); + class Equal { + public: + Equal() = default; + + bool operator()(const Layout& lhs, const Layout& rhs); + + Equal& IgnoreTiles() { + ignore_tiles_ = true; + return *this; + } + + Equal& IgnoreIndexPrimitiveType() { + ignore_index_primitive_type_ = true; + return *this; + } + + Equal& IgnorePointerPrimitiveType() { + ignore_pointer_primitive_type_ = true; + return *this; + } + + Equal& IgnoreMemorySpace() { + ignore_memory_space_ = true; + return *this; + } + + Equal& IgnorePhysicalShape() { + ignore_physical_shape_ = true; + return *this; + } + + Equal& IgnoreElementSize() { + ignore_element_size_ = true; + return *this; + } + + Equal& MinorToMajorOnly() { + return IgnoreTiles() + .IgnoreIndexPrimitiveType() + .IgnorePointerPrimitiveType() + .IgnoreMemorySpace() + .IgnorePhysicalShape() + .IgnoreElementSize(); + } + + private: + bool ignore_tiles_ = false; + bool ignore_element_size_ = false; + bool ignore_index_primitive_type_ = false; + bool ignore_pointer_primitive_type_ = false; + bool ignore_memory_space_ = false; + bool ignore_physical_shape_ = false; + }; + + bool operator==(const Layout& other) const; + bool operator!=(const Layout& other) const { return !(*this == other); } + + // The following methods mirror the protobuf generated code interface for the + // message LayoutProto. This enabled easy migration of this data structure + // from a proto to a proper C++ class. + // + // TODO(b/29771030): Replace or augment these methods with a more ergonomic + // interface. + + // Methods for accessing the DimLevelType array. + int dim_level_types_size() const { return dim_level_types_.size(); } + DimLevelType dim_level_type(int index) const { + return dim_level_types_.at(index); + } + Layout& set_dim_level_type(int index, DimLevelType dim_level_type) { + dim_level_types_.at(index) = dim_level_type; + return *this; + } + Layout& add_dim_level_type(DimLevelType dim_level_type) { + dim_level_types_.push_back(dim_level_type); + return *this; + } + Layout& clear_dim_level_types() { + dim_level_types_.clear(); + return *this; + } + absl::Span dim_level_types() const { + return dim_level_types_; + } + DimLevelTypeVector* mutable_dim_level_types() { return &dim_level_types_; } + + // Methods for accessing the dim_unique array. + int dim_unique_size() const { return dim_unique_.size(); } + bool dim_unique(int index) const { return dim_unique_.at(index); } + Layout& set_dim_unique(int index, bool unique) { + dim_unique_.at(index) = unique; + return *this; + } + Layout& add_dim_unique(bool unique) { + dim_unique_.push_back(unique); + return *this; + } + Layout& clear_dim_unique() { + dim_unique_.clear(); + return *this; + } + absl::Span dim_unique() const { return dim_unique_; } + absl::InlinedVector* mutable_dim_unique() { + return &dim_unique_; + } + + // Methods for accessing the dim_ordered array. + int dim_ordered_size() const { return dim_ordered_.size(); } + bool dim_ordered(int index) const { return dim_ordered_.at(index); } + Layout& set_dim_ordered(int index, bool ordered) { + dim_ordered_.at(index) = ordered; + return *this; + } + Layout& add_dim_ordered(bool ordered) { + dim_ordered_.push_back(ordered); + return *this; + } + Layout& clear_dim_ordered() { + dim_ordered_.clear(); + return *this; + } + absl::Span dim_ordered() const { return dim_ordered_; } + absl::InlinedVector* mutable_dim_ordered() { + return &dim_ordered_; + } + + // Methods for accessing the minor-to-major array. + int minor_to_major_size() const { return minor_to_major_.size(); } + int64_t minor_to_major(int index) const { return minor_to_major_.at(index); } + Layout& set_minor_to_major(int index, int64_t value) { + minor_to_major_.at(index) = value; + return *this; + } + Layout& add_minor_to_major(int64_t value) { + minor_to_major_.push_back(value); + return *this; + } + Layout& clear_minor_to_major() { + minor_to_major_.clear(); + return *this; + } + // Removes the given dimension from 'minor_to_major_', and adjusts the other + // dimensions accordingly. Also adjusts 'dim_level_types_', 'dim_ordered_' and + // 'dim_unique_' in case it is a sparse layout. + Layout& DeleteDimension(int64_t dim_to_delete); + absl::Span minor_to_major() const { return minor_to_major_; } + DimensionVector* mutable_minor_to_major() { return &minor_to_major_; } + + // Methods for accessing the tile field. + int64_t tiles_size() const { return tiles_.size(); } + const Tile& tiles(int index) const { return tiles_.at(index); } + Tile* mutable_tiles(int index) { return &tiles_.at(index); } + Tile* add_tiles() { + tiles_.push_back(Tile()); + return &tiles_.back(); + } + Layout& clear_tiles() { + tiles_.clear(); + return *this; + } + absl::Span tiles() const { return tiles_; } + TileVector* mutable_tiles() { return &tiles_; } + + int64_t element_size_in_bits() const { return element_size_in_bits_; } + Layout& set_element_size_in_bits(int64_t value) { + element_size_in_bits_ = value; + return *this; + } + + PrimitiveType index_primitive_type() const { return index_primitive_type_; } + Layout& set_index_primitive_type(PrimitiveType value) { + index_primitive_type_ = value; + return *this; + } + + PrimitiveType pointer_primitive_type() const { + return pointer_primitive_type_; + } + Layout& set_pointer_primitive_type(PrimitiveType value) { + pointer_primitive_type_ = value; + return *this; + } + + static constexpr int64_t kDefaultMemorySpace = 0; + static constexpr int64_t kGenericFastMemorySpace = 1; + int64_t memory_space() const { return memory_space_; } + Layout& set_memory_space(int64_t value) { + memory_space_ = value; + return *this; + } + + // Methods for accessing the physical shape. + bool has_physical_shape() const { return physical_shape_ != nullptr; } + const Shape& physical_shape() const { + CHECK(has_physical_shape()); + return *physical_shape_; + } + Shape* mutable_physical_shape(); + void clear_physical_shape(); + + int64_t dynamic_shape_metadata_prefix_bytes() const { + return dynamic_shape_metadata_prefix_bytes_; + } + void set_dynamic_shape_metadata_prefix_bytes(int64_t bytes) { + dynamic_shape_metadata_prefix_bytes_ = bytes; + } + + void Swap(Layout* other) { + using std::swap; + swap(*this, *other); + } + + void Clear() { *this = Layout(); } + + template + friend H AbslHashValue(H h, const Layout& l) { + return H::combine(std::move(h), l.minor_to_major_, l.tiles_, + l.element_size_in_bits_, l.index_primitive_type_, + l.pointer_primitive_type_, l.memory_space_); + } + + private: + // The list of dimension level types, indicating the method that will be used + // to represent each dimension of the array. + DimLevelTypeVector dim_level_types_; + + // Whether each DimLevelType is unique and ordered. + absl::InlinedVector dim_unique_; + absl::InlinedVector dim_ordered_; + + // A map from physical dimension numbers to logical dimension numbers. + // The first element is the most minor physical dimension (fastest varying + // index) and the last the most major (slowest varying index). The contents of + // the vector are the indices of the *logical* dimensions in the shape. + // + // For example, in shape f32[8,100,100,3]{3,0,2,1}, the logical dimensions + // are [8,100,100,3] and minor_to_major_ is {3,0,2,1}. + // So, the most minor physical dimension is [8,100,100,3][3], which is size 3. + // The second most minor is [8,100,100,3][0], which is size 8. + // The third most minor is [8,100,100,3][2], which is size 100. + // And the major dim is [8,100,100,3][1], which is size 100. + DimensionVector minor_to_major_; + + // The tiles used in tiling-based layout. + TileVector tiles_; + + // The primitive type to use for sparse array indices and pointers. Each of + // these must either be INVALID, or an unsigned integer type. + PrimitiveType index_primitive_type_ = PRIMITIVE_TYPE_INVALID; + PrimitiveType pointer_primitive_type_ = PRIMITIVE_TYPE_INVALID; + + // The number of bits used to store an individual array element. + // When the value is 0, default to ShapeUtil::ByteSizeOfPrimitiveType. + int64_t element_size_in_bits_ = 0; + + // The assigned memory space. + int64_t memory_space_ = 0; + + // The physical on-device shape used to represent a sparse array. + std::unique_ptr physical_shape_; + + // The dynamic shape metadata size in bytes in front of the shape data. The + // field may be non-zero for a static shape whose associated buffer is for a + // dynamic shape, e.g. a result of SliceToDynamic. + int64_t dynamic_shape_metadata_prefix_bytes_ = 0; +}; + +std::ostream& operator<<(std::ostream& out, const Tile& Tile); +std::ostream& operator<<(std::ostream& out, const Layout& layout); + +} // namespace xla + +#endif // XLA_LAYOUT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout_util.h new file mode 100644 index 0000000000000000000000000000000000000000..545d3659754049d167029710184ac5e3d9a226c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/layout_util.h @@ -0,0 +1,292 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Utility functions related to layouts of Shapes. + +#ifndef XLA_LAYOUT_UTIL_H_ +#define XLA_LAYOUT_UTIL_H_ + +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/layout.h" +#include "xla/printer.h" +#include "xla/shape.h" +#include "xla/status.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +namespace xla { + +// Namespaced collection of (static) Layout utilities. +class LayoutUtil { + public: + LayoutUtil(const LayoutUtil&) = delete; + LayoutUtil& operator=(const LayoutUtil&) = delete; + + // Creates a layout with the given minor-to-major dimension order. (This is a + // convenience function for protobuf construction.) + static Layout MakeLayout( + absl::Span minor_to_major, + absl::Span dim_level_types = {}, + absl::Span dim_unique = {}, + absl::Span dim_ordered = {}, + absl::Span tiles = {}, + PrimitiveType index_primitive_type = PRIMITIVE_TYPE_INVALID, + PrimitiveType pointer_primitive_type = PRIMITIVE_TYPE_INVALID, + int64_t element_size_in_bits = 0, int64_t memory_space = 0, + std::optional physical_shape = std::nullopt, + int64_t dynamic_shape_metadata_prefix_bytes = 0); + + // Similar to MakeLayout, but take indices in reverse order. + static Layout MakeLayoutFromMajorToMinor( + absl::Span major_to_minor); + + // Returns a layout with descending ((i.e. {n-1, n-2, ... 0}) minor-to-major + // dimensions. + static Layout MakeDescendingLayout(int64_t rank); + + // Returns a layout with ascending ((i.e. {0, 1, ... n-1}) minor-to-major + // dimensions. + static Layout MakeAscendingLayout(int64_t rank); + + // Returns default layout for the given shape. + static Layout GetDefaultLayoutForShape(const Shape& shape); + + // Helper functions that create default layouts for various ranks. + static Layout GetDefaultLayoutForRank(int64_t rank); + static Layout GetDefaultLayoutForR2(); + static Layout GetDefaultLayoutForR3(); + static Layout GetDefaultLayoutForR4(); + + // Sets the default layout on the Shape. + static void SetToDefaultLayout(Shape* shape); + + // Returns a shape with the same dimensions as `shape` but with the default + // layout. + static Shape GetWithDefaultLayout(const Shape& shape); + + // Sets the layouts of all Shapes within the given ProgramShape to the + // default. + static void SetToDefaultLayout(ProgramShape* program_shape); + + // Validates that the layout within the given shape is correct. The check + // is performed for all subshapes as well. If missing layouts are allowed + // the check does not fail on array shapes without layouts. + static Status ValidateLayoutInShape(const Shape& shape, + bool allow_missing_layouts = false); + + // Validates that the provided layout satisfies invariants for the given + // shape. + static Status ValidateLayoutForShape(const Layout& layout, + const Shape& shape); + + // Clears the layout in the given Shape. After this function is called, + // HasLayout will return false for the shape. + static void ClearLayout(Shape* shape); + + // Clears the layout on all Shapes within the given ProgramShape. + static void ClearLayout(ProgramShape* program_shape); + + // Clears the tiling fields from the shape and/or all of its subshapes. + static void ClearTiles(Shape* shape); + + // Returns whether the given Shape is an array and has a dense in-memory + // representation. + static bool IsDenseArray(const Shape& shape); + + // Returns whether the given Shape is an array and has a sparse in-memory + // representation. + static bool IsSparseArray(const Shape& shape); + + // Returns whether the given Shape is a sparse array and has a COO (coordinate + // matrix) in-memory representation. + static bool IsCOOArray(const Shape& shape); + + // Returns whether the given Shape is a sparse array and has a CSR (compressed + // sparse row) in-memory representation. + static bool IsCSRArray(const Shape& shape); + + // Returns whether the given Shape is a sparse array and has a CSR (compressed + // sparse row) in-memory representation. + static bool IsCSCArray(const Shape& shape); + + // Returns whether the given Layout has a dense in-memory representation. + static bool IsDense(const Layout& layout); + + // Returns whether the given Layout has a sparse in-memory representation. + static bool IsSparse(const Layout& layout); + + // Returns whether the given Layout represents a COO (coordinate matrix) + // sparse array. + static bool IsCOO(const Layout& layout); + + // Returns whether the given Layout represents a CSC (compressed sparse + // column) array. + static bool IsCSR(const Layout& layout); + + // Returns whether the given Layout represents a CSC (compressed sparse + // column) array. + static bool IsCSC(const Layout& layout); + + // Returns whether the layout is monotonic and dim 0 is minor in the layout. + // * R0 and R1: this is always trivially true. + // * R2+: equivalent to column-major. Dimension 0 is the minor, dimension 1 is + // more major, and so on until dimension N-1 which is the major. + static bool IsMonotonicWithDim0Minor(const Layout& layout); + + // Returns whether the layout is monotonic and dim 0 is major in the layout. + // * R0 and R1: this is always trivially true. + // * R2+: equivalent to row-major. Dimension 0 is the major, dimension 1 is + // more minor, and so on until dimension N-1 which is the minor. + // + // Returns `true` for "default", major-to-minor layouts (e.g. {3,2,1,0}). + static bool IsMonotonicWithDim0Major(const Layout& layout); + + // Returns whether the given shape has a layout. For tuple shapes, true is + // returned only if all elements have layouts. + static bool HasLayout(const Shape& shape); + + // Returns whether all Shapes within the given ProgramShape have layouts. + static bool HasLayout(const ProgramShape& program_shape); + + // Returns whether any subshapes of the shape have custom (!= 0) + // element_size_in_bits. + static bool HasCustomElementSizeInBits(const Shape& shape); + + // Returns whether lhs and rhs are identical. + static bool Equal(const Layout& lhs, const Layout& rhs); + + // Returns the minor_to_major array for the given Shape. Requires that the + // shape is an array. + static inline absl::Span MinorToMajor(const Shape& shape) { + DCHECK(shape.IsArray()); + return shape.layout().minor_to_major(); + } + + static inline absl::Span MinorToMajor(const Layout& layout) { + return layout.minor_to_major(); + } + + // Major(0) is the most major logical dimension number, Major(1) is the + // second-most-major logical dimension number and so on. + // + // This can be used to translate physical dimension numbers to logical + // dimension numbers. Assume that we are numbering the physical dimensions so + // that the most major physical dimension has physical dimension number 0 and + // so on. Then a physical dimension number p corresponds to the logical + // dimension number Major(p). So this function could also be called + // PhysicalToLogical(). + // + // As an example, consider physical dimension number 0, which by definition is + // the most major. Then Major(0) is the most major logical dimension, so Major + // maps the physical dimension number 0 to the most major logical dimension + // number Major(0). + static int64_t Major(const Layout& layout, + int64_t physical_dimension_number) { + DCHECK_LE(0, physical_dimension_number); + DCHECK_LT(physical_dimension_number, layout.minor_to_major_size()); + return Minor(layout, + layout.minor_to_major_size() - 1 - physical_dimension_number); + } + + // Minor(0) is the most minor logical dimension number, minor(1) is the + // second-most-minor logical dimension number and so on. + static inline int64_t Minor(const Layout& layout, + int64_t physical_dimension_number) { + DCHECK_LE(0, physical_dimension_number); + DCHECK_LT(physical_dimension_number, layout.minor_to_major_size()); + return layout.minor_to_major(physical_dimension_number); + } + + // Returns the inverse mapping of the Major() function. More precisely, return + // a vector v such that if l == Major(p), then v[l] == p. + // + // This can be used to translate logical dimension numbers into physical + // dimension numbers. Assume that we are numbering the physical dimensions so + // that the most major physical dimension has physical dimension number 0 and + // so on. Then a logical dimension number l corresponds to the physical + // dimension number MakeLogicalToPhysical(layout)[l]. + // + // In the returned vector, the first element represents the most major logical + // dimension. The element whose contents are 0 represents the most major + // physical dimension, and the element with contents (rank - 1) represents + // the most minor physical dimension. + static std::vector MakeLogicalToPhysical(const Layout& layout); + + // Prints a human-readable string that represents the given layout. + static void PrintHumanString(Printer* printer, const Layout& layout); + + // Returns a human-readable string that represents the given layout. + static std::string HumanString(const Layout& layout); + + // Copies the layout from 'src' to 'dst'. Recursively copies layouts of + // tuples. 'src' and 'dst' need not be compatible but the two shapes must + // have the same tuple structure (if any) and arrays must have the same + // rank. within the shapes must have the same number of dimensions. + static Status CopyLayoutBetweenShapes(const Shape& src, Shape* dst); + + // Returns true if the layouts of lhs and rhs are equal, false + // otherwise. Recursively compares layouts of tuples. + // + // lhs and rhs need not be compatible to have the same layout but the two + // shapes must have the same tuple structure (if any) and arrays must have the + // same rank. Element type is ignored. + static bool LayoutsInShapesEqual(const Shape& lhs, const Shape& rhs); + + // Returns whether the given dimensions are consecutive in the given layout, + // not necessarily in the order given. + static bool AreDimensionsConsecutive(const Layout& layout, + absl::Span dims); + + // Constructs a new layout by making the given dimension `dim` in the given + // layout `layout` as the most major dimension. + static Layout MoveDimToMajor(const Layout& layout, int64_t dim); + + // Returns the linearized index of the cell at the given indices. The unit + // of the offset is in elements of the shape. + // + // NOTE: this method only uses the top-level tile and disregards the sub-tile + // in the layout. This method is also performance critical. + static int64_t LinearIndex(const Shape& shape, + absl::Span indices); + + // If the shape has a layout, returns the contained memory space. Otherwise, + // returns Layout::kDefaultMemorySpace. + static int64_t MemorySpace(const Shape& shape); + + static xla::DimLevelType GetDimLevelType(const Layout& layout, int64_t dim); + static bool DimUnique(const Layout& layout, int64_t dim); + static bool DimOrdered(const Layout& layout, int64_t dim); + + // Return true iff the given DimLevelType and dim_unique/dim_ordered values + // represent a valid encoding. + static bool ValidateDimLevel(xla::DimLevelType dim_level_type, + bool dim_unique, bool dim_ordered); + + // Returns true if `byte_strides` is major to minor order, i.e. the strides + // form a cumulative product of the byte size and dimensions in reverse order + // and the smallest stride is the byte size for `element_type`. + static bool ByteStridesIsMajorToMinor(absl::Span byte_strides, + absl::Span dims, + PrimitiveType element_type); +}; + +} // namespace xla + +#endif // XLA_LAYOUT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/lazy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/lazy.h new file mode 100644 index 0000000000000000000000000000000000000000..e296a41403a1c8a6a6956826746ffd253191b44f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/lazy.h @@ -0,0 +1,45 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_LAZY_H_ +#define XLA_LAZY_H_ + +#include + +#include "absl/functional/any_invocable.h" + +namespace xla { + +template +class Lazy { + public: + explicit Lazy(absl::AnyInvocable func) + : maybe_value_(std::move(func)) {} + + const T& get() const { + if (!std::holds_alternative(maybe_value_)) { + maybe_value_ = + std::move(std::get>(maybe_value_))(); + } + return std::get(maybe_value_); + } + + private: + mutable std::variant, T> maybe_value_; +}; + +} // namespace xla + +#endif // XLA_LAZY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal.h new file mode 100644 index 0000000000000000000000000000000000000000..2c6b43cad4e1ca50bb374df175f085d4df9b7ce7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal.h @@ -0,0 +1,1603 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_LITERAL_H_ +#define XLA_LITERAL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/array.h" +#include "xla/array2d.h" +#include "xla/array3d.h" +#include "xla/array4d.h" +#include "xla/index_util.h" +#include "xla/layout.h" +#include "xla/layout_util.h" +#include "xla/primitive_util.h" +#include "xla/printer.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status.h" +#include "xla/status_macros.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/core/bitmap.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep +#include "tsl/platform/macros.h" + +namespace xla { + +// Forward declare Literal and LiteralSlice class to be used by the creation +// methods in the base class. +class Literal; +class LiteralSlice; + +// Abstract base class for literals. +class LiteralBase { + public: + virtual ~LiteralBase() = 0; + + // Literals are equal if they have compatible shapes and the same data + // values. Layout is not compared. + bool operator==(const LiteralBase& other) const; + bool operator!=(const LiteralBase& other) const { return !(*this == other); } + + // Returns the shape of the literal. + const Shape& shape() const; + + // Serialize to proto. + LiteralProto ToProto() const; + + // Returns a Span of the array for this literal for the given NativeT + // (e.g., float). CHECKs if the subshape of the literal at the given + // ShapeIndex is not array. See primitive_util.h for the mapping from XLA type + // to native type. + template + absl::Span data(const ShapeIndex& shape_index = {}) const; + + // Returns a const pointer to (or size of) the underlying buffer holding the + // array at the given shape index. CHECKs if the subshape of the literal at + // the given ShapeIndex is not array. + const void* untyped_data(const ShapeIndex& shape_index = {}) const; + int64_t size_bytes(const ShapeIndex& shape_index = {}) const; + + // Returns this literal's data as a string. This literal must be a rank-1 U8 + // array. + std::string GetR1U8AsString() const; + + // Prints a string representation of the literal value. The Shape of the + // literal is a prefix of the literal value in the string. + // + // Warning: this function can take minutes for multi-million element Literals. + void Print(Printer* printer) const; + + // Similar to Print, but prints the result in a compact one-line form. + void PrintOneline(Printer* printer) const; + + // Prints a string representation of the literal value which does *not* + // include the shape string. + void PrintWithoutShape(Printer* printer) const; + + // Similar to PrintWithoutShape, but prints the result in a compact one-line + // form. + void PrintWithoutShapeOneline(Printer* printer) const; + + // Prints a string representation of the literal value which includes the + // shape string with its layout.does *not* include the shape string. + void PrintWithLayout(Printer* printer) const; + + // Similar to PrintWithLayout, but prints the result in a compact one-line + // form. + void PrintWithLayoutOneline(Printer* printer) const; + + // Returns a string representation of the literal value. The Shape of the + // literal is a prefix of the literal value in the string. + // + // Warning: this function can take minutes for multi-million element Literals. + std::string ToString() const; + + // Similar to ToString, but return the result in a compact one-line form. + std::string ToStringOneline() const; + + // Returns a string representation of the literal value which does *not* + // include the shape string. + std::string ToStringWithoutShape() const; + + // Similar to ToStringWithoutShape, but return the result in a compact + // one-line form. + std::string ToStringWithoutShapeOneline() const; + + // Returns a string representation of the literal value which includes the + // shape string with its layout.does *not* include the shape string. + std::string ToStringWithLayout() const; + + // Similar to ToStringWithLayout, but return the result in a compact one-line + // form. + std::string ToStringWithLayoutOneline() const; + + // Gets an element in the literal at the given index. The multi_index is + // CHECKed against the dimension sizes. + template + NativeT Get(absl::Span multi_index, + const ShapeIndex& shape_index) const; + // Overloads of Get for array literals. CHECKs if the literal is not + // array-shaped and dense. + template + NativeT Get(absl::Span multi_index) const; + + // Get the dynamic size on dim_index in the literal at the given shape_index. + int32_t GetDynamicSize(int64_t dim_index, + const ShapeIndex& shape_index) const; + int32_t GetDynamicSize(int64_t dim_index) const; + + // Returns the element value at index (0, ..., 0), however many zeroes are + // required for that index. + template + NativeT GetFirstElement() const; + + // As above but returns any integer type casted to an int64_t. + std::optional GetFirstInteger() const; + + // As Get(), but determines the correct type and converts the value + // into text. + std::string GetAsString(absl::Span multi_index, + const ShapeIndex& shape_index = {}) const; + + // Return whether the value at the specified index is equal to the provided + // generic `value` (T must be an arithmetic type). + // + // Precondition: must be an array. + template + typename std::enable_if::is_specialized, bool>::type + IsEqualAt(absl::Span multi_index, T value) const { + if (auto as_s64 = GetIntegralAsS64(multi_index)) { + return *as_s64 == value; + } + complex128 as_complex128 = *GetAsComplex128(multi_index); + return as_complex128.imag() == 0 && as_complex128.real() == value; + } + + bool IsEqualAt(absl::Span multi_index, + complex128 value) const { + if (auto as_s64 = GetIntegralAsS64(multi_index)) { + return *as_s64 == value.real() && value.imag() == 0; + } + auto as_complex128 = GetAsComplex128(multi_index); + return *as_complex128 == value; + } + + // As Get(), but determines the correct type and converts the value into + // int64_t. This literal must be an array. + std::optional GetIntegralAsS64( + absl::Span multi_index) const; + + // As Get(), but determines the correct type, and converts the value into + // double. This literal must be an array. + std::optional GetAsDouble( + absl::Span multi_index) const; + + // As Get(), but determines the correct type, and converts the value into + // complex128. All floating point types can be converted into complex128. + // + // This literal must be an array. + std::optional GetAsComplex128( + absl::Span multi_index) const; + + // Convert each element whose *linear* index is listed in "linear_indices" + // to a double and return the sum of all of these elements. + std::optional GetSumAsDouble( + absl::Span linear_indices) const; + + // Invokes the "per cell" callback for each element in the provided + // literal with the element's indices and a string representation of + // the element's value. + // + // This function is useful if you want a polymorphic representation + // of the tensor's elements (turning it to a string for something + // like representation in a protobuf). + // + // This literal must have a dense layout. + void EachCellAsString( + absl::FunctionRef indices, + const std::string& value)> + per_cell) const; + template + void EachCell( + absl::FunctionRef indices, NativeT value)> + per_cell) const; + + // Checks whether all of this literal's values are equal to the given scalar + // literal. + // + // If `this` is not an array (e.g. it's a tuple), returns false. This is + // simpler than trying to handle subshapes here, and it's almost always what + // you want. + // + // Preconditions: + // - `scalar` is a scalar. + // - `scalar` has the same element-type as `this`. + bool IsAll(const Literal& scalar) const; + + // Returns whether every element in this literal is equal to value. + // + // value is an int8_t because we expect this to be called with small + // compile-time constants (0, -1, etc.) and so that whatever value you pass + // can be represented exactly by floating-point types as small as 16 bits. + // + // If value doesn't fit in this literal's type, returns false. Values of 1/0 + // are considered equal to true/false; other values are not considered equal + // to true. + // + // Returns false if this literal is not array-shaped. + bool IsAll(int8_t value) const; + + // Like IsAll(int8_t), except we check whether the literal is equal to a + // particular floating-point or complex number. + // + // Returns false if this literal is not a floating-point / complex value, or + // if it's not an array. + // + // This casts value to the type of literal, then compares using ==, with the + // caveat that NaNs are considered equal. Unlike IsAll, this does not + // necessarily return false if the value does not fit in this literal's type. + bool IsAllFloat(float value) const; + bool IsAllComplex(complex64 value) const; + + // Deetermines if this literal consists entirely of the first element of the + // literal. + // + // Returns false if this literal is not an array. + bool IsAllFirst() const; + + // Returns the number of elements that have value equal to the given value. + // Returns 0 if value does not fit in this literal's type or if the literal + // is not an array. + template + int64_t CountEqual(T value) const; + + // Returns the number of elements that have value equal to the given complex + // value. Returns 0 if value does not fit in this literal's type or if the + // literal is not an array. + template + int64_t CountEqual(std::complex value) const; + + // Literal consists entirely of an iota. + bool IsR1Iota() const; + + // Returns the stride if the literal is a strided iota. + std::optional IsR1StridedIota() const; + + // Returns whether this literal is zero at the specified index. This literal + // must be an array with a dense layout. + bool IsZero(absl::Span indices) const; + + // Returns the count of the elements in the array at the given shape index in + // this literal. + int64_t element_count(const ShapeIndex& index = {}) const { + if (index.empty()) { + // Common case, avoid GetSubshape(). + return ShapeUtil::ElementsIn(shape()); + } + return ShapeUtil::ElementsIn(ShapeUtil::GetSubshape(shape(), index)); + } + + // Compute a hash for this literal. + template + friend H AbslHashValue(H state, const LiteralBase& value) { + return LiteralBase::Hash(std::move(state), value); + } + + template ::max()> + static H Hash(H state, const LiteralBase& literal) { + state = + Shape::Hash(std::move(state), literal.shape()); + + ShapeUtil::ForEachSubshape( + literal.shape(), [&](const Shape& subshape, const ShapeIndex& index) { + if (!subshape.IsArray()) { + return; + } + + CHECK(LayoutUtil::IsDenseArray(subshape)); + auto data = absl::MakeConstSpan( + static_cast(literal.untyped_data(index)), + std::min(kByteLimit, literal.size_bytes(index))); + state = H::combine(std::move(state), data); + }); + + return std::move(state); + } + + // Converts this literal to the given shape. Returns an error is the + // conversion is not possible. + StatusOr ConvertToShape(const Shape& dest_shape) const; + + // Converts this literal to another primitive type using a bitcast + // conversion. Returns an error if the conversion is not possible. This + // literal must be array-shaped. + StatusOr BitcastConvert(const Shape& dest_shape) const; + + // Converts this literal to another primitive type. Returns an error if the + // conversion is not possible. This literal must be array-shaped. + StatusOr Convert(PrimitiveType primitive_dest_type) const; + + // Clones the underlying buffers into a new Literal. + Literal Clone() const; + std::unique_ptr CloneToUnique() const; + + // TODO(b/67651157): The methods below which perform computation on Literals + // (Reshape, Slice, etc) should be moved elsewhere, and perhaps combined with + // evaluator code which operates on Literals. + // + // Creates a new value that has the equivalent value as this + // literal, but conforms to new_layout; e.g. a literal matrix that was in {0, + // 1} minor-to-major dimension layout can be re-layed-out as {1, 0} + // minor-to-major dimension layout and the value in the cell at any given + // logical index (i0, i1) will be the same. + // + // For tuple shaped literals, shape_index should be used to select the inner + // array that the new layout applies to. + // + // Note: this is useful when the client wants to ensure that a value placed in + // the XLA allocation tracker has a particular layout; for efficiency + // purposes or avoiding unimplemented operation/layout combinations. + Literal Relayout(const Layout& new_layout, + const ShapeIndex& shape_index = {}) const; + + // An overload of Relayout which changes the layout of the entire shape rather + // than being limited to a single array within the shape. + Literal Relayout(const Shape& shape_with_layout) const; + + // Generate a new literal whose static sizes are equal to the previous + // literal's dynamic sizes. + Literal ToStatic() const; + + // Expand a static literal into a new one with a bounded dynamic literal. The + // static dimensions of the original literal becomes dynamic dimensions of the + // new literal, where the argument `bounded_shape` becomes the bounded shape + // of the new literal. + // + // Precondition: bounded_shape.is_dynamic() + Literal ToBoundedDynamic(const Shape& bounded_shape) const; + + // Creates a new literal by reshaping this literal to have the given + // dimensions. The total number of elements must not change; The + // implementation currently only supports monotonic dim0-major layouts. + // This literal must be an array. + StatusOr Reshape(absl::Span dimensions) const; + + // Creates a new literal by broadcasting this literal with `dimensions` to + // yield a literal of shape `result_shape`. + StatusOr Broadcast(const Shape& result_shape, + absl::Span dimensions) const; + + // Creates a new literal by reordering the dimensions of this literal. + // The given `permutation` must be a permutation of the dimension numbers + // in the original literal, and it specifies the order of the new dimensions + // in the result literal (i.e., new_order[i] = old_order[permutation[i]]). + // For example, a transpose call on a literal of shape [3 x 8 x 4] and + // `permutation` = {2, 0, 1} returns a new literal of shape [4 x 3 x 8]. + // This literal must be an array. + Literal Transpose(absl::Span permutation) const; + + // Creates a sub-array from this literal by extracting the indices + // [start_index, limit_index) of each dimension. The result literal has the + // same rank and layout as for the given literal. The number of indices in + // start_indices and limit_indices must be the rank of the literal, and the + // indices follow the order of the dimensions. + // This literal must be an array. + Literal Slice(absl::Span start_indices, + absl::Span limit_indices) const; + + // Creates a literal with a prepended dimension with bound "times"; e.g. a + // f32[3x2] with times=4 will produce a f32[4x3x2] with the 3x2 from this + // literal replicated four times. + // This literal must be an array. + template + Literal Replicate(int64_t times) const; + + // Returns true if the leaf arrays of the literal within the given shape index + // are all determined. + // See comments on ArrayValueState for detailed explanation. + bool IsDetermined(const ShapeIndex& shape_index = {}) const; + + // Returns true if the leaf arrays of the literal within the given shape index + // are all known. + // See comments on ArrayValueState for detailed explanation. + bool IsKnown(const ShapeIndex& shape_index = {}) const; + + // Creates a new Literal object with the shape specified as parameter. + // The content of the literal values is the default value of the primitive + // type of literal itself (0 for numeric types, and false for predicates). + // + // Note: It's an antipattern to use this method then immediately call + // MutableLiteralBase::Populate on the result (since that results in zero + // initialization, then reinitialization. Consider if a call to + // std::make_unique(shape), followed by the call to + // MutableLiteralBase::Populate can be used instead. + static Literal CreateFromShape(const Shape& shape); + + // WARNING: These two functions are only supposed to be used by HloEvaluator. + // The rest of XLA assumes all literals are known. + // Similar to CreateFromShape() but marks all leaf arrays as unknown. + static Literal CreateFromShapeWithUnknownLeafArrays(const Shape& shape); + // Similar to CreateFromShape() but marks all leaf arrays as undetermined. + static Literal CreateFromShapeWithUndeterminedLeafArrays(const Shape& shape); + + protected: + // Array literals could be in one of the following three states: + // 1) Known: we have evaluated and known the value of the array literal. + // 2) Unknown: we have tried to evaluate the array literal, but its value + // cannot be evaluated statically. + // 3) Undetermined: we haven't tried to evaluate the array literal. + // Unknown and Undetermined states are only meant to be used within + // HloEvaluator. The rest of XLA assumes array literals are all known. + // Literals that are unknown or undetermined can be copied from, using + // CopyFrom and Clone, or moved from using move constructor. Accessing values + // of such literals causes undefined behavior. + enum class ArrayValueState { kKnown = 0, kUnknown = 1, kUndetermined = 2 }; + + // A data structure representing a subshape at a particular ShapeIndex within + // the literal. For array-shaped ShapeIndexes, this data structure holds the + // pointer to the memory allocated for the array data. + class Piece { + public: + ArrayValueState get_array_value_state() const; + void set_array_value_state(ArrayValueState state); + // Returns the buffer holding the array data for this piece as an array + // slice. This piece must be array-shaped. + template + absl::Span data() const; + template + absl::Span data(); + + // Returns the buffer holding the array data for this piece as a void*. This + // piece must be array-shaped. + void* untyped_data(); + const void* untyped_data() const; + + // Gets or sets an element in the array at the given index. The multi_index + // is CHECKed against the dimension sizes of the array. This piece must be + // array-shaped. + template + NativeT Get(absl::Span index) const; + template + void Set(absl::Span index, NativeT value); + + int32_t GetDynamicSize(int64_t dim_index) const; + void SetDynamicSize(int64_t dim_index, int32_t size); + void AllocateBuffers(); + void DeallocateBuffers(); + // Gets/sets the buffer holding the array data. + const char* buffer() const; + char* buffer() { + return const_cast(const_cast(this)->buffer()); + } + void set_buffer(char* buffer) { + DCHECK(LayoutUtil::IsDenseArray(*subshape_)); + auto* dense_rep = std::holds_alternative(rep_) + ? &rep_.emplace() + : GetDenseRep(); + DCHECK(dense_rep); + dense_rep->data = buffer; + } + void MoveDataFrom(Piece& from) { + DCHECK(!std::holds_alternative(rep_)); + DCHECK(!std::holds_alternative(rep_)); + if (auto* dense_rep = from.GetDenseRep()) { + rep_.emplace().data = dense_rep->data; + } else if (auto* inlined_rep = from.GetDenseInlinedRep()) { + std::memcpy(rep_.emplace().data, inlined_rep->data, + from.total_bytes_dense()); + } + from.rep_.emplace(); + } + + using DynamicSizeType = int32_t; + + // Gets/sets the buffer holding dynamic sizes. + const DynamicSizeType* dynamic_size_buffer() const { + DCHECK(LayoutUtil::IsDenseArray(*subshape_)); + return reinterpret_cast( + buffer() + dynamic_size_buffer_offset()); + } + DynamicSizeType* dynamic_size_buffer() { + return const_cast( + const_cast(this)->dynamic_size_buffer()); + } + + int64_t dynamic_size_buffer_bytes() const { + DCHECK(LayoutUtil::IsDenseArray(*subshape_)); + return subshape().dimensions_size() * sizeof(DynamicSizeType); + } + + // Gets or sets the subshape of this piece. This reference points to a + // subshape within the shape in the containing Literal (Literal::shape_). + const Shape& subshape() const { return *subshape_; } + void set_subshape(const Shape* subshape) { + subshape_ = subshape; + if (std::holds_alternative(rep_)) { + if (subshape_->IsTuple()) { + rep_.emplace(); + } + } + } + + // Returns the size in bytes of the buffer holding the dense array data. + int64_t size_bytes_dense() const { + DCHECK(LayoutUtil::IsDenseArray(*subshape_)); + return ShapeUtil::ByteSizeOf(subshape()); + } + + // The dynamic metadata starts at the end of the data in the literal. + // The literal can have any number of bytes. For example, it could be a PRED + // with 7 elements. `dynamic_size_buffer_offset` returns the number of bytes + // before the dynamic size information including whatever padding is needed + // to align the start of the dynamic size information so that it is aligned + // to a multiple of `sizeof(DynamicSizeType)`. + int64_t dynamic_size_buffer_offset() const { + // Make sure the dynamic buffer starts on a boundary aligned to + // `sizeof(DynamicSizeType)`. + return RoundUpTo(size_bytes_dense(), sizeof(DynamicSizeType)); + } + + // Total size in bytes, including the dynamic size addition. + // + // The shape can become dynamic after this literal is allocated, so we + // over-allocate the margin for the dynamic shape description in case we + // need it. + int64_t total_bytes_dense() const { + return dynamic_size_buffer_offset() + dynamic_size_buffer_bytes(); + } + + // Returns the number of elements in this piece's array. + int64_t element_count() const { return ShapeUtil::ElementsIn(subshape()); } + + // Returns the child piece at 'index' of this piece. + Piece& child(int64_t index) { + return const_cast(const_cast(this)->child(index)); + } + const Piece& child(int64_t index) const { + auto* tuple_rep = GetTupleRep(); + DCHECK(tuple_rep); + return tuple_rep->children[index]; + } + + // Adds a child piece to this piece's children. + void emplace_back(Piece child_piece) { + auto* tuple_rep = GetTupleRep(); + DCHECK(tuple_rep); + tuple_rep->children.emplace_back(std::move(child_piece)); + } + + // Returns the size of children pieces of this piece. + int64_t children_size() const { + if (auto* tuple_rep = GetTupleRep()) { + return tuple_rep->children.size(); + } + return 0; + } + + // Visitor functions that recursively traverses the piece and calls the + // given function at each child piece. The function has the type: + // void (const ShapeIndex& index, const Piece& piece) + template + void ForEachSubpiece(const Fn& func) const { + ShapeIndex index; + return ForEachHelper( + [&func](const ShapeIndex& index, const Piece& piece) { + func(index, piece); + return OkStatus(); + }, + *this, &index) + .IgnoreError(); + } + // Same as above, but the function has the type: + // Status (const ShapeIndex& index, const Piece& piece) + // The first non-OK return value is returned by the function. + template + Status ForEachSubpieceWithStatus(const Fn& func) const { + ShapeIndex index; + return ForEachHelper(func, *this, &index); + } + // Same as above, but the function has the type: + // Bool (const ShapeIndex& index, const Piece& piece) + // The first non-true return value is returned by the function. + template + bool ForEachSubpieceWithBool(const Fn& func) const { + ShapeIndex index; + return ForEachHelperBool(func, *this, &index); + } + // Same as above, but the function has the type: + // Void (const ShapeIndex& index, Piece& piece) + template + void ForEachMutableSubpiece(const Fn& func) { + ShapeIndex index; + return ForEachMutableHelper( + [&func](const ShapeIndex& index, Piece* piece) { + func(index, piece); + return OkStatus(); + }, + const_cast(this), &index) + .IgnoreError(); + } + // Same as above, but the function has the type: + // Status (const ShapeIndex& index, Piece& piece) + // The first non-OK return value is returned by the function. + template + Status ForEachMutableSubpieceWithStatus(const Fn& func) { + ShapeIndex index; + return ForEachMutableHelper( + func, const_cast(this), &index); + } + + // Checks whether all elements of this Piece are equal to the given literal. + // + // Returns false if this Piece is not an array. + // + // Preconditions: + // - `scalar` is a scalar. + // - `scalar`'s type matches that of `this`. + bool IsAll(const Literal& scalar) const; + + // Returns the number of elements with equal value to the given literal. + // Returns 0 if this Piece is not an array. + int64_t CountAll(const Literal& scalar) const; + + // Returns true if this piece and 'other' contain the same data. This piece + // and 'other' must be array-shaped and compatible. If a literal has dynamic + // shape, comparison is done only for the valid elements. + bool EqualElements(const Piece& other) const; + + // Returns true if this piece and other pieces have the same dynamic + // dimension sizes. + bool EqualDynamicSize(const Piece& other) const; + + // Writes the shape and data (if array-shaped) into the given proto. + void WriteToProto(LiteralProto* proto) const; + + // Copy the data from 'src' into this piece's buffer. Shapes of this piece + // and src must be compatible. If only_dynamic_bound is true, only elements + // within dynamic bounds will be copied. + Status CopyFrom(const Piece& src, bool only_dynamic_bound); + + // Copies the data from the given proto into this piece. The shape of this + // piece must be equal (not just compatible) to the shape of the proto. + Status CopyFromProto(const LiteralProto& proto); + + // See comments on ArrayValueState for detailed explanation. + bool IsDetermined() const; + + bool IsKnown() const; + + private: + // Uninitialized state representation. + struct Uninitialized {}; + // Out of line dense array storage. + union DenseRep { + char* data; + }; + struct TupleRep { + // Children pieces for tuple shaped pieces. + std::vector children = {}; + }; + + // Use just so many bytes that we don't increase the sizeof(Piece). + static inline constexpr size_t kMaxInlinedBytes = + std::max(sizeof(DenseRep), sizeof(TupleRep)); + + // Inlined dense array storage. + struct DenseInlinedRep { + char data[kMaxInlinedBytes]; + }; + + const DenseInlinedRep* GetDenseInlinedRep() const { + return std::get_if(&rep_); + } + DenseInlinedRep* GetDenseInlinedRep() { + return std::get_if(&rep_); + } + + const DenseRep* GetDenseRep() const { return std::get_if(&rep_); } + DenseRep* GetDenseRep() { return std::get_if(&rep_); } + + const TupleRep* GetTupleRep() const { return std::get_if(&rep_); } + TupleRep* GetTupleRep() { return std::get_if(&rep_); } + // Helpers for traversing the piece via ForEachSubpiece rooted at 'index'. + // The first non-OK (or non-true) value is returned by the function. + // The callable 'func' has the same signature as described above in + // ForEachSubpiece*. + template + Status ForEachHelper(const Fn& func, const Piece& piece, + ShapeIndex* index) const { + TF_RETURN_IF_ERROR(func(*index, piece)); + if (auto* tuple_rep = piece.GetTupleRep()) { + for (int64_t i = 0; i < tuple_rep->children.size(); ++i) { + index->push_back(i); + TF_RETURN_IF_ERROR( + ForEachHelper(func, tuple_rep->children[i], index)); + index->pop_back(); + } + } + return OkStatus(); + } + template + bool ForEachHelperBool(const Fn& func, const Piece& piece, + ShapeIndex* index) const { + if (!func(*index, piece)) { + return false; + } + if (auto* tuple_rep = piece.GetTupleRep()) { + for (int64_t i = 0; i < tuple_rep->children.size(); ++i) { + index->push_back(i); + if (!ForEachHelperBool(func, tuple_rep->children[i], index)) { + return false; + } + index->pop_back(); + } + } + return true; + } + template + Status ForEachMutableHelper(const Fn& func, Piece* piece, + ShapeIndex* index) { + TF_RETURN_IF_ERROR(func(*index, piece)); + if (auto* tuple_rep = piece->GetTupleRep()) { + for (int64_t i = 0; i < tuple_rep->children.size(); ++i) { + index->push_back(i); + TF_RETURN_IF_ERROR( + ForEachMutableHelper(func, &tuple_rep->children[i], index)); + index->pop_back(); + } + } + return OkStatus(); + } + + // Recursive helper for EqualElements. + template + bool EqualElementsInternal(const Piece& other, + std::vector* multi_index) const; + + // Internal helper to copy elements from another given piece + template + void CopyElementsWithDynamicBound(const LiteralBase::Piece& src); + + // Storage representation of this piece. + std::variant rep_; + + // The shape of piece. This points into the shape of the containing Literal + // (Literal::shape_). + const Shape* subshape_ = nullptr; + + ArrayValueState array_value_state_ = ArrayValueState::kKnown; + }; // class Piece + + const Piece& piece(const ShapeIndex& shape_index) const; + + // Returns the piece at the root of the shape. + virtual const Piece& root_piece() const = 0; + + // LiteralSlice and Literal must access Pieces of other Literals. + friend class MutableLiteralBase; + friend class LiteralSlice; + friend class BorrowingLiteral; + + private: + // Like IsAllFloat, but if round_value is false and the value is not + // representable with the literal's type (e.g., due to rounding error or + // overflow/underflow when casting the value to the literal's type), returns + // false. + bool IsAllFloatImpl(float value, bool round_value) const; +}; + +// Abstract base class representing a mutable literal in XLA. +class MutableLiteralBase : public LiteralBase { + public: + ~MutableLiteralBase() override = 0; + + // Returns a Span view of the array for this literal for the + // given NativeT (e.g., float). CHECKs if the subshape of the literal at the + // given ShapeIndex is not array. See primitive_util.h for the mapping from + // XLA type to native type. + template + absl::Span data(const ShapeIndex& shape_index = {}); + // Unhide const method from parent class. + using LiteralBase::data; + + // TODO(b/67651157): Remove this accessor. Literal users should not be able to + // mutate the shape as this can produce malformed Literals. + Shape* mutable_shape_do_not_use(); + + // Set the dynamic size on dim_index in the literal at the given shape_index. + void SetDynamicSize(int64_t dim_index, const ShapeIndex& shape_index, + int32_t size); + void SetDynamicSize(int64_t dim_index, int32_t size); + + // Returns a pointer to the underlying buffer holding the array at the given + // shape index. CHECKs if the subshape of the literal at the given ShapeIndex + // is not array. + void* untyped_data(const ShapeIndex& shape_index = {}); + // Unhide const method from parent class. + using LiteralBase::untyped_data; + + template + void MutableEachCell(absl::FunctionRef indices, NativeT value)> + per_cell); + + // Copy values from 'src_literal' rooted at 'src_shape_index' into this + // literal rooted at 'dest_shape_index'. The subshape of this literal rooted + // at 'dest_shape_index' must be compatible with the subshape of 'src_literal' + // rooted at 'src_shape_index', but need not be arrays. If only_dynamic_bound + // is true, only elements within dynamic bounds will be copied. + Status CopyFrom(const LiteralSlice& src_literal, + const ShapeIndex& dest_shape_index = {}, + const ShapeIndex& src_shape_index = {}, + bool only_dynamic_bound = false); + + // Copies the values from src_literal, starting at src_base shape indexes, + // to this literal, starting at dest_base, where the copy size in each + // dimension is specified by copy_size. + // The src_literal and this literal must have the same primitive type, + // src_base+copy_size must fit the source literal dimensions, as well as + // dest_base+copy_size must fit the destination literal dimensions. + // Note: if either src_literal or this literal contains dimensions with zero + // element, then copy_size must be 0 in these dimensions while the + // corresponding base indices being 0. + // This literal and 'src_literal' must be arrays. + Status CopySliceFrom(const LiteralSlice& src_literal, + absl::Span src_base, + absl::Span dest_base, + absl::Span copy_size); + + // Copies one element from src_literal[src_index] to (*this)[dest_index]. + void CopyElementFrom(const LiteralSlice& src_literal, + absl::Span src_index, + absl::Span dest_index); + + // Sets an element in the literal at the given index. The multi_index is + // CHECKed against the dimension sizes. + template + void Set(absl::Span multi_index, const ShapeIndex& shape_index, + NativeT value); + // Overloads of Set for array literals. CHECKs if the literal is not + // array-shaped and dense. + template + void Set(absl::Span multi_index, NativeT value); + + // As Set(), but truncates `value` to the literal element type before storing. + // This literal must be an array. + Status SetIntegralAsS64(absl::Span multi_index, int64_t value); + + // As Set(), but truncates `value` to the literal element type before storing. + // This literal must be an array. + Status SetFromDouble(absl::Span multi_index, double value); + + // Populate this literal with the given values. Examples: + // + // // Populate with floats. + // Array2D float_values = ... + // literal.PopulateR2FromArray2D(values); + // + // // Populate with int32s. + // literal.PopulateR2({{1, 2}, {3, 4}}); + // + // The shape and element type of this literal must match given values. For + // example, in the call above to literal.PopulateR2(), 'literal' must be a 2x2 + // array of S32. + template + void PopulateR1(absl::Span values); + void PopulateR1(const tsl::core::Bitmap& values); + template + void PopulateR2(std::initializer_list> values); + template + void PopulateFromArray(const Array& values); + template + void PopulateR2FromArray2D(const Array2D& values); + template + void PopulateR3FromArray3D(const Array3D& values); + template + void PopulateR4FromArray4D(const Array4D& values); + + // Populates literal values by calling the generator function for every cell + // in this literal object. + // + // generator must be a callable of the type + // NativeT(absl::Span indexes) or compatible. + // + // This literal must have a dense layout. + template + Status Populate( + absl::FunctionRef)> generator); + + // A parallel version of Populate(). This can be used if the generator is + // thread-safe and the values for the shape's different elements are + // independent. + template + Status PopulateParallel( + absl::FunctionRef, int)> generator); + + // Similar to Populate() but takes a populator function that allows caller + // specify how to write to the destination buffer rather than a generator that + // returns the values. This is useful when the value population simply does + // memcpy without compute therefore can be written in a type agnostic way, so + // that we can avoid templatizing the method for better code size. + // + // This literal must have a dense layout. + Status PopulateInplace( + absl::FunctionRef)> populator); + + // A parallel version of PopulateInplace(). This can be used if the generator + // is thread-safe and the values for the shape's different elements are + // independent. + Status PopulateInplaceParallel( + absl::FunctionRef, int)> populator); + + // Fills this literal with the given value. + template + void PopulateWithValue(NativeT value); + + // This operation is the inverse of DecomposeTuple. The given elements are + // moved into the tuple elements of a new tuple-shaped Literal which is + // returned. Upon return, each of the Literals in 'elements' is set to a nil + // shape (empty tuple). + static Literal MoveIntoTuple(absl::Span elements); + + // Serialize from a proto. + static StatusOr CreateFromProto(const LiteralProto& proto, + bool prohibit_empty_literal = true); + + protected: + // Returns the piece at the given ShapeIndex. + Piece& piece(const ShapeIndex& shape_index) { + return const_cast(LiteralBase::piece(shape_index)); + } + + Piece& mutable_root_piece() { return const_cast(root_piece()); } + + // Internal template helper for the Literal::CopySliceFrom(), matching its + // arguments one by one. + template + Status CopySliceFromInternal(const LiteralBase& src_literal, + absl::Span src_base, + absl::Span dest_base, + absl::Span copy_size); + + // A unique_ptr like class which may or may not have ownership of its pointer. + // The literal may or may not own the storage of the shape. Creating/copying a + // shape can incur significant overhead which in many case we'd like to avoid, + // esp. for small literals. + class MaybeOwningShapePtr { + public: + MaybeOwningShapePtr() = default; + explicit MaybeOwningShapePtr(std::unique_ptr unique) + : ptr_and_owning_bit_(TakeUnique(std::move(unique))) {} + + explicit MaybeOwningShapePtr(const Shape* borrowed) + : ptr_and_owning_bit_(Borrow(borrowed)) {} + + ~MaybeOwningShapePtr() { MaybeDeleteOwned(); } + + const Shape* get() const { + return reinterpret_cast(ptr_and_owning_bit_ & kPointerMask); + } + Shape* get_mutable(bool ensure_owned = false) { + const Shape* const_ptr = get(); + // TODO(b/67651157): Remove this copy on write logic and combine get() and + // get_mutable() once we remove mutable_shape_do_not_use(). + if (const_ptr && !OwnsPtr()) { + ptr_and_owning_bit_ = TakeUnique(std::make_unique(*const_ptr)); + const_ptr = get(); + } + DCHECK(OwnsPtr()); + return const_cast(const_ptr); + } + const Shape* operator->() const { return get(); } + const Shape& operator*() const { return *get(); } + + MaybeOwningShapePtr& operator=(std::unique_ptr unique) { + MaybeDeleteOwned(); + ptr_and_owning_bit_ = TakeUnique(std::move(std::move(unique))); + return *this; + } + + MaybeOwningShapePtr& operator=(const Shape* borrowed) { + MaybeDeleteOwned(); + ptr_and_owning_bit_ = Borrow(borrowed); + return *this; + } + + MaybeOwningShapePtr& operator=(MaybeOwningShapePtr&& other) { + using std::swap; + swap(ptr_and_owning_bit_, other.ptr_and_owning_bit_); + return *this; + } + + MaybeOwningShapePtr(const MaybeOwningShapePtr&) = delete; + MaybeOwningShapePtr(MaybeOwningShapePtr&& other) + : ptr_and_owning_bit_(other.ptr_and_owning_bit_) { + other.ptr_and_owning_bit_ = 0; + } + + MaybeOwningShapePtr Clone() const { + const Shape* ptr = get(); + if (ptr && OwnsPtr()) { + return MaybeOwningShapePtr(std::make_unique(*ptr)); + } + return MaybeOwningShapePtr(ptr); + } + + private: + enum : uint64_t { + kOwningBitMask = 1UL, + kPointerMask = ~kOwningBitMask, + }; + static intptr_t TakeUnique(std::unique_ptr unique) { + Shape* released = unique.release(); + DCHECK_EQ(reinterpret_cast(released) & kOwningBitMask, 0); + return reinterpret_cast(released) | kOwningBitMask; + } + + static intptr_t Borrow(const Shape* borrowed) { + DCHECK_EQ(reinterpret_cast(borrowed) & kOwningBitMask, 0); + return reinterpret_cast(borrowed); + } + + bool OwnsPtr() const { return kOwningBitMask & ptr_and_owning_bit_; } + + void MaybeDeleteOwned() { + if (OwnsPtr()) { + delete get(); + } + } + + intptr_t ptr_and_owning_bit_ = 0; + }; + + // The parent class borrows this shape. + MaybeOwningShapePtr shape_; + + // Implementation details shared between Populate() and PopulateParallel() + // template + // Status PopulateInternal(const FnType& generator, bool parallel); + template + Status PopulateInternal( + absl::FunctionRef, int)> generator, + bool parallel); + void PopulateInplaceInternal( + absl::FunctionRef, int)> populator, + bool parallel); + + friend class LiteralBase; + friend class MutableBorrowingLiteral; +}; +std::ostream& operator<<(std::ostream& out, const Literal& literal); + +// The underlying buffer and shape is always owned by this class. +class Literal : public MutableLiteralBase { + public: + Literal(); + + // Create a literal of the given shape. The literal is allocated sufficient + // memory to hold the shape. Memory is uninitialized. + explicit Literal(const Shape& shape); + ~Literal() override; + + // Literals are moveable, but not copyable. To copy a literal use + // Literal::Clone or Literal::CloneToUnique. This prevents inadvertent copies + // of literals which can be expensive. + Literal(const Literal& other) = delete; + Literal& operator=(const Literal& other) = delete; + Literal(Literal&& other); + // 'allocate_arrays' indicates whether to allocate memory for the arrays in + // the shape. If false, buffer pointers inside of the Literal::Pieces are set + // to nullptr. + Literal(const Shape& shape, bool allocate_arrays, + ArrayValueState leaf_array_value_state = ArrayValueState::kKnown); + Literal& operator=(Literal&& other); + + // Similar to CopyFrom, but with move semantics. The subshape of this literal + // rooted at 'dest_shape_index' must be *equal* to the shape 'src_literal' + // (layouts and shapes must match), but need not be arrays. The memory + // allocated in this literal for the subshape at dest_shape_index is + // deallocated, and the respective buffers are replaced with those in + // src_literal. Upon return, src_literal is set to a nil shape (empty tuple). + virtual Status MoveFrom(Literal&& src_literal, + const ShapeIndex& dest_shape_index); + Status MoveFrom(Literal&& src_literal) { + return MoveFrom(std::move(src_literal), /*dest_shape_index=*/{}); + } + + // Returns a vector containing the tuple elements of this Literal as separate + // Literals. This Literal must be tuple-shaped and can be a nested tuple. The + // elements are moved into the new Literals; no data is copied. Upon return + // this Literal is set to a nil shape (empty tuple) + // + // TODO(jlebar): Because this function invalidates `this`, it should be + // ref-qualified with &&. + std::vector DecomposeTuple(); + + // Returns a subliteral specified by given shape_index. No data is copied, the + // current literal becomes invalid after this function call. + // + // TODO(jlebar): Because this function invalidates `this`, it should be + // ref-qualified with &&. + Literal SubLiteral(ShapeIndexView shape_index); + + private: + friend class LiteralBase; + friend class MutableLiteralBase; + const Piece& root_piece() const override { return root_piece_; }; + // Deallocate the buffers held by this literal. + void DeallocateBuffers(); + + // Recursively sets the subshapes and buffers of all subpieces rooted at + // 'piece'. If 'allocate_array' is true, memory is allocated for the arrays in + // the shape. + void SetPiece( + const Shape& shape, Piece* piece, bool allocate_arrays, + ArrayValueState leaf_array_value_state = ArrayValueState::kKnown); + Piece root_piece_; +}; + +// The underlying buffer is not owned by this class and is always owned by +// others. The shape is not owned by this class and not mutable. +class MutableBorrowingLiteral : public MutableLiteralBase { + public: + ~MutableBorrowingLiteral() override; + + MutableBorrowingLiteral() : MutableLiteralBase() {} + + MutableBorrowingLiteral(const MutableBorrowingLiteral& literal); + MutableBorrowingLiteral& operator=(const MutableBorrowingLiteral& literal); + + // Implicit conversion constructors. + // NOLINTNEXTLINE(google-explicit-constructor) + MutableBorrowingLiteral(MutableLiteralBase* literal); + MutableBorrowingLiteral(MutableBorrowingLiteral literal, + const ShapeIndex& view_root); + MutableBorrowingLiteral(const char* src_buf_ptr, const Shape& shape); + + // Create a literal from a list of buffers and a shape. + // Returns a tuple literal if `shape` is a tuple type. + MutableBorrowingLiteral(absl::Span src_buf_ptrs, const Shape& shape); + + private: + const Piece& root_piece() const override { return *root_piece_; }; + // Recursively copies the subtree from the `src_piece` at the given child + // index to the `dest_piece`. For buffers only the pointers are copied, but + // not the content. + void CopyPieceSubtree(const Shape& shape, const Piece* src_piece, + Piece* dest_piece); + Piece* root_piece_ = nullptr; +}; + +// A read-only view of a Literal. A LiteralSlice contains pointers to shape and +// literal buffers always owned by others. +class LiteralSlice : public LiteralBase { + public: + LiteralSlice() : LiteralBase() {} + + // Implicit conversion constructors. + // NOLINTNEXTLINE(google-explicit-constructor) + LiteralSlice(const LiteralBase& literal); + LiteralSlice(const LiteralBase& literal, const ShapeIndex& view_root); + + private: + const Piece& root_piece() const override { return *root_piece_; }; + + const Piece* root_piece_; // Not owned. +}; + +// A read-only Literal where the underlying buffers are never owned by this +// class. +class BorrowingLiteral : public LiteralBase { + public: + BorrowingLiteral() : LiteralBase() {} + + // 'src_buf_ptr' is not owned by this class and must outlive the + // lifetime of this class. It points to an appropriately sized buffer with + // data interpretered as indicated by 'shape'. + // This constructor is only used for array shapes. + BorrowingLiteral(const char* src_buf_ptr, const Shape& shape); + // Similar as above, except to be used for constructing non-nested tuples. + BorrowingLiteral(absl::Span src_buf_ptrs, + const Shape& shape); + // TODO(b/79707221): adding constructors for nested tuples as well. + + private: + // Recursively builds the subtree for the given piece and sets the subshapes + // of the given piece with the given shape. + void BuildPieceSubtree(const Shape& shape, Piece* piece); + + // Accessor for the root piece of this literal. + const Piece& root_piece() const override { return root_piece_; }; + Piece root_piece_; + + // Shape of this literal. Stored as unique_ptr such that the (default) move + // construction of this class would be trivially correct: the pointer to Shape + // root_piece_ stores will still point to the correct address. + std::unique_ptr shape_; +}; + +template +absl::Span LiteralBase::Piece::data() const { + DCHECK(LayoutUtil::IsDenseArray(subshape())) + << __func__ << " is only supported for dense arrays: " << subshape(); + DCHECK(!subshape().has_layout() || + subshape().layout().element_size_in_bits() == 0) + << __func__ + << " is not supported for layouts with custom bit size: " << subshape(); + DCHECK_EQ(subshape().element_type(), + primitive_util::NativeToPrimitiveType()) + << "Attempting to access " + << PrimitiveType_Name(primitive_util::NativeToPrimitiveType()) + << " type, but literal element type is " + << PrimitiveType_Name(subshape().element_type()); + return absl::Span(reinterpret_cast(buffer()), + element_count()); +} + +template +absl::Span LiteralBase::Piece::data() { + DCHECK(LayoutUtil::IsDenseArray(subshape())) + << __func__ << " is only supported for dense arrays: " << subshape(); + DCHECK(!subshape().has_layout() || + subshape().layout().element_size_in_bits() == 0) + << __func__ + << " is not supported for layouts with custom bit size: " << subshape(); + DCHECK_EQ(subshape().element_type(), + primitive_util::NativeToPrimitiveType()) + << "Attempting to access " + << PrimitiveType_Name(primitive_util::NativeToPrimitiveType()) + << " type, but literal element type is " + << PrimitiveType_Name(subshape().element_type()); + return absl::Span(reinterpret_cast(buffer()), + element_count()); +} + +template +NativeT LiteralBase::Piece::Get(absl::Span multi_index) const { + DCHECK(LayoutUtil::IsDenseArray(subshape())) + << __func__ << " is only supported for dense arrays: " << subshape(); + return data()[IndexUtil::MultidimensionalIndexToLinearIndex( + subshape(), multi_index)]; +} + +template +void LiteralBase::Piece::Set(absl::Span multi_index, + NativeT value) { + DCHECK(LayoutUtil::IsDenseArray(subshape())) + << __func__ << " is only supported for dense arrays: " << subshape(); + data()[IndexUtil::MultidimensionalIndexToLinearIndex( + subshape(), multi_index)] = value; +} + +template +absl::Span LiteralBase::data( + const ShapeIndex& shape_index) const { + return piece(shape_index).data(); +} + +template +absl::Span MutableLiteralBase::data(const ShapeIndex& shape_index) { + return piece(shape_index).data(); +} + +template +inline NativeT LiteralBase::Get(absl::Span multi_index, + const ShapeIndex& shape_index) const { + return piece(shape_index).Get(multi_index); +} + +template +inline NativeT LiteralBase::Get(absl::Span multi_index) const { + return root_piece().Get(multi_index); +} + +template +inline void MutableLiteralBase::Set(absl::Span multi_index, + const ShapeIndex& shape_index, + NativeT value) { + return piece(shape_index).Set(multi_index, value); +} + +template +inline void MutableLiteralBase::Set(absl::Span multi_index, + NativeT value) { + return mutable_root_piece().Set(multi_index, value); +} + +template +NativeT LiteralBase::GetFirstElement() const { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + return data().at(0); +} + +template +int64_t LiteralBase::CountEqual(T value) const { + if (!shape().IsArray()) { + return 0; + } + PrimitiveType ty = shape().element_type(); + Literal scalar(ShapeUtil::MakeScalarShape(ty)); + return primitive_util::PrimitiveTypeSwitch( + [&](auto primitive_type_constant) -> int64_t { + if constexpr (primitive_util::IsArrayType(primitive_type_constant)) { + using NativeT = primitive_util::NativeTypeOf; + scalar.Set({}, static_cast(value)); + return root_piece().CountAll(scalar); + } + return 0; + }, + ty); +} + +template +int64_t LiteralBase::CountEqual(std::complex value) const { + if (!shape().IsArray()) { + return 0; + } + PrimitiveType ty = shape().element_type(); + Literal scalar(ShapeUtil::MakeScalarShape(ty)); + return primitive_util::PrimitiveTypeSwitch( + [&](auto primitive_type_constant) -> int64_t { + if constexpr (primitive_util::IsComplexType(primitive_type_constant)) { + using NativeT = primitive_util::NativeTypeOf; + scalar.Set({}, static_cast(value)); + return root_piece().CountAll(scalar); + } + return 0; + }, + ty); +} + +template +TF_ATTRIBUTE_NOINLINE void LiteralBase::EachCell( + absl::FunctionRef indices, NativeT value)> + per_cell) const { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + if (ShapeUtil::IsZeroElementArray(shape())) { + return; + } + std::vector indices(shape().rank(), 0); + + Shape shape_dynamic = shape(); + for (int64_t i = 0; i < shape_dynamic.rank(); ++i) { + shape_dynamic.set_dimensions(i, GetDynamicSize(i)); + } + do { + per_cell(indices, Get(indices)); + } while (IndexUtil::BumpIndices(shape_dynamic, absl::MakeSpan(indices))); +} + +template +TF_ATTRIBUTE_NOINLINE void MutableLiteralBase::MutableEachCell( + absl::FunctionRef indices, NativeT value)> + per_cell) { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + if (ShapeUtil::IsZeroElementArray(shape())) { + return; + } + std::vector indices(shape().rank(), 0); + Shape shape_dynamic = shape(); + for (int64_t i = 0; i < shape_dynamic.rank(); ++i) { + shape_dynamic.set_dimensions(i, GetDynamicSize(i)); + } + do { + Set(indices, per_cell(indices, Get(indices))); + } while (IndexUtil::BumpIndices(shape_dynamic, absl::MakeSpan(indices))); +} + +template +TF_ATTRIBUTE_NOINLINE void MutableLiteralBase::PopulateR1( + absl::Span values) { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + CHECK_EQ(shape().rank(), 1); + if (shape().is_static()) { + CHECK_EQ(ShapeUtil::ElementsIn(shape()), values.size()); + } else { + CHECK_EQ(GetDynamicSize(0), values.size()); + } + CHECK_EQ(shape().element_type(), + primitive_util::NativeToPrimitiveType()); + auto data_span = data(); + std::copy(values.begin(), values.end(), data_span.begin()); +} + +template +TF_ATTRIBUTE_NOINLINE void MutableLiteralBase::PopulateR2( + std::initializer_list> values) { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + CHECK_EQ(shape().rank(), 2); + CHECK_EQ(shape().element_type(), + primitive_util::NativeToPrimitiveType()); + + const int64_t values_dim0_size = values.size(); + const int64_t values_dim1_size = values.begin()->size(); + const int64_t literal_dim0_size = shape().is_dynamic_dimension(0) + ? GetDynamicSize(0) + : shape().dimensions(0); + const int64_t literal_dim1_size = shape().is_dynamic_dimension(1) + ? GetDynamicSize(1) + : shape().dimensions(1); + + CHECK_EQ(values_dim0_size, literal_dim0_size); + CHECK_EQ(values_dim1_size, literal_dim1_size); + + int64_t dim0 = 0; + for (auto inner_list : values) { + int64_t dim1 = 0; + for (auto value : inner_list) { + Set({dim0, dim1}, value); + ++dim1; + } + CHECK_EQ(values_dim1_size, dim1); + ++dim0; + } +} + +template +TF_ATTRIBUTE_NOINLINE void MutableLiteralBase::PopulateFromArray( + const Array& values) { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + CHECK(shape().IsArray()); + CHECK_EQ(shape().element_type(), + primitive_util::NativeToPrimitiveType()); + CHECK_EQ(shape().rank(), values.num_dimensions()); + for (int dim = 0; dim < values.num_dimensions(); ++dim) { + int64_t shape_size = shape().is_dynamic_dimension(dim) + ? GetDynamicSize(dim) + : shape().dimensions(dim); + CHECK_EQ(values.dim(dim), shape_size); + } + values.Each([this](absl::Span indices, NativeT value) { + this->Set(indices, value); + }); +} + +template +void MutableLiteralBase::PopulateR2FromArray2D(const Array2D& values) { + PopulateFromArray(values); +} + +template +void MutableLiteralBase::PopulateR3FromArray3D(const Array3D& values) { + PopulateFromArray(values); +} + +template +void MutableLiteralBase::PopulateR4FromArray4D(const Array4D& values) { + PopulateFromArray(values); +} + +template +TF_ATTRIBUTE_NOINLINE Status MutableLiteralBase::PopulateInternal( + absl::FunctionRef, int)> generator, + bool parallel) { + const Shape& this_shape = shape(); + DCHECK(LayoutUtil::IsDenseArray(this_shape)); + TF_RET_CHECK(this_shape.element_type() == + primitive_util::NativeToPrimitiveType()) + << "Failing to populate literal with element type " + << primitive_util::LowercasePrimitiveTypeName(this_shape.element_type()) + << " using data of type " + << primitive_util::LowercasePrimitiveTypeName( + primitive_util::NativeToPrimitiveType()); + PopulateInplaceInternal( + [&](void* dest, absl::Span indices, int thread_id) { + *static_cast(dest) = generator(indices, thread_id); + }, + parallel); + return OkStatus(); +} + +template +TF_ATTRIBUTE_NOINLINE Status MutableLiteralBase::Populate( + absl::FunctionRef)> generator) { + TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + return PopulateInternal( + [&](absl::Span indexes, int /*thread_id*/) { + return generator(indexes); + }, + /*parallel=*/false); +} +template +TF_ATTRIBUTE_NOINLINE Status MutableLiteralBase::PopulateParallel( + absl::FunctionRef, int)> generator) { + TF_RET_CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + return PopulateInternal(generator, + /*parallel=*/data().size() > 32); +} + +template +void MutableLiteralBase::PopulateWithValue(NativeT value) { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + CHECK_EQ(shape().element_type(), + primitive_util::NativeToPrimitiveType()); + for (NativeT& element : data()) { + element = value; + } +} + +template +Literal LiteralBase::Replicate(int64_t times) const { + CHECK(LayoutUtil::IsDenseArray(shape())) + << __func__ << " is only supported for dense arrays: " << shape(); + DimensionVector bounds = {times}; + bounds.reserve(shape().dimensions_size() + 1); + for (int64_t bound : shape().dimensions()) { + bounds.push_back(bound); + } + Literal literal(ShapeUtil::MakeShape(shape().element_type(), bounds)); + int64_t elements = ShapeUtil::ElementsIn(literal.shape()); + if (elements == 0) { + return literal; + } + + DimensionVector output_indices(bounds.size(), 0); + absl::Span input_indices = output_indices; + input_indices.remove_prefix(1); + + bool done = false; + while (!done) { + const auto element = Get(input_indices); + literal.Set(output_indices, element); + + done = true; + for (int n = 0; n < output_indices.size(); ++n) { + ++output_indices[n]; + if (output_indices[n] < bounds[n]) { + done = false; + break; + } + output_indices[n] = 0; + } + } + return literal; +} + +} // namespace xla + +#endif // XLA_LITERAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_comparison.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_comparison.h new file mode 100644 index 0000000000000000000000000000000000000000..fc30fea3b243cb603d444254385ba6df908b7e67 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_comparison.h @@ -0,0 +1,104 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Library for comparing literals without taking a dependency on testing +// libraries. + +#ifndef XLA_LITERAL_COMPARISON_H_ +#define XLA_LITERAL_COMPARISON_H_ + +#include +#include +#include +#include +#include + +#include "xla/error_spec.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status.h" + +namespace xla { +namespace literal_comparison { + +// Returns ok if the given shapes have the same rank, dimension sizes, and +// primitive types. +Status EqualShapes(const Shape& expected, const Shape& actual); + +// Returns ok if the given literals share identical dynamic shapes and +// dimension sizes. +Status EqualDynamicShapesAndDimensions(const LiteralSlice& expected, + const LiteralSlice& actual); + +// Returns ok if the expected and actual literals are (bitwise) equal for all +// elements in the literal. Also, asserts that the rank, dimensions sizes, and +// primitive type are equal. +Status Equal(const LiteralSlice& expected, const LiteralSlice& actual); + +// Structure that contains the distribution of absolute and relative errors, +// bucketized into five buckets: [0.0001, 0.001, 0.01, 0.1, 1]. +// Useful to understand the distribution of errors and set the permissible +// error bounds in an ErrorSpec. +struct ErrorBuckets { + explicit ErrorBuckets(const std::vector& absolute_error_buckets = {}, + const std::vector& rel_error_buckets = {}) + : abs_error_buckets(absolute_error_buckets), + rel_error_buckets(rel_error_buckets) {} + + const std::vector abs_error_buckets; + const std::vector rel_error_buckets; +}; + +using MiscompareCallback = std::function; + +// Inspects whether the expected and actual literals are within the given error +// bound for all elements. Also, inspects whether the rank, dimensions sizes, +// and dimension bounds are equivalent. +// +// Tuples are matched recursively. +// +// When comparing tensors of non-floating-point type, this inspects for exact +// equality, ignoring the ErrorSpec. +// +// If the shape of the literals is neither a complex/floating-point tensor nor a +// tuple which contains a complex/floating-point tensor, Near() is equivalent to +// Equal(). We don't raise an error in this case, because we want to allow +// callers to call Near() even if they have no preconceptions about the shapes +// being compared. +// +// If detailed_message is true, then the error message in the assertion result +// will contain a more detailed breakdown of mismatches. By default, we display +// a detailed message only for "large" inputs. +// +// If miscompare_callback is nullptr, Near will return an error on the first +// detected mismatch. +Status Near(const LiteralSlice& expected, const LiteralSlice& actual, + const ErrorSpec& error, std::optional detailed_message, + const MiscompareCallback& miscompare_callback); + +// Calling ToString on a literal with over 100 million elements takes around +// 3 minutes. The utility of printing a literal with >1000 elements is +// questionable, especially when writing the Literal proto to disk is orders +// of magnitude faster. +std::string ToStringTruncated(const LiteralSlice& literal); + +} // namespace literal_comparison +} // namespace xla + +#endif // XLA_LITERAL_COMPARISON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e125ef7fe30b766eec17b7778eb564af726fc9fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/literal_util.h @@ -0,0 +1,556 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Utilities for dealing with Literal protobufs. + +#ifndef XLA_LITERAL_UTIL_H_ +#define XLA_LITERAL_UTIL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/array.h" +#include "xla/array2d.h" +#include "xla/array3d.h" +#include "xla/array4d.h" +#include "xla/layout.h" +#include "xla/layout_util.h" +#include "xla/literal.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/core/bitmap.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +namespace xla { + +class LiteralUtil { + public: + LiteralUtil() = delete; + + // Returns a literal scalar representing the first element. + static Literal GetFirstScalarLiteral(const LiteralSlice& literal); + // Returns a literal scalar representing the element at `multi_index`. + static Literal GetScalarLiteral(const LiteralBase& literal, + absl::Span multi_index); + // Sets the value of the element at `multi_index` with a scalar literal. + static void SetScalarLiteral(MutableLiteralBase& literal, + absl::Span multi_index, + const LiteralBase& scalar); + + // Creates a new literal of a given rank. To minimize ambiguity (for users + // and the compiler) these CreateR[0-2] methods should explicitly specify the + // native type. For example: + // + // CreateR1({1.0, 42.0}); + // CreateR2({{1, 2}, {3, 4}}); + // + // The variants not ending with WithLayout use the default XLA layout for the + // literal's linear representation in memory. + template + static Literal CreateR0(NativeT value); + template + static Literal CreateR1(absl::Span values); + static Literal CreateR1(const tsl::core::Bitmap& values); + template + static Literal CreateR2( + std::initializer_list> values); + template + static Literal CreateR2WithLayout( + std::initializer_list> values, + const Layout& layout); + template + static Literal CreateR3(std::initializer_list< + std::initializer_list>> + values); + template + static Literal CreateR3WithLayout( + std::initializer_list< + std::initializer_list>> + values, + const Layout& layout); + template + static Literal CreateR4( + std::initializer_list>>> + values); + template + static Literal CreateR4WithLayout( + std::initializer_list>>> + values, + const Layout& layout); + + // Creates a scalar literal value zero of the given primitive type. + static Literal Zero(PrimitiveType primitive_type); + // Creates a scalar literal value one of the given primitive type. + static Literal One(PrimitiveType primitive_type); + // Creates a scalar literal value containing the minimum value of the given + // primitive type. For floating-point types supporting inf, returns -inf. + static Literal MinValue(PrimitiveType primitive_type); + // Creates a scalar literal value containing the maximum value of the given + // primitive type. For floating-point types supporting inf, returns inf. + static Literal MaxValue(PrimitiveType primitive_type); + // Creates a scalar literal value containing the NaN value of the given + // primitive type. Fail for non-inexact types. For complex types, returns a + // nan + nan * j value. + static StatusOr NanValue(PrimitiveType primitive_type); + // Creates a literal of the given shape where each element is `value`. + template + static Literal CreateFullWithDescendingLayout( + absl::Span dimensions, NativeT value); + + // Creates a new literal from an Array type. The variants not ending with + // WithLayout use the default XLA layout for the literal's linear + // representation in memory. + template + static Literal CreateFromArray(const Array& values); + template + static Literal CreateFromArrayWithLayout(const Array& values, + const Layout& layout); + template + static Literal CreateR2FromArray2D(const Array2D& values); + template + static Literal CreateR2FromArray2DWithLayout(const Array2D& values, + const Layout& layout); + template + static Literal CreateR3FromArray3D(const Array3D& values); + template + static Literal CreateR3FromArray3DWithLayout(const Array3D& values, + const Layout& layout); + template + static Literal CreateR4FromArray4D(const Array4D& values); + template + static Literal CreateR4FromArray4DWithLayout(const Array4D& values, + const Layout& layout); + + // Creates a new vector of U8s literal value from a string. + static Literal CreateR1U8(absl::string_view value); + + // Creates a linspace-populated literal with the given number of rows and + // columns. + static Literal CreateR2F32Linspace(float from, float to, int64_t rows, + int64_t cols); + + // Creates a literal that projects the (x, y) dimensions given in values into + // the z dimension given by "projection". + template + static Literal CreateR3Projected( + std::initializer_list> values, + int64_t projection); + + // Creates a literal that projects the (x, y) dimensions given in values into + // the z and p dimensions given. + template + static Literal CreateR4Projected( + std::initializer_list> values, + int64_t projection_p, int64_t projection_z); + + // Returns an identity matrix (rank 2) with the given row and column count. + template + static Literal MakeIdentityR2(int64_t size); + + // Returns a tuple literal composed of given literals. Data is copied from the + // given elements into the returned literal. + static Literal MakeTuple(absl::Span elements); + + static Literal MakeTupleFromSlices(absl::Span elements); + + // As above, but intended to be invoked with move semantics; i.e. + // + // std::vector elements = ...; + // auto result = LiteralUtil::MakeTupleOwned(std::move(elements)); + // + // This would have been declared as an overload, but there is ambiguity + // in invocation between the above signature and this one. + static Literal MakeTupleOwned(std::vector elements); + + // This overload lets you pass a list of Literals to MakeTupleOwned: + // + // LiteralUtil::MakeTupleOwned(LiteralUtil::CreateR1(...), ...). + // + // Simply relying on the MakeTupleOwned(std::vector) + // overload doesn't work because std::initializer_list's elements are always + // const. + // + // The arguments to this function must all be Literal. + template + static Literal MakeTupleOwned(Ts... elements) { + std::array arr{std::move(elements)...}; + std::vector v; + v.insert(v.begin(), std::make_move_iterator(arr.begin()), + std::make_move_iterator(arr.end())); + return MakeTupleOwned(std::move(v)); + } + + // Create a constant token literal. Token types have no value. + static Literal CreateToken(); + + // Creates a new Literal object with its values havings the primitive_type + // type, and with dimensions defined by the dimensions parameter. + // The content of the literal values is the default value of the primitive + // type of literal itself (0 for numeric types, and false for predicates). + static Literal CreateFromDimensions(PrimitiveType primitive_type, + absl::Span dimensions); + + // ConvertTo family of functions: + // If the given literal's data type is , converts it to a + // literal; otherwise, returns a copy of it. If the literal is a tuple, + // recursively converts its elements. + static Literal ConvertBF16ToF32(const LiteralSlice& bf16_literal); + static Literal ConvertBF16ToF64(const LiteralSlice& bf16_literal); + static Literal ConvertF32ToF8E4M3FNUZ(const LiteralSlice& f32_literal); + static Literal ConvertF32ToF8E5M2FNUZ(const LiteralSlice& f32_literal); + static Literal ConvertF32ToBF16(const LiteralSlice& f32_literal); + static Literal ConvertF32ToS8(const LiteralSlice& f32_literal); + static Literal ConvertF32ToF64(const LiteralSlice& f32_literal); + static Literal ConvertF64ToBF16(const LiteralSlice& f64_literal); + static Literal ConvertF64ToF32(const LiteralSlice& f64_literal); + static Literal ConvertS32ToF32(const LiteralSlice& s32_literal); + + // Creates a scalar literal whose value is the maximum value of a given + // literal slice. + static Literal MaxElement(const LiteralSlice& literal); + + // Creates a literal with a new shape with the given new dimensions using the + // data in the given input literal. For reshaping purposes the (flat) data + // buffer of the input literal is assumed to have the given minor_to_major + // layout order. + static Literal ReshapeSlice(absl::Span new_dimensions, + absl::Span minor_to_major, + const LiteralSlice& literal); + + // Creates a literal with the supplied shape, and uses the provided value + // generator to populate the literal's values. + // Returns the new literal object, or an error Status if failed. + template > + static StatusOr CreateLiteralWithGenerator( + const Shape& shape, + absl::FunctionRef)> generator); + + // Creates a literal with the supplied shape, and initializes the literal + // values using a normal distribution with given mean and stddev standard + // deviation, and using the engine as entropy generator. + // Returns the new literal object, or an error Status if failed. + template > + static StatusOr CreateRandomLiteral(const Shape& shape, E* engine, + T mean, T stddev); + + // Creates a literal with the supplied shape, and initializes the literal + // values using a normal distribution with given mean and stddev standard + // deviation. + // Returns the new literal object, or an error Status if failed. + template > + static StatusOr CreateRandomLiteral(const Shape& shape, T mean, + T stddev); + + // + // End of factory methods. + + // Returns a multi-dimensional index as a string. For example: '{7, 8}' will + // be returned for a 2-dimensional index with dimension 0 index equal to 7, + // dimension 1 equal to 8. + static std::string MultiIndexAsString(absl::Span multi_index); + + // Converts the given literal to a scalar int64_t, if possible. + // + // Fails if the literal is not an integral type or if the value it contains + // cannot be represented as an int64_t. + static std::optional LiteralAsScalarInt64(const Literal& l); +}; + +std::ostream& operator<<(std::ostream& out, const Literal& literal); + +template +/* static */ Literal LiteralUtil::CreateR0(NativeT value) { + Literal literal(ShapeUtil::MakeShape( + primitive_util::NativeToPrimitiveType(), {})); + literal.Set({}, value); + return literal; +} + +template +/* static */ Literal LiteralUtil::CreateR1(absl::Span values) { + Literal literal( + ShapeUtil::MakeShape(primitive_util::NativeToPrimitiveType(), + {static_cast(values.size())})); + literal.PopulateR1(values); + return literal; +} + +template +/* static */ Literal LiteralUtil::CreateR2WithLayout( + std::initializer_list> values, + const Layout& layout) { + Literal literal(ShapeUtil::MakeShapeWithDenseLayout( + primitive_util::NativeToPrimitiveType(), + {static_cast(values.size()), + static_cast(values.begin()->size())}, + layout.minor_to_major())); + literal.PopulateR2(values); + return literal; +} + +template +/* static */ Literal LiteralUtil::CreateR2( + std::initializer_list> values) { + return CreateR2WithLayout(values, LayoutUtil::GetDefaultLayoutForR2()); +} + +template +/* static */ Literal LiteralUtil::CreateR3WithLayout( + std::initializer_list>> + values, + const Layout& layout) { + const int64_t d0 = values.size(); + const int64_t d1 = values.begin()->size(); + const int64_t d2 = values.begin()->begin()->size(); + Array3D tmp(d0, d1, d2); + int64_t i0 = 0; + for (auto d1_values : values) { + int64_t i1 = 0; + for (auto d2_values : d1_values) { + int64_t i2 = 0; + for (auto value : d2_values) { + tmp(i0, i1, i2) = value; + ++i2; + } + ++i1; + } + ++i0; + } + return CreateR3FromArray3DWithLayout(tmp, layout); +} + +template +/* static */ Literal LiteralUtil::CreateR3( + std::initializer_list>> + values) { + return CreateR3WithLayout(values, LayoutUtil::GetDefaultLayoutForR3()); +} + +template +/* static */ Literal LiteralUtil::CreateR4WithLayout( + std::initializer_list>>> + values, + const Layout& layout) { + const int64_t d0 = values.size(); + const int64_t d1 = values.begin()->size(); + const int64_t d2 = values.begin()->begin()->size(); + const int64_t d3 = values.begin()->begin()->begin()->size(); + Array4D tmp(d0, d1, d2, d3); + int64_t i0 = 0; + for (auto d1_values : values) { + int64_t i1 = 0; + for (auto d2_values : d1_values) { + int64_t i2 = 0; + for (auto d3_values : d2_values) { + int64_t i3 = 0; + for (auto value : d3_values) { + tmp(i0, i1, i2, i3) = value; + ++i3; + } + ++i2; + } + ++i1; + } + ++i0; + } + return CreateR4FromArray4DWithLayout(tmp, layout); +} + +template +/* static */ Literal LiteralUtil::CreateR4( + std::initializer_list>>> + values) { + return CreateR4WithLayout(values, LayoutUtil::GetDefaultLayoutForR4()); +} + +template +/* static */ Literal LiteralUtil::CreateFromArrayWithLayout( + const Array& values, const Layout& layout) { + Literal literal(ShapeUtil::MakeShapeWithDenseLayout( + primitive_util::NativeToPrimitiveType(), values.dimensions(), + layout.minor_to_major())); + literal.PopulateFromArray(values); + return literal; +} + +template +/* static */ Literal LiteralUtil::CreateFromArray( + const Array& values) { + return CreateFromArrayWithLayout( + values, LayoutUtil::GetDefaultLayoutForRank(values.num_dimensions())); +} + +template +/* static */ Literal LiteralUtil::CreateR2FromArray2DWithLayout( + const Array2D& values, const Layout& layout) { + return CreateFromArrayWithLayout(values, layout); +} + +template +/* static */ Literal LiteralUtil::CreateR2FromArray2D( + const Array2D& values) { + return CreateFromArray(values); +} + +template +/* static */ Literal LiteralUtil::CreateR3FromArray3DWithLayout( + const Array3D& values, const Layout& layout) { + return CreateFromArrayWithLayout(values, layout); +} + +template +/* static */ Literal LiteralUtil::CreateR3FromArray3D( + const Array3D& values) { + return CreateFromArray(values); +} + +template +/* static */ Literal LiteralUtil::CreateR3Projected( + std::initializer_list> values, + int64_t projection) { + int64_t dim0_size = projection; + int64_t dim1_size = values.size(); + int64_t dim2_size = values.begin()->size(); + + Array3D array(dim0_size, dim1_size, dim2_size); + for (int64_t dim0 = 0; dim0 < dim0_size; ++dim0) { + int64_t dim1 = 0; + for (auto inner_list : values) { + int64_t dim2 = 0; + for (auto value : inner_list) { + array(dim0, dim1, dim2) = value; + ++dim2; + } + CHECK_EQ(dim2_size, dim2); + ++dim1; + } + CHECK_EQ(dim1_size, dim1); + } + return CreateR3FromArray3D(array); +} + +template +/* static */ Literal LiteralUtil::CreateR4Projected( + std::initializer_list> values, + int64_t projection_p, int64_t projection_z) { + int64_t dim0_size = projection_p; + int64_t dim1_size = projection_z; + int64_t dim2_size = values.size(); + int64_t dim3_size = values.begin()->size(); + + Array4D array(dim0_size, dim1_size, dim2_size, dim3_size); + for (int64_t dim0 = 0; dim0 < dim0_size; ++dim0) { + for (int64_t dim1 = 0; dim1 < dim1_size; ++dim1) { + int64_t dim2 = 0; + for (auto inner_list : values) { + int64_t dim3 = 0; + for (auto value : inner_list) { + array(dim0, dim1, dim2, dim3) = value; + ++dim3; + } + CHECK_EQ(dim3_size, dim3); + ++dim2; + } + CHECK_EQ(dim2_size, dim2); + } + } + return CreateR4FromArray4D(array); +} + +template +/* static */ Literal LiteralUtil::CreateR4FromArray4D( + const Array4D& values) { + return CreateFromArray(values); +} + +template +/* static */ Literal LiteralUtil::CreateR4FromArray4DWithLayout( + const Array4D& values, const Layout& layout) { + return CreateFromArrayWithLayout(values, layout); +} + +// Returns an identity matrix (rank 2) with the given row and column count. +template +/* static */ Literal LiteralUtil::MakeIdentityR2(int64_t size) { + Array2D array(size, size, 0); + for (int64_t i = 0; i < size; ++i) { + array(i, i) = 1; + } + return CreateR2FromArray2D(array); +} + +template +/* static */ Literal LiteralUtil::CreateFullWithDescendingLayout( + absl::Span dimensions, NativeT value) { + Literal literal(ShapeUtil::MakeShapeWithDescendingLayout( + primitive_util::NativeToPrimitiveType(), dimensions)); + literal.PopulateWithValue(value); + return literal; +} + +template +/* static */ StatusOr LiteralUtil::CreateLiteralWithGenerator( + const Shape& shape, + absl::FunctionRef)> generator) { + using NativeT = primitive_util::NativeTypeOf; + TF_RET_CHECK(shape.element_type() == type); + Literal literal(shape); + TF_RETURN_IF_ERROR(literal.Populate( + [=](absl::Span indexes) { return generator(indexes); })); + return std::move(literal); +} + +template +/* static */ StatusOr LiteralUtil::CreateRandomLiteral( + const Shape& shape, E* engine, T mean, T stddev) { + using NativeT = primitive_util::NativeTypeOf; + std::normal_distribution generator(mean, stddev); + return CreateLiteralWithGenerator( + shape, [&](absl::Span /*indexes*/) { + return static_cast(generator(*engine)); + }); +} + +template +/* static */ StatusOr LiteralUtil::CreateRandomLiteral( + const Shape& shape, T mean, T stddev) { + std::minstd_rand0 engine; + return CreateRandomLiteral(shape, &engine, mean, stddev); +} + +} // namespace xla + +#endif // XLA_LITERAL_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/map_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/map_util.h new file mode 100644 index 0000000000000000000000000000000000000000..b6321bcba40b21c5ed294f3fe3f88c34b9a08121 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/map_util.h @@ -0,0 +1,125 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MAP_UTIL_H_ +#define XLA_MAP_UTIL_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/statusor.h" +#include "xla/util.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// FindOrDie returns a const reference to the value associated with +// the given key if it exists. Crashes otherwise. +// +// This is intended as a replacement for operator[] as an rvalue (for reading) +// when the key is guaranteed to exist. +template +const typename Collection::value_type::second_type& FindOrDie( + const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + CHECK(it != collection.end()) << "Map key not found: " << key; + return it->second; +} + +// Same as above, but returns a non-const reference. +template +typename Collection::value_type::second_type& FindOrDie( + Collection& collection, // NOLINT + const typename Collection::value_type::first_type& key) { + typename Collection::iterator it = collection.find(key); + CHECK(it != collection.end()) << "Map key not found: " << key; + return it->second; +} + +// Like FindOrDie but returns an error instead of dying if `key` is not in +// `container`. +template +StatusOr< + std::reference_wrapper> +MaybeFind(const Collection& collection, + const typename Collection::value_type::first_type& key) { + typename Collection::const_iterator it = collection.find(key); + if (it == collection.end()) { + std::ostringstream os; + os << key; + return NotFound("key not found: %s", os.str()); + } + return {it->second}; +} + +// Returns a const reference to the value associated with the given key if it +// exists, otherwise returns a const reference to the provided default value. +// +// WARNING: If a temporary object is passed as the default "value," +// this function will return a reference to that temporary object, +// which will be destroyed at the end of the statement. A common +// example: if you have a map with string values, and you pass a char* +// as the default "value," either use the returned value immediately +// or store it in a string (not string&). +template +const typename Collection::value_type::second_type& FindOrDefault( + const Collection& collection, + const typename Collection::value_type::first_type& key, + const typename Collection::value_type::second_type& value) { + auto it = collection.find(key); + if (it != collection.end()) return it->second; + return value; +} + +// Inserts the key-value pair into the collection. Dies if key was already +// present. +template +void InsertOrDie(Collection* const collection, Key&& key, Value&& value) { + auto p = collection->insert( + std::make_pair(std::forward(key), std::forward(value))); + CHECK(p.second) << "duplicate key: " << key; +} + +// Returns true if and only if the given collection contains the given key. +template +bool ContainsKey(const Collection& collection, const Key& key) { + return collection.find(key) != collection.end(); +} + +// Returns a function that returns whether the map contains the given key. +template +auto IsKeyIn(const absl::flat_hash_map& map) { + return [&](const Key& key) { return map.contains(key); }; +} + +// Returns a function that returns whether the set contains the given value. +template +auto IsValueIn(const absl::flat_hash_set& set) { + return [&](const T& value) { return set.contains(value); }; +} + +// Inserts `value` into `set`. Dies if it was already present. +template +void InsertOrDie(Set* const set, Value&& value) { + CHECK(set->insert(std::forward(value)).second) + << "duplicate value: " << value; +} + +} // namespace xla + +#endif // XLA_MAP_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/metric_table_report.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/metric_table_report.h new file mode 100644 index 0000000000000000000000000000000000000000..9c3659363e8b8fc92d235df2d2b2440d12c2971f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/metric_table_report.h @@ -0,0 +1,175 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_METRIC_TABLE_REPORT_H_ +#define XLA_METRIC_TABLE_REPORT_H_ + +#include +#include + +#include "absl/strings/str_cat.h" + +namespace xla { + +// Class for creating a text format table showing entries with a metric +// (e.g. cycles) and a text (e.g. name of function taking that many +// cycles). Entries are grouped by a category and sorted in decreasing order of +// the metric. +// +// Example of a categories table generated using this class: +// +// ********** microseconds report ********** +// There are 3,912,517 microseconds in total. +// There are 123 microseconds ( 0.00%) not accounted for by the data. +// There are 3002 ops. +// +// ********** categories table ********** +// The left hand side numbers are microseconds. +// 1,749,414 (44.71% Σ44.72%) convolution (206 ops) +// * 10.51% %convolution.202 +// * 10.51% %convolution.204 +// * 10.51% %convolution.203 +// * ... (203 more ops) +// 884,939 (22.62% Σ67.33%) convolution window-dilated (7 ops) +// * 7.50% %convolution-window-dilated.7 +// [...] +// +// The entry table is similar, it just has the entries directly as the entries +// instead of grouping by categories first. +class MetricTableReport { + public: + // Represents an entry in the table. + struct Entry { + // Text to show in the entry table for this entry. + std::string text; + + // Text to show in the category table for this entry. + std::string short_text; + + // Text that represents the category of this entry - entries with the same + // category are grouped together in the category table. + std::string category_text; + + // The value of the metric for this entry. + double metric = 0.0; + }; + + void AddEntry(Entry entry); + + // The default name for the metric is "units", this function allows setting a + // more meaningful name. + void SetMetricName(std::string metric_name); + + // The default name for referring to entries is "entries", this functions + // allows setting a more meaningful name. + void SetEntryName(std::string entry_name); + + // By default the size of the table is limited. Calling this function forces + // all entries to be shown no matter how many there are. + void SetShowAllEntries(); + + // Set option to show a table with data on the categories of entries. + void SetShowCategoryTable(); + + // Set option to show a table with data on the entries. + void SetShowEntryTable(); + + // Returns the report as a string. expected_metric_sum is the expected sum of + // the metric across the entries. It is not an error for the actual sum to be + // different from the expectation - the report will include the + // discrepancy. All metric percentages are for the ratio with respect to the + // expected sum, not the actual sum. + std::string MakeReport(double expected_metric_sum); + + // As MakeReport(), but writes the report to the INFO log in a way that avoids + // cutting the report off if it is longer than the maximum line length for a + // logged line. Individual lines in the report may still be cut off, but they + // would have to be very long for that to happen. + void WriteReportToInfoLog(double expected_metric_sum); + + private: + static constexpr double kDefaultMaxMetricProportionToShow = 0.99; + static constexpr int64_t kDefaultMaxEntriesToShow = 100; + static constexpr int64_t kDefaultMaxEntriesPerCategoryToShow = 5; + + // Append all parameters to the report. + template + void AppendLine(Args... args) { + absl::StrAppend(&report_, std::forward(args)..., "\n"); + } + + // Represents a set of entries with the same category_text. + struct Category { + std::string category_text; + double metric_sum = 0.0; // Sum of metric across entries. + std::vector entries; + }; + + // Returns a vector of categories of entries with the same category_text. The + // vector is sorted in order of decreasing metric sum. + // + // The returned categories contain pointers into the entries parameter. The + // style guide requires parameters to which references/pointers are retained + // to be taken by pointer, even for const parameters, so that is why entries + // is taken by pointer. + static std::vector MakeCategories( + const std::vector* entries); + + // Append a header to the report. + void AppendHeader(); + + // Append a table of categories to the report. + void AppendCategoryTable(); + + // Append a table of entries to the report. + void AppendEntryTable(); + + // Appends a row of a table to the report. + void AppendTableRow(const std::string& text, const double metric, + const double running_metric_sum); + + // Returns the discrepancy between the expected sum of the metric of the + // entries and the actual sum. + double UnaccountedMetric(); + + // Formats the metric value as a string. + std::string MetricString(double metric); + + // Returns a string representing the metric value as a proportion of the + // expected metric sum. + std::string MetricPercent(double metric); + + // The entries to make a report about. + std::vector entries_; + + double expected_metric_sum_ = 0.0; + std::string metric_name_ = "units"; + std::string entry_name_ = "entries"; + bool show_category_table_ = false; + bool show_entry_table_ = false; + + // These members control how many categories and entries to show in tables. + int64_t max_entries_to_show_ = kDefaultMaxEntriesToShow; + int64_t max_entries_per_category_to_show_ = + kDefaultMaxEntriesPerCategoryToShow; + double max_metric_proportion_to_show_ = kDefaultMaxMetricProportionToShow; + + // The report that is being created. + std::string report_; +}; + +} // namespace xla + +#endif // XLA_METRIC_TABLE_REPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..0310dbf0a9689a319ad318ec399014c984f7c6b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h @@ -0,0 +1,64 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_BACKENDS_CPU_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_BACKENDS_CPU_TRANSFORMS_PASSES_H_ + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +namespace xla { +namespace cpu { + +//===----------------------------------------------------------------------===// +// Auxiliary passes for lowering to XLA Cpu runtime. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createConvertXlaCpuToCpuRuntimePass(); + +std::unique_ptr> +createXlaAbiLegalizationPass(); + +std::unique_ptr> +createLegalizeLibraryOpsPass(); + +std::unique_ptr> +createLegalizeI1VectorTransferOpsPass(); + +std::unique_ptr> +createConvertXlaCpuMemRefElementCastToLLVMPass(); + +std::unique_ptr> +createRemoveCopiesToOutParamsPass(); + +std::unique_ptr> +createSparseCustomCallRewritingPass(); + +std::unique_ptr> +createRewriteReallocToAllocPass(); + +//===-----------------------------------------------------------------------===/ + +#define GEN_PASS_REGISTRATION +#include "xla/mlir/backends/cpu/transforms/passes.h.inc" + +} // namespace cpu +} // namespace xla + +#endif // XLA_MLIR_BACKENDS_CPU_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..85bf402aeb96ff961a24851db7df895b46fdfefe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/cpu/transforms/passes.h.inc @@ -0,0 +1,1040 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +#define GEN_PASS_DECL_CONVERTXLACPUTOCPURUNTIMEPASS +#define GEN_PASS_DECL_LEGALIZEI1VECTORTRANSFEROPSPASS +#define GEN_PASS_DECL_LEGALIZELIBRARYOPSPASS +#define GEN_PASS_DECL_LEGALIZEXLAABIPASS +#define GEN_PASS_DECL_REMOVECOPIESTOOUTPARAMSPASS +#define GEN_PASS_DECL_REWRITEREALLOCTOALLOCPASS +#define GEN_PASS_DECL_SPARSECUSTOMCALLREWRITINGPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// ConvertXlaCpuMemRefElementCastToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +#undef GEN_PASS_DECL_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +namespace impl { + +template +class ConvertXlaCpuMemRefElementCastToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertXlaCpuMemRefElementCastToLLVMPassBase; + + ConvertXlaCpuMemRefElementCastToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertXlaCpuMemRefElementCastToLLVMPassBase(const ConvertXlaCpuMemRefElementCastToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-convert-memref-element-cast-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-convert-memref-element-cast-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Converts xla_cpu.memref_element_cast ops to LLVM."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertXlaCpuMemRefElementCastToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertXlaCpuMemRefElementCastToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertXlaCpuMemRefElementCastToLLVMPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTXLACPUMEMREFELEMENTCASTTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertXlaCpuToCpuRuntimePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTXLACPUTOCPURUNTIMEPASS +#undef GEN_PASS_DECL_CONVERTXLACPUTOCPURUNTIMEPASS +#endif // GEN_PASS_DECL_CONVERTXLACPUTOCPURUNTIMEPASS +#ifdef GEN_PASS_DEF_CONVERTXLACPUTOCPURUNTIMEPASS +namespace impl { + +template +class ConvertXlaCpuToCpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertXlaCpuToCpuRuntimePassBase; + + ConvertXlaCpuToCpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertXlaCpuToCpuRuntimePassBase(const ConvertXlaCpuToCpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-to-cpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-to-cpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts xla_cpu operations to XLA Cpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertXlaCpuToCpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertXlaCpuToCpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertXlaCpuToCpuRuntimePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTXLACPUTOCPURUNTIMEPASS +#endif // GEN_PASS_DEF_CONVERTXLACPUTOCPURUNTIMEPASS + +//===----------------------------------------------------------------------===// +// LegalizeI1VectorTransferOpsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LEGALIZEI1VECTORTRANSFEROPSPASS +#undef GEN_PASS_DECL_LEGALIZEI1VECTORTRANSFEROPSPASS +#endif // GEN_PASS_DECL_LEGALIZEI1VECTORTRANSFEROPSPASS +#ifdef GEN_PASS_DEF_LEGALIZEI1VECTORTRANSFEROPSPASS +namespace impl { + +template +class LegalizeI1VectorTransferOpsPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeI1VectorTransferOpsPassBase; + + LegalizeI1VectorTransferOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeI1VectorTransferOpsPassBase(const LegalizeI1VectorTransferOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-i1-vector-transfers"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-i1-vector-transfers"; } + + ::llvm::StringRef getDescription() const override { return "Legalizes transfer ops operating on vectors of i1."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeI1VectorTransferOpsPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeI1VectorTransferOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeI1VectorTransferOpsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LEGALIZEI1VECTORTRANSFEROPSPASS +#endif // GEN_PASS_DEF_LEGALIZEI1VECTORTRANSFEROPSPASS + +//===----------------------------------------------------------------------===// +// LegalizeLibraryOpsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LEGALIZELIBRARYOPSPASS +#undef GEN_PASS_DECL_LEGALIZELIBRARYOPSPASS +#endif // GEN_PASS_DECL_LEGALIZELIBRARYOPSPASS +#ifdef GEN_PASS_DEF_LEGALIZELIBRARYOPSPASS +namespace impl { + +template +class LegalizeLibraryOpsPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeLibraryOpsPassBase; + + LegalizeLibraryOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeLibraryOpsPassBase(const LegalizeLibraryOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-library-ops"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-library-ops"; } + + ::llvm::StringRef getDescription() const override { return "Legalizes ops that map to runtime library calls."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeLibraryOpsPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeLibraryOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeLibraryOpsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LEGALIZELIBRARYOPSPASS +#endif // GEN_PASS_DEF_LEGALIZELIBRARYOPSPASS + +//===----------------------------------------------------------------------===// +// LegalizeXlaAbiPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LEGALIZEXLAABIPASS +#undef GEN_PASS_DECL_LEGALIZEXLAABIPASS +#endif // GEN_PASS_DECL_LEGALIZEXLAABIPASS +#ifdef GEN_PASS_DEF_LEGALIZEXLAABIPASS +namespace impl { + +template +class LegalizeXlaAbiPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeXlaAbiPassBase; + + LegalizeXlaAbiPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeXlaAbiPassBase(const LegalizeXlaAbiPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-abi"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-abi"; } + + ::llvm::StringRef getDescription() const override { return "Converts layouts and data formats at ABI boundaries"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeXlaAbiPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeXlaAbiPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeXlaAbiPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LEGALIZEXLAABIPASS +#endif // GEN_PASS_DEF_LEGALIZEXLAABIPASS + +//===----------------------------------------------------------------------===// +// RemoveCopiesToOutParamsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_REMOVECOPIESTOOUTPARAMSPASS +#undef GEN_PASS_DECL_REMOVECOPIESTOOUTPARAMSPASS +#endif // GEN_PASS_DECL_REMOVECOPIESTOOUTPARAMSPASS +#ifdef GEN_PASS_DEF_REMOVECOPIESTOOUTPARAMSPASS +namespace impl { + +template +class RemoveCopiesToOutParamsPassBase : public ::mlir::OperationPass { +public: + using Base = RemoveCopiesToOutParamsPassBase; + + RemoveCopiesToOutParamsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RemoveCopiesToOutParamsPassBase(const RemoveCopiesToOutParamsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-remove-copies-to-out-params"); + } + ::llvm::StringRef getArgument() const override { return "xla-remove-copies-to-out-params"; } + + ::llvm::StringRef getDescription() const override { return "Removes redundant alloc/copy pairs to out params."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RemoveCopiesToOutParamsPass"); + } + ::llvm::StringRef getName() const override { return "RemoveCopiesToOutParamsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RemoveCopiesToOutParamsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_REMOVECOPIESTOOUTPARAMSPASS +#endif // GEN_PASS_DEF_REMOVECOPIESTOOUTPARAMSPASS + +//===----------------------------------------------------------------------===// +// RewriteReallocToAllocPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_REWRITEREALLOCTOALLOCPASS +#undef GEN_PASS_DECL_REWRITEREALLOCTOALLOCPASS +#endif // GEN_PASS_DECL_REWRITEREALLOCTOALLOCPASS +#ifdef GEN_PASS_DEF_REWRITEREALLOCTOALLOCPASS +namespace impl { + +template +class RewriteReallocToAllocPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteReallocToAllocPassBase; + + RewriteReallocToAllocPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteReallocToAllocPassBase(const RewriteReallocToAllocPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rewrite-realloc-to-alloc"); + } + ::llvm::StringRef getArgument() const override { return "xla-rewrite-realloc-to-alloc"; } + + ::llvm::StringRef getDescription() const override { return "Rewrites realloc to alloc + copy"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteReallocToAllocPass"); + } + ::llvm::StringRef getName() const override { return "RewriteReallocToAllocPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteReallocToAllocPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_REWRITEREALLOCTOALLOCPASS +#endif // GEN_PASS_DEF_REWRITEREALLOCTOALLOCPASS + +//===----------------------------------------------------------------------===// +// SparseCustomCallRewritingPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SPARSECUSTOMCALLREWRITINGPASS +#undef GEN_PASS_DECL_SPARSECUSTOMCALLREWRITINGPASS +#endif // GEN_PASS_DECL_SPARSECUSTOMCALLREWRITINGPASS +#ifdef GEN_PASS_DEF_SPARSECUSTOMCALLREWRITINGPASS +namespace impl { + +template +class SparseCustomCallRewritingPassBase : public ::mlir::OperationPass { +public: + using Base = SparseCustomCallRewritingPassBase; + + SparseCustomCallRewritingPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SparseCustomCallRewritingPassBase(const SparseCustomCallRewritingPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-sparse-custom-call-to-pack"); + } + ::llvm::StringRef getArgument() const override { return "xla-sparse-custom-call-to-pack"; } + + ::llvm::StringRef getDescription() const override { return "Converts CustomCall operations to sparse operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SparseCustomCallRewritingPass"); + } + ::llvm::StringRef getName() const override { return "SparseCustomCallRewritingPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SparseCustomCallRewritingPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_SPARSECUSTOMCALLREWRITINGPASS +#endif // GEN_PASS_DEF_SPARSECUSTOMCALLREWRITINGPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// ConvertXlaCpuMemRefElementCastToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertXlaCpuMemRefElementCastToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertXlaCpuMemRefElementCastToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertXlaCpuMemRefElementCastToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertXlaCpuMemRefElementCastToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertXlaCpuToCpuRuntimePass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertXlaCpuToCpuRuntimePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertXlaCpuToCpuRuntimePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertXlaCpuToCpuRuntimePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertXlaCpuToCpuRuntimePass(); + }); +} + +//===----------------------------------------------------------------------===// +// LegalizeI1VectorTransferOpsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLegalizeI1VectorTransferOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeI1VectorTransferOpsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLegalizeI1VectorTransferOpsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeI1VectorTransferOpsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LegalizeLibraryOpsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLegalizeLibraryOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeLibraryOpsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLegalizeLibraryOpsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeLibraryOpsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LegalizeXlaAbiPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLegalizeXlaAbiPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createXlaAbiLegalizationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLegalizeXlaAbiPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createXlaAbiLegalizationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RemoveCopiesToOutParamsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerRemoveCopiesToOutParamsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRemoveCopiesToOutParamsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerRemoveCopiesToOutParamsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRemoveCopiesToOutParamsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RewriteReallocToAllocPass Registration +//===----------------------------------------------------------------------===// + +inline void registerRewriteReallocToAllocPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteReallocToAllocPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerRewriteReallocToAllocPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteReallocToAllocPass(); + }); +} + +//===----------------------------------------------------------------------===// +// SparseCustomCallRewritingPass Registration +//===----------------------------------------------------------------------===// + +inline void registerSparseCustomCallRewritingPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSparseCustomCallRewritingPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSparseCustomCallRewritingPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSparseCustomCallRewritingPass(); + }); +} + +//===----------------------------------------------------------------------===// +// CpuTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerCpuTransformsPasses() { + registerConvertXlaCpuMemRefElementCastToLLVMPass(); + registerConvertXlaCpuToCpuRuntimePass(); + registerLegalizeI1VectorTransferOpsPass(); + registerLegalizeLibraryOpsPass(); + registerLegalizeXlaAbiPass(); + registerRemoveCopiesToOutParamsPass(); + registerRewriteReallocToAllocPass(); + registerSparseCustomCallRewritingPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class ConvertXlaCpuMemRefElementCastToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertXlaCpuMemRefElementCastToLLVMPassBase; + + ConvertXlaCpuMemRefElementCastToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertXlaCpuMemRefElementCastToLLVMPassBase(const ConvertXlaCpuMemRefElementCastToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-convert-memref-element-cast-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-convert-memref-element-cast-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Converts xla_cpu.memref_element_cast ops to LLVM."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertXlaCpuMemRefElementCastToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertXlaCpuMemRefElementCastToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertXlaCpuMemRefElementCastToLLVMPassBase) + +protected: +}; + +template +class ConvertXlaCpuToCpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertXlaCpuToCpuRuntimePassBase; + + ConvertXlaCpuToCpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertXlaCpuToCpuRuntimePassBase(const ConvertXlaCpuToCpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-to-cpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-to-cpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts xla_cpu operations to XLA Cpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertXlaCpuToCpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertXlaCpuToCpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertXlaCpuToCpuRuntimePassBase) + +protected: +}; + +template +class LegalizeI1VectorTransferOpsPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeI1VectorTransferOpsPassBase; + + LegalizeI1VectorTransferOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeI1VectorTransferOpsPassBase(const LegalizeI1VectorTransferOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-i1-vector-transfers"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-i1-vector-transfers"; } + + ::llvm::StringRef getDescription() const override { return "Legalizes transfer ops operating on vectors of i1."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeI1VectorTransferOpsPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeI1VectorTransferOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeI1VectorTransferOpsPassBase) + +protected: +}; + +template +class LegalizeLibraryOpsPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeLibraryOpsPassBase; + + LegalizeLibraryOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeLibraryOpsPassBase(const LegalizeLibraryOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-library-ops"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-library-ops"; } + + ::llvm::StringRef getDescription() const override { return "Legalizes ops that map to runtime library calls."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeLibraryOpsPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeLibraryOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeLibraryOpsPassBase) + +protected: +}; + +template +class LegalizeXlaAbiPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeXlaAbiPassBase; + + LegalizeXlaAbiPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeXlaAbiPassBase(const LegalizeXlaAbiPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-abi"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-abi"; } + + ::llvm::StringRef getDescription() const override { return "Converts layouts and data formats at ABI boundaries"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeXlaAbiPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeXlaAbiPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeXlaAbiPassBase) + +protected: +}; + +template +class RemoveCopiesToOutParamsPassBase : public ::mlir::OperationPass { +public: + using Base = RemoveCopiesToOutParamsPassBase; + + RemoveCopiesToOutParamsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RemoveCopiesToOutParamsPassBase(const RemoveCopiesToOutParamsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-remove-copies-to-out-params"); + } + ::llvm::StringRef getArgument() const override { return "xla-remove-copies-to-out-params"; } + + ::llvm::StringRef getDescription() const override { return "Removes redundant alloc/copy pairs to out params."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RemoveCopiesToOutParamsPass"); + } + ::llvm::StringRef getName() const override { return "RemoveCopiesToOutParamsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RemoveCopiesToOutParamsPassBase) + +protected: +}; + +template +class RewriteReallocToAllocPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteReallocToAllocPassBase; + + RewriteReallocToAllocPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteReallocToAllocPassBase(const RewriteReallocToAllocPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rewrite-realloc-to-alloc"); + } + ::llvm::StringRef getArgument() const override { return "xla-rewrite-realloc-to-alloc"; } + + ::llvm::StringRef getDescription() const override { return "Rewrites realloc to alloc + copy"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteReallocToAllocPass"); + } + ::llvm::StringRef getName() const override { return "RewriteReallocToAllocPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteReallocToAllocPassBase) + +protected: +}; + +template +class SparseCustomCallRewritingPassBase : public ::mlir::OperationPass { +public: + using Base = SparseCustomCallRewritingPassBase; + + SparseCustomCallRewritingPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SparseCustomCallRewritingPassBase(const SparseCustomCallRewritingPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-sparse-custom-call-to-pack"); + } + ::llvm::StringRef getArgument() const override { return "xla-sparse-custom-call-to-pack"; } + + ::llvm::StringRef getDescription() const override { return "Converts CustomCall operations to sparse operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SparseCustomCallRewritingPass"); + } + ::llvm::StringRef getName() const override { return "SparseCustomCallRewritingPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SparseCustomCallRewritingPassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/dataflow_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/dataflow_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..033037af1131003f908dff81b011362b2c2396fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/dataflow_analysis.h @@ -0,0 +1,56 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_BACKENDS_GPU_TRANSFORMS_DATAFLOW_ANALYSIS_H_ +#define XLA_MLIR_BACKENDS_GPU_TRANSFORMS_DATAFLOW_ANALYSIS_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project + +namespace xla { +namespace gpu { + +class DataflowAnalysis { + public: + explicit DataflowAnalysis(mlir::Operation* op) {} + + struct Node { + mlir::Operation* operation; + size_t index; + std::vector children; + }; + + using DataflowGraph = std::vector; + + // This function creates a dataflow graph that represent data dependencies in + // the graph capture function. The analysis relies on some properties of the + // IR in XLA: + // (1) Buffer arguments do not alias. It is guaranteed that two buffer + // arguments to the graph capture function do not overlap. + // (2) XLA operations do not have any side effects beyond writing to its + // buffer arguments. So it is safe to reorder operations if they do not + // have write-conflicts. + // (3) We have information about read-only and read-write buffer arguments. + DataflowGraph GetDataflowGraph(mlir::func::FuncOp graph_capture_function); + + std::string ToDot(const DataflowGraph& graph); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_MLIR_BACKENDS_GPU_TRANSFORMS_DATAFLOW_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..4c3fc987ea74b518b7efba234d05ca690f041afa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h @@ -0,0 +1,133 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_BACKENDS_GPU_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_BACKENDS_GPU_TRANSFORMS_PASSES_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +#define GEN_PASS_DECL_ADDHLOTRACEANNOTATIONSPASS +#define GEN_PASS_DECL_CONVERTGPUTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTLMHLOTOGPULAUNCHPASS +#define GEN_PASS_DECL_CONVERTLMHLOTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTMEMREFGETGLOBALTOARGPASS +#define GEN_PASS_DECL_OUTLINEGPUGRAPHSPASS +#define GEN_PASS_DECL_ADDCONCURRENTREGIONSPASS +#define GEN_PASS_DECL_STREAMASSIGNMENTPASS +#include "xla/mlir/backends/gpu/transforms/passes.h.inc" + +class ThunkSequence; // forward declare + +struct GpuPipelineOpts { + // Enable experimental pass that outlines parts of the XLA computation into + // CUDA Graphs, which allows us to amortize the cost of launching multiple + // device kernels. + int32_t gpu_graph_level = 0; + int32_t min_graph_size = 0; + bool enable_concurrent_region = false; + stream_executor::GpuComputeCapability compute_capability; +}; + +// Populate passes that lower MLIR modules from a combination of LMHLO and +// LMHLO_GPU dialects to the XLA Gpu runtime. This pipeline is composed from +// the passes defined below, and few builtin MLIR passes. +void populateXlaGpuRuntimePasses(mlir::OpPassManager& pm, + ThunkSequence* thunk_sequence, + const GpuPipelineOpts& opts = {}); + +//===----------------------------------------------------------------------===// +// Auxiliary passes for lowering to XLA Gpu runtime. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createConvertMemrefGetGlobalToArgPass(); + +std::unique_ptr> +createConvertMemrefGetGlobalToArgPass(int64_t min_num_elements); + +//===-----------------------------------------------------------------------===/ +// Passes for lowering from the `gpu` dialect. +//===-----------------------------------------------------------------------===/ + +std::unique_ptr> +createConvertGpuToGpuRuntimePass(); + +//===----------------------------------------------------------------------===// +// Passes for lowering from the `lmhlo` dialect. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createConvertLmhloToGpuLaunchPass(ThunkSequence* thunk_sequence = nullptr); + +std::unique_ptr> +createConvertLmhloToGpuRuntimePass(); + +//===----------------------------------------------------------------------===// +// Passes for lowering from the `lmhlo_gpu` dialect. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createConvertLmhloGpuToGpuRuntimePass(); + +//===----------------------------------------------------------------------===// +// XLA runtime performance tracing passes. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createAddHloTraceAnnotationsPass(); + +//===----------------------------------------------------------------------===// +// XLA runtime <-> Cuda Graphs integration. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createOutlineGpuGraphsPass(); + +std::unique_ptr> createOutlineGpuGraphsPass( + int32_t gpu_graph_level, int32_t min_graph_size); + +//===----------------------------------------------------------------------===// +// Passes for marking concurrent region in CUDA graph capture function. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createAddConcurrentRegionsPass(); + +//===----------------------------------------------------------------------===// +// Passes for assigning kernels to streams in CUDA graph capture function. +//===----------------------------------------------------------------------===// + +std::unique_ptr> +createStreamAssignmentPass(); + +//===-----------------------------------------------------------------------===/ + +#define GEN_PASS_REGISTRATION +#include "xla/mlir/backends/gpu/transforms/passes.h.inc" + +} // namespace gpu +} // namespace xla + +#endif // XLA_MLIR_BACKENDS_GPU_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..7eabe8c5e637ae8464bd59ce5502662a7ecfe0e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/passes.h.inc @@ -0,0 +1,1134 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ADDCONCURRENTREGIONSPASS +#define GEN_PASS_DECL_ADDHLOTRACEANNOTATIONSPASS +#define GEN_PASS_DECL_CONVERTGPUTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTLMHLOTOGPULAUNCHPASS +#define GEN_PASS_DECL_CONVERTLMHLOTOGPURUNTIMEPASS +#define GEN_PASS_DECL_CONVERTMEMREFGETGLOBALTOARGPASS +#define GEN_PASS_DECL_OUTLINEGPUGRAPHSPASS +#define GEN_PASS_DECL_STREAMASSIGNMENTPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// AddConcurrentRegionsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ADDCONCURRENTREGIONSPASS +#undef GEN_PASS_DECL_ADDCONCURRENTREGIONSPASS +#endif // GEN_PASS_DECL_ADDCONCURRENTREGIONSPASS +#ifdef GEN_PASS_DEF_ADDCONCURRENTREGIONSPASS +namespace impl { + +template +class AddConcurrentRegionsPassBase : public ::mlir::OperationPass { +public: + using Base = AddConcurrentRegionsPassBase; + + AddConcurrentRegionsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddConcurrentRegionsPassBase(const AddConcurrentRegionsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-add-concurrent-regions"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-add-concurrent-regions"; } + + ::llvm::StringRef getDescription() const override { return "Identify and mark concurrent regions in CUDA graph capture functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddConcurrentRegionsPass"); + } + ::llvm::StringRef getName() const override { return "AddConcurrentRegionsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddConcurrentRegionsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ADDCONCURRENTREGIONSPASS +#endif // GEN_PASS_DEF_ADDCONCURRENTREGIONSPASS + +//===----------------------------------------------------------------------===// +// AddHloTraceAnnotationsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ADDHLOTRACEANNOTATIONSPASS +#undef GEN_PASS_DECL_ADDHLOTRACEANNOTATIONSPASS +#endif // GEN_PASS_DECL_ADDHLOTRACEANNOTATIONSPASS +#ifdef GEN_PASS_DEF_ADDHLOTRACEANNOTATIONSPASS +namespace impl { + +template +class AddHloTraceAnnotationsPassBase : public ::mlir::OperationPass { +public: + using Base = AddHloTraceAnnotationsPassBase; + + AddHloTraceAnnotationsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddHloTraceAnnotationsPassBase(const AddHloTraceAnnotationsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-add-hlo-trace-annotations"); + } + ::llvm::StringRef getArgument() const override { return "xla-add-hlo-trace-annotations"; } + + ::llvm::StringRef getDescription() const override { return "Adds HLO trace annotations to the supported operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddHloTraceAnnotationsPass"); + } + ::llvm::StringRef getName() const override { return "AddHloTraceAnnotationsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddHloTraceAnnotationsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ADDHLOTRACEANNOTATIONSPASS +#endif // GEN_PASS_DEF_ADDHLOTRACEANNOTATIONSPASS + +//===----------------------------------------------------------------------===// +// ConvertGpuToGpuRuntimePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTGPUTOGPURUNTIMEPASS +#undef GEN_PASS_DECL_CONVERTGPUTOGPURUNTIMEPASS +#endif // GEN_PASS_DECL_CONVERTGPUTOGPURUNTIMEPASS +#ifdef GEN_PASS_DEF_CONVERTGPUTOGPURUNTIMEPASS +namespace impl { + +template +class ConvertGpuToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuToGpuRuntimePassBase; + + ConvertGpuToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuToGpuRuntimePassBase(const ConvertGpuToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts gpu operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuToGpuRuntimePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTGPUTOGPURUNTIMEPASS +#endif // GEN_PASS_DEF_CONVERTGPUTOGPURUNTIMEPASS + +//===----------------------------------------------------------------------===// +// ConvertLmhloGpuToGpuRuntimePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#undef GEN_PASS_DECL_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#endif // GEN_PASS_DECL_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#ifdef GEN_PASS_DEF_CONVERTLMHLOGPUTOGPURUNTIMEPASS +namespace impl { + +template +class ConvertLmhloGpuToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloGpuToGpuRuntimePassBase; + + ConvertLmhloGpuToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloGpuToGpuRuntimePassBase(const ConvertLmhloGpuToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-gpu-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-gpu-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo_gpu operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloGpuToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloGpuToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloGpuToGpuRuntimePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTLMHLOGPUTOGPURUNTIMEPASS +#endif // GEN_PASS_DEF_CONVERTLMHLOGPUTOGPURUNTIMEPASS + +//===----------------------------------------------------------------------===// +// ConvertLmhloToGpuLaunchPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTLMHLOTOGPULAUNCHPASS +#undef GEN_PASS_DECL_CONVERTLMHLOTOGPULAUNCHPASS +#endif // GEN_PASS_DECL_CONVERTLMHLOTOGPULAUNCHPASS +#ifdef GEN_PASS_DEF_CONVERTLMHLOTOGPULAUNCHPASS +namespace impl { + +template +class ConvertLmhloToGpuLaunchPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloToGpuLaunchPassBase; + + ConvertLmhloToGpuLaunchPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloToGpuLaunchPassBase(const ConvertLmhloToGpuLaunchPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-to-gpu-launch"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-to-gpu-launch"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo fusions to Gpu dialect kernel launch"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloToGpuLaunchPass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloToGpuLaunchPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloToGpuLaunchPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTLMHLOTOGPULAUNCHPASS +#endif // GEN_PASS_DEF_CONVERTLMHLOTOGPULAUNCHPASS + +//===----------------------------------------------------------------------===// +// ConvertLmhloToGpuRuntimePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTLMHLOTOGPURUNTIMEPASS +#undef GEN_PASS_DECL_CONVERTLMHLOTOGPURUNTIMEPASS +#endif // GEN_PASS_DECL_CONVERTLMHLOTOGPURUNTIMEPASS +#ifdef GEN_PASS_DEF_CONVERTLMHLOTOGPURUNTIMEPASS +namespace impl { + +template +class ConvertLmhloToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloToGpuRuntimePassBase; + + ConvertLmhloToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloToGpuRuntimePassBase(const ConvertLmhloToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloToGpuRuntimePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTLMHLOTOGPURUNTIMEPASS +#endif // GEN_PASS_DEF_CONVERTLMHLOTOGPURUNTIMEPASS + +//===----------------------------------------------------------------------===// +// ConvertMemrefGetGlobalToArgPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMEMREFGETGLOBALTOARGPASS +struct ConvertMemrefGetGlobalToArgPassOptions { + int64_t min_num_elements_ = 0; +}; +#undef GEN_PASS_DECL_CONVERTMEMREFGETGLOBALTOARGPASS +#endif // GEN_PASS_DECL_CONVERTMEMREFGETGLOBALTOARGPASS +#ifdef GEN_PASS_DEF_CONVERTMEMREFGETGLOBALTOARGPASS +namespace impl { + +template +class ConvertMemrefGetGlobalToArgPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertMemrefGetGlobalToArgPassBase; + + ConvertMemrefGetGlobalToArgPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMemrefGetGlobalToArgPassBase(const ConvertMemrefGetGlobalToArgPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-memref-get-global-to-arg"); + } + ::llvm::StringRef getArgument() const override { return "xla-memref-get-global-to-arg"; } + + ::llvm::StringRef getDescription() const override { return "Converts memref.get_global corresponding to lmhlo constants"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemrefGetGlobalToArgPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMemrefGetGlobalToArgPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemrefGetGlobalToArgPassBase) + + ConvertMemrefGetGlobalToArgPassBase(const ConvertMemrefGetGlobalToArgPassOptions &options) : ConvertMemrefGetGlobalToArgPassBase() { + min_num_elements_ = options.min_num_elements_; + } +protected: + ::mlir::Pass::Option min_num_elements_{*this, "min-num-elements", ::llvm::cl::desc("Do not convert `memref.get_global` operation if the number of elements is smaller than the given value."), ::llvm::cl::init(0)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTMEMREFGETGLOBALTOARGPASS +#endif // GEN_PASS_DEF_CONVERTMEMREFGETGLOBALTOARGPASS + +//===----------------------------------------------------------------------===// +// OutlineGpuGraphsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_OUTLINEGPUGRAPHSPASS +struct OutlineGpuGraphsPassOptions { + int64_t min_graph_size_ = 2; +}; +#undef GEN_PASS_DECL_OUTLINEGPUGRAPHSPASS +#endif // GEN_PASS_DECL_OUTLINEGPUGRAPHSPASS +#ifdef GEN_PASS_DEF_OUTLINEGPUGRAPHSPASS +namespace impl { + +template +class OutlineGpuGraphsPassBase : public ::mlir::OperationPass { +public: + using Base = OutlineGpuGraphsPassBase; + + OutlineGpuGraphsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OutlineGpuGraphsPassBase(const OutlineGpuGraphsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-outline-gpu-graphs"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-outline-gpu-graphs"; } + + ::llvm::StringRef getDescription() const override { return "Outline sequences of Xla Gpu operations into CUDA Graphs"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OutlineGpuGraphsPass"); + } + ::llvm::StringRef getName() const override { return "OutlineGpuGraphsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OutlineGpuGraphsPassBase) + + OutlineGpuGraphsPassBase(const OutlineGpuGraphsPassOptions &options) : OutlineGpuGraphsPassBase() { + min_graph_size_ = options.min_graph_size_; + } +protected: + ::mlir::Pass::Option min_graph_size_{*this, "min_graph_size", ::llvm::cl::desc("The minimum size of the outlined CUDA graph function."), ::llvm::cl::init(2)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_OUTLINEGPUGRAPHSPASS +#endif // GEN_PASS_DEF_OUTLINEGPUGRAPHSPASS + +//===----------------------------------------------------------------------===// +// StreamAssignmentPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_STREAMASSIGNMENTPASS +#undef GEN_PASS_DECL_STREAMASSIGNMENTPASS +#endif // GEN_PASS_DECL_STREAMASSIGNMENTPASS +#ifdef GEN_PASS_DEF_STREAMASSIGNMENTPASS +namespace impl { + +template +class StreamAssignmentPassBase : public ::mlir::OperationPass { +public: + using Base = StreamAssignmentPassBase; + + StreamAssignmentPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + StreamAssignmentPassBase(const StreamAssignmentPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-stream-assignment"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-stream-assignment"; } + + ::llvm::StringRef getDescription() const override { return "Identify and mark concurrent regions in CUDA graph capture functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("StreamAssignmentPass"); + } + ::llvm::StringRef getName() const override { return "StreamAssignmentPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(StreamAssignmentPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_STREAMASSIGNMENTPASS +#endif // GEN_PASS_DEF_STREAMASSIGNMENTPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// AddConcurrentRegionsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerAddConcurrentRegionsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createAddConcurrentRegionsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAddConcurrentRegionsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createAddConcurrentRegionsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// AddHloTraceAnnotationsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerAddHloTraceAnnotationsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createAddHloTraceAnnotationsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAddHloTraceAnnotationsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createAddHloTraceAnnotationsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertGpuToGpuRuntimePass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertGpuToGpuRuntimePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuToGpuRuntimePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertGpuToGpuRuntimePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuToGpuRuntimePass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertLmhloGpuToGpuRuntimePass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertLmhloGpuToGpuRuntimePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloGpuToGpuRuntimePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertLmhloGpuToGpuRuntimePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloGpuToGpuRuntimePass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertLmhloToGpuLaunchPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertLmhloToGpuLaunchPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloToGpuLaunchPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertLmhloToGpuLaunchPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloToGpuLaunchPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertLmhloToGpuRuntimePass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertLmhloToGpuRuntimePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloToGpuRuntimePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertLmhloToGpuRuntimePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLmhloToGpuRuntimePass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMemrefGetGlobalToArgPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMemrefGetGlobalToArgPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemrefGetGlobalToArgPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMemrefGetGlobalToArgPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemrefGetGlobalToArgPass(); + }); +} + +//===----------------------------------------------------------------------===// +// OutlineGpuGraphsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerOutlineGpuGraphsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createOutlineGpuGraphsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerOutlineGpuGraphsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createOutlineGpuGraphsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// StreamAssignmentPass Registration +//===----------------------------------------------------------------------===// + +inline void registerStreamAssignmentPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createStreamAssignmentPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerStreamAssignmentPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createStreamAssignmentPass(); + }); +} + +//===----------------------------------------------------------------------===// +// GpuTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerGpuTransformsPasses() { + registerAddConcurrentRegionsPass(); + registerAddHloTraceAnnotationsPass(); + registerConvertGpuToGpuRuntimePass(); + registerConvertLmhloGpuToGpuRuntimePass(); + registerConvertLmhloToGpuLaunchPass(); + registerConvertLmhloToGpuRuntimePass(); + registerConvertMemrefGetGlobalToArgPass(); + registerOutlineGpuGraphsPass(); + registerStreamAssignmentPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class AddConcurrentRegionsPassBase : public ::mlir::OperationPass { +public: + using Base = AddConcurrentRegionsPassBase; + + AddConcurrentRegionsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddConcurrentRegionsPassBase(const AddConcurrentRegionsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-add-concurrent-regions"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-add-concurrent-regions"; } + + ::llvm::StringRef getDescription() const override { return "Identify and mark concurrent regions in CUDA graph capture functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddConcurrentRegionsPass"); + } + ::llvm::StringRef getName() const override { return "AddConcurrentRegionsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddConcurrentRegionsPassBase) + +protected: +}; + +template +class AddHloTraceAnnotationsPassBase : public ::mlir::OperationPass { +public: + using Base = AddHloTraceAnnotationsPassBase; + + AddHloTraceAnnotationsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddHloTraceAnnotationsPassBase(const AddHloTraceAnnotationsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-add-hlo-trace-annotations"); + } + ::llvm::StringRef getArgument() const override { return "xla-add-hlo-trace-annotations"; } + + ::llvm::StringRef getDescription() const override { return "Adds HLO trace annotations to the supported operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddHloTraceAnnotationsPass"); + } + ::llvm::StringRef getName() const override { return "AddHloTraceAnnotationsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddHloTraceAnnotationsPassBase) + +protected: +}; + +template +class ConvertGpuToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuToGpuRuntimePassBase; + + ConvertGpuToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuToGpuRuntimePassBase(const ConvertGpuToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts gpu operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuToGpuRuntimePassBase) + +protected: +}; + +template +class ConvertLmhloGpuToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloGpuToGpuRuntimePassBase; + + ConvertLmhloGpuToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloGpuToGpuRuntimePassBase(const ConvertLmhloGpuToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-gpu-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-gpu-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo_gpu operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloGpuToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloGpuToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloGpuToGpuRuntimePassBase) + +protected: +}; + +template +class ConvertLmhloToGpuLaunchPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloToGpuLaunchPassBase; + + ConvertLmhloToGpuLaunchPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloToGpuLaunchPassBase(const ConvertLmhloToGpuLaunchPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-to-gpu-launch"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-to-gpu-launch"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo fusions to Gpu dialect kernel launch"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloToGpuLaunchPass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloToGpuLaunchPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloToGpuLaunchPassBase) + +protected: +}; + +template +class ConvertLmhloToGpuRuntimePassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLmhloToGpuRuntimePassBase; + + ConvertLmhloToGpuRuntimePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLmhloToGpuRuntimePassBase(const ConvertLmhloToGpuRuntimePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-lmhlo-to-gpu-runtime"); + } + ::llvm::StringRef getArgument() const override { return "xla-lmhlo-to-gpu-runtime"; } + + ::llvm::StringRef getDescription() const override { return "Converts lmhlo operations to XLA Gpu runtime custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLmhloToGpuRuntimePass"); + } + ::llvm::StringRef getName() const override { return "ConvertLmhloToGpuRuntimePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLmhloToGpuRuntimePassBase) + +protected: +}; + +template +class ConvertMemrefGetGlobalToArgPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertMemrefGetGlobalToArgPassBase; + + ConvertMemrefGetGlobalToArgPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMemrefGetGlobalToArgPassBase(const ConvertMemrefGetGlobalToArgPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-memref-get-global-to-arg"); + } + ::llvm::StringRef getArgument() const override { return "xla-memref-get-global-to-arg"; } + + ::llvm::StringRef getDescription() const override { return "Converts memref.get_global corresponding to lmhlo constants"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemrefGetGlobalToArgPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMemrefGetGlobalToArgPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemrefGetGlobalToArgPassBase) + +protected: + ::mlir::Pass::Option min_num_elements_{*this, "min-num-elements", ::llvm::cl::desc("Do not convert `memref.get_global` operation if the number of elements is smaller than the given value."), ::llvm::cl::init(0)}; +}; + +template +class OutlineGpuGraphsPassBase : public ::mlir::OperationPass { +public: + using Base = OutlineGpuGraphsPassBase; + + OutlineGpuGraphsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OutlineGpuGraphsPassBase(const OutlineGpuGraphsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-outline-gpu-graphs"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-outline-gpu-graphs"; } + + ::llvm::StringRef getDescription() const override { return "Outline sequences of Xla Gpu operations into CUDA Graphs"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OutlineGpuGraphsPass"); + } + ::llvm::StringRef getName() const override { return "OutlineGpuGraphsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OutlineGpuGraphsPassBase) + +protected: + ::mlir::Pass::Option min_graph_size_{*this, "min_graph_size", ::llvm::cl::desc("The minimum size of the outlined CUDA graph function."), ::llvm::cl::init(2)}; +}; + +template +class StreamAssignmentPassBase : public ::mlir::OperationPass { +public: + using Base = StreamAssignmentPassBase; + + StreamAssignmentPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + StreamAssignmentPassBase(const StreamAssignmentPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-gpu-stream-assignment"); + } + ::llvm::StringRef getArgument() const override { return "xla-gpu-stream-assignment"; } + + ::llvm::StringRef getDescription() const override { return "Identify and mark concurrent regions in CUDA graph capture functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("StreamAssignmentPass"); + } + ::llvm::StringRef getName() const override { return "StreamAssignmentPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(StreamAssignmentPassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/uid_generator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/uid_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..1a89d184ac04a68f33591459af6719e0ae1f0632 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu/transforms/uid_generator.h @@ -0,0 +1,42 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_BACKENDS_GPU_TRANSFORMS_UID_GENERATOR_H_ +#define XLA_MLIR_BACKENDS_GPU_TRANSFORMS_UID_GENERATOR_H_ + +#include + +namespace xla { +namespace gpu { + +// Every stateful operation in the module gets assigned a unique id, that is +// passed to the custom call handler. This id is used for caching resources +// between the different invocations of the same custom call (e.g. cache +// convolution descriptors). +// +// TODO(b/255600288): Improve stateful custom calls in Xla runtime. +class UidGenerator { + public: + UidGenerator() : uid_(0) {} + int64_t uid() { return uid_.fetch_add(1); } + + private: + std::atomic uid_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_MLIR_BACKENDS_GPU_TRANSFORMS_UID_GENERATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu2/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu2/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..fc44bc29e253f687a3bf40eee8d7cf362a78e749 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/backends/gpu2/transforms/passes.h @@ -0,0 +1,78 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_BACKENDS_GPU2_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_BACKENDS_GPU2_TRANSFORMS_PASSES_H_ + +namespace xla::gpu { + +class ThunkSequence; // forward declare + +struct Gpu2PipelineOpts {}; + +} // namespace xla::gpu + +//===----------------------------------------------------------------------===// +// TODO(ezhulenev): We currently do not build with XLA:GPU experimental runtime +// in open source because we do not have bazel dependency from XLA to IREE. +#if XLA_DISABLE_GPU2_COMPILER +//===----------------------------------------------------------------------===// + +namespace mlir { +class OpPassManager; +} // namespace mlir + +namespace xla::gpu { +inline void populateGpu2RuntimePasses(mlir::OpPassManager&, ThunkSequence*, + const Gpu2PipelineOpts& opts) {} +inline void registerGpu2Pases() {} +} // namespace xla::gpu + +//===----------------------------------------------------------------------===// +#else // !XLA_DISABLE_GPU2_COMPILER +//===----------------------------------------------------------------------===// + +#include +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +namespace xla::gpu { + +// Populate passes that lower MLIR modules from a combination of LMHLO and +// LMHLO_GPU dialects to the XLA:GPU runtime (aka IREE input dialects + XLA:GPU +// custom calls implementing library integration). +void populateGpu2RuntimePasses(mlir::OpPassManager& pm, + ThunkSequence* thunk_sequence, + const Gpu2PipelineOpts& opts); + +//===----------------------------------------------------------------------===// +// Conversion from LMHLO dialects to XLA:GPU runtime +//===----------------------------------------------------------------------===// + +std::unique_ptr > +createConvertToGpu2RuntimePass(ThunkSequence* thunk_sequence = nullptr); + +//===----------------------------------------------------------------------===// +// XLA:GPU passes registration +//===----------------------------------------------------------------------===// + +void registerGpu2Pases(); + +} // namespace xla::gpu + +#endif // !XLA_DISABLE_GPU2_RUNTIME +#endif // XLA_MLIR_BACKENDS_GPU2_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h new file mode 100644 index 0000000000000000000000000000000000000000..690fb63e84062c0ea336f177f6aeda4eb774e208 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h @@ -0,0 +1,36 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the operations and types used in the XLAFramework dialect. +// +#ifndef XLA_MLIR_FRAMEWORK_IR_XLA_FRAMEWORK_H_ +#define XLA_MLIR_FRAMEWORK_IR_XLA_FRAMEWORK_H_ + +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Dialect.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/OpImplementation.h" // from @llvm-project + +#define GET_TYPEDEF_CLASSES +#include "xla/mlir/framework/ir/xla_framework_types.h.inc" +#define GET_OP_CLASSES +#include "xla/mlir/framework/ir/xla_framework.h.inc" +#include "xla/mlir/framework/ir/xla_framework_dialect.h.inc" + +#undef GET_OP_CLASSES + +#endif // XLA_MLIR_FRAMEWORK_IR_XLA_FRAMEWORK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..b40f0ca5663e83692dd48c258dc0884f517e37b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework.h.inc @@ -0,0 +1,234 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: xla_framework_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace xla_framework { +class MemToXLABufferOp; +} // namespace xla_framework +} // namespace mlir +namespace mlir { +namespace xla_framework { +class XLABufferToMemOp; +} // namespace xla_framework +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace xla_framework { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_framework::MemToXLABufferOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MemToXLABufferOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MemToXLABufferOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MemToXLABufferOpGenericAdaptorBase(MemToXLABufferOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class MemToXLABufferOpGenericAdaptor : public detail::MemToXLABufferOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MemToXLABufferOpGenericAdaptorBase; +public: + MemToXLABufferOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MemToXLABufferOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MemToXLABufferOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MemToXLABufferOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMemref() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MemToXLABufferOpAdaptor : public MemToXLABufferOpGenericAdaptor<::mlir::ValueRange> { +public: + using MemToXLABufferOpGenericAdaptor::MemToXLABufferOpGenericAdaptor; + MemToXLABufferOpAdaptor(MemToXLABufferOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MemToXLABufferOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants> { +public: + using Op::Op; + using Op::print; + using Adaptor = MemToXLABufferOpAdaptor; + template + using GenericAdaptor = MemToXLABufferOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_framework.mem_to_buffer"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::BaseMemRefType> getMemref(); + ::mlir::OpOperand &getMemrefMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::xla_framework::BufferType> getBuffer(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type buffer, ::mlir::Value memref); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value memref); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: +}; +} // namespace xla_framework +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_framework::MemToXLABufferOp) + +namespace mlir { +namespace xla_framework { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_framework::XLABufferToMemOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class XLABufferToMemOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + XLABufferToMemOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + XLABufferToMemOpGenericAdaptorBase(XLABufferToMemOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class XLABufferToMemOpGenericAdaptor : public detail::XLABufferToMemOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::XLABufferToMemOpGenericAdaptorBase; +public: + XLABufferToMemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + XLABufferToMemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : XLABufferToMemOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + XLABufferToMemOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBuffer() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class XLABufferToMemOpAdaptor : public XLABufferToMemOpGenericAdaptor<::mlir::ValueRange> { +public: + using XLABufferToMemOpGenericAdaptor::XLABufferToMemOpGenericAdaptor; + XLABufferToMemOpAdaptor(XLABufferToMemOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class XLABufferToMemOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants> { +public: + using Op::Op; + using Op::print; + using Adaptor = XLABufferToMemOpAdaptor; + template + using GenericAdaptor = XLABufferToMemOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_framework.buffer_to_mem"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::xla_framework::BufferType> getBuffer(); + ::mlir::OpOperand &getBufferMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::BaseMemRefType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, MemRefType memref_type, Value buffer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value buffer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value buffer); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: + MemRefType getType() { return getResult().getType().cast(); } +}; +} // namespace xla_framework +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_framework::XLABufferToMemOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..c11ca16d979585c076bc5ef3311d0963f5839b6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_dialect.h.inc @@ -0,0 +1,37 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: xla_framework_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace xla_framework { + +class XLAFrameworkDialect : public ::mlir::Dialect { + explicit XLAFrameworkDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~XLAFrameworkDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("xla_framework"); + } + + /// Parse a type registered to this dialect. + ::mlir::Type parseType(::mlir::DialectAsmParser &parser) const override; + + /// Print a type registered to this dialect. + void printType(::mlir::Type type, + ::mlir::DialectAsmPrinter &os) const override; + + // The attribute string tied to entry point functions honoring XLA's calling + // convention. + static constexpr StringRef kXLAEntryAttrName = "xla_entry"; + }; +} // namespace xla_framework +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_framework::XLAFrameworkDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_types.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_types.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..1b2b973e9116003fb3fb3526835518b5c06920db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/ir/xla_framework_types.h.inc @@ -0,0 +1,33 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* TypeDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_TYPEDEF_CLASSES +#undef GET_TYPEDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace xla_framework { +class BufferType; +class BufferType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"buffer"}; + } + +}; +} // namespace xla_framework +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_framework::BufferType) + +#endif // GET_TYPEDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..cb11e9e96deb938d9d7b3a057b0e073141aa3daa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h @@ -0,0 +1,49 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_FRAMEWORK_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_FRAMEWORK_TRANSFORMS_PASSES_H_ + +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project + +namespace mlir { + +namespace func { +class FuncOp; +} // namespace func +template +class OperationPass; + +namespace xla_framework { + +// Wrap function with XLA:CPU's C interface. +std::unique_ptr> CreateOutlineWithXLAFrameworkPass(); + +// Convert XLAFramework operations to LLVM operations. +std::unique_ptr> CreateLegalizeXLAFrameworkToLLVMPass(); + +#define GEN_PASS_REGISTRATION +#define GEN_PASS_DECL_LEGALIZEXLAFRAMEWORKTOLLVM +#define GEN_PASS_DECL_OUTLINEWITHXLAFRAMEWORK +#include "xla/mlir/framework/transforms/passes.h.inc" + +} // namespace xla_framework +} // namespace mlir + +#endif // XLA_MLIR_FRAMEWORK_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..2112e8133fb5085ba9310785fa97d8a9742e9370 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/framework/transforms/passes.h.inc @@ -0,0 +1,272 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_LEGALIZEXLAFRAMEWORKTOLLVM +#define GEN_PASS_DECL_OUTLINEWITHXLAFRAMEWORK +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// LegalizeXLAFrameworkToLLVM +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LEGALIZEXLAFRAMEWORKTOLLVM +#undef GEN_PASS_DECL_LEGALIZEXLAFRAMEWORKTOLLVM +#endif // GEN_PASS_DECL_LEGALIZEXLAFRAMEWORKTOLLVM +#ifdef GEN_PASS_DEF_LEGALIZEXLAFRAMEWORKTOLLVM +namespace impl { + +template +class LegalizeXLAFrameworkToLLVMBase : public ::mlir::OperationPass { +public: + using Base = LegalizeXLAFrameworkToLLVMBase; + + LegalizeXLAFrameworkToLLVMBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeXLAFrameworkToLLVMBase(const LegalizeXLAFrameworkToLLVMBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-xla-framework-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-xla-framework-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Legalize XLAFramework to bare pointers and LLVM memref descriptors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeXLAFrameworkToLLVM"); + } + ::llvm::StringRef getName() const override { return "LegalizeXLAFrameworkToLLVM"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeXLAFrameworkToLLVMBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LEGALIZEXLAFRAMEWORKTOLLVM +#endif // GEN_PASS_DEF_LEGALIZEXLAFRAMEWORKTOLLVM + +//===----------------------------------------------------------------------===// +// OutlineWithXLAFramework +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_OUTLINEWITHXLAFRAMEWORK +#undef GEN_PASS_DECL_OUTLINEWITHXLAFRAMEWORK +#endif // GEN_PASS_DECL_OUTLINEWITHXLAFRAMEWORK +#ifdef GEN_PASS_DEF_OUTLINEWITHXLAFRAMEWORK +namespace impl { + +template +class OutlineWithXLAFrameworkBase : public ::mlir::OperationPass { +public: + using Base = OutlineWithXLAFrameworkBase; + + OutlineWithXLAFrameworkBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OutlineWithXLAFrameworkBase(const OutlineWithXLAFrameworkBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("outline-with-xla-framework"); + } + ::llvm::StringRef getArgument() const override { return "outline-with-xla-framework"; } + + ::llvm::StringRef getDescription() const override { return "Create XLAFramework based wrapper function to match XLA:CPU's interface"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OutlineWithXLAFramework"); + } + ::llvm::StringRef getName() const override { return "OutlineWithXLAFramework"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::xla_framework::XLAFrameworkDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OutlineWithXLAFrameworkBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_OUTLINEWITHXLAFRAMEWORK +#endif // GEN_PASS_DEF_OUTLINEWITHXLAFRAMEWORK +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// LegalizeXLAFrameworkToLLVM Registration +//===----------------------------------------------------------------------===// + +inline void registerLegalizeXLAFrameworkToLLVM() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::xla_framework::CreateLegalizeXLAFrameworkToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLegalizeXLAFrameworkToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::xla_framework::CreateLegalizeXLAFrameworkToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// OutlineWithXLAFramework Registration +//===----------------------------------------------------------------------===// + +inline void registerOutlineWithXLAFramework() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::xla_framework::CreateOutlineWithXLAFrameworkPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerOutlineWithXLAFrameworkPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::xla_framework::CreateOutlineWithXLAFrameworkPass(); + }); +} + +//===----------------------------------------------------------------------===// +// XlaFramework Registration +//===----------------------------------------------------------------------===// + +inline void registerXlaFrameworkPasses() { + registerLegalizeXLAFrameworkToLLVM(); + registerOutlineWithXLAFramework(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class LegalizeXLAFrameworkToLLVMBase : public ::mlir::OperationPass { +public: + using Base = LegalizeXLAFrameworkToLLVMBase; + + LegalizeXLAFrameworkToLLVMBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeXLAFrameworkToLLVMBase(const LegalizeXLAFrameworkToLLVMBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-legalize-xla-framework-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-legalize-xla-framework-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Legalize XLAFramework to bare pointers and LLVM memref descriptors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeXLAFrameworkToLLVM"); + } + ::llvm::StringRef getName() const override { return "LegalizeXLAFrameworkToLLVM"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeXLAFrameworkToLLVMBase) + +protected: +}; + +template +class OutlineWithXLAFrameworkBase : public ::mlir::OperationPass { +public: + using Base = OutlineWithXLAFrameworkBase; + + OutlineWithXLAFrameworkBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OutlineWithXLAFrameworkBase(const OutlineWithXLAFrameworkBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("outline-with-xla-framework"); + } + ::llvm::StringRef getArgument() const override { return "outline-with-xla-framework"; } + + ::llvm::StringRef getDescription() const override { return "Create XLAFramework based wrapper function to match XLA:CPU's interface"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OutlineWithXLAFramework"); + } + ::llvm::StringRef getName() const override { return "OutlineWithXLAFramework"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::xla_framework::XLAFrameworkDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OutlineWithXLAFrameworkBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..512f3eec1577c696b2dc40be75ee2b28c161111b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h @@ -0,0 +1,43 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_MATH_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_MATH_TRANSFORMS_PASSES_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +namespace xla { + +#define GEN_PASS_DECL_MATHAPPROXIMATIONPASS +#define GEN_PASS_DECL_MATHOPTIMIZATIONPASS +#include "xla/mlir/math/transforms/passes.h.inc" + +std::unique_ptr> +CreateMathOptimizationPass(bool enable_avx2 = false); + +std::unique_ptr> +CreateMathApproximationPass(llvm::ArrayRef oplist = {}); + +#define GEN_PASS_REGISTRATION +#include "xla/mlir/math/transforms/passes.h.inc" + +} // namespace xla + +#endif // XLA_MLIR_MATH_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..3b12dc70934fa7795c06b386576ea0ceb7a7c959 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/math/transforms/passes.h.inc @@ -0,0 +1,288 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_MATHAPPROXIMATIONPASS +#define GEN_PASS_DECL_MATHOPTIMIZATIONPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// MathApproximationPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_MATHAPPROXIMATIONPASS +struct MathApproximationPassOptions { + ::llvm::ArrayRef oplist; +}; +#undef GEN_PASS_DECL_MATHAPPROXIMATIONPASS +#endif // GEN_PASS_DECL_MATHAPPROXIMATIONPASS +#ifdef GEN_PASS_DEF_MATHAPPROXIMATIONPASS +namespace impl { + +template +class MathApproximationPassBase : public ::mlir::OperationPass { +public: + using Base = MathApproximationPassBase; + + MathApproximationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + MathApproximationPassBase(const MathApproximationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-math-approximation"); + } + ::llvm::StringRef getArgument() const override { return "xla-math-approximation"; } + + ::llvm::StringRef getDescription() const override { return "Approximate math operations for accuracy and speed."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MathApproximationPass"); + } + ::llvm::StringRef getName() const override { return "MathApproximationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MathApproximationPassBase) + + MathApproximationPassBase(const MathApproximationPassOptions &options) : MathApproximationPassBase() { + oplist = options.oplist; + } +protected: + ::mlir::Pass::ListOption oplist{*this, "oplist", ::llvm::cl::desc("List of math operations to be approximated. Use 'all' to select all supported math operations.")}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_MATHAPPROXIMATIONPASS +#endif // GEN_PASS_DEF_MATHAPPROXIMATIONPASS + +//===----------------------------------------------------------------------===// +// MathOptimizationPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_MATHOPTIMIZATIONPASS +struct MathOptimizationPassOptions { + bool enable_avx2_ = false; +}; +#undef GEN_PASS_DECL_MATHOPTIMIZATIONPASS +#endif // GEN_PASS_DECL_MATHOPTIMIZATIONPASS +#ifdef GEN_PASS_DEF_MATHOPTIMIZATIONPASS +namespace impl { + +template +class MathOptimizationPassBase : public ::mlir::OperationPass { +public: + using Base = MathOptimizationPassBase; + + MathOptimizationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + MathOptimizationPassBase(const MathOptimizationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-math-optimization"); + } + ::llvm::StringRef getArgument() const override { return "xla-math-optimization"; } + + ::llvm::StringRef getDescription() const override { return "Optimize operations from the `math` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MathOptimizationPass"); + } + ::llvm::StringRef getName() const override { return "MathOptimizationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MathOptimizationPassBase) + + MathOptimizationPassBase(const MathOptimizationPassOptions &options) : MathOptimizationPassBase() { + enable_avx2_ = options.enable_avx2_; + } +protected: + ::mlir::Pass::Option enable_avx2_{*this, "enable-avx2", ::llvm::cl::desc("Enable math approximations that emit AVX2 intrinsics."), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_MATHOPTIMIZATIONPASS +#endif // GEN_PASS_DEF_MATHOPTIMIZATIONPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// MathApproximationPass Registration +//===----------------------------------------------------------------------===// + +inline void registerMathApproximationPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateMathApproximationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerMathApproximationPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateMathApproximationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// MathOptimizationPass Registration +//===----------------------------------------------------------------------===// + +inline void registerMathOptimizationPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateMathOptimizationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerMathOptimizationPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateMathOptimizationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// MathTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerMathTransformsPasses() { + registerMathApproximationPass(); + registerMathOptimizationPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class MathApproximationPassBase : public ::mlir::OperationPass { +public: + using Base = MathApproximationPassBase; + + MathApproximationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + MathApproximationPassBase(const MathApproximationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-math-approximation"); + } + ::llvm::StringRef getArgument() const override { return "xla-math-approximation"; } + + ::llvm::StringRef getDescription() const override { return "Approximate math operations for accuracy and speed."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MathApproximationPass"); + } + ::llvm::StringRef getName() const override { return "MathApproximationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MathApproximationPassBase) + +protected: + ::mlir::Pass::ListOption oplist{*this, "oplist", ::llvm::cl::desc("List of math operations to be approximated. Use 'all' to select all supported math operations.")}; +}; + +template +class MathOptimizationPassBase : public ::mlir::OperationPass { +public: + using Base = MathOptimizationPassBase; + + MathOptimizationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + MathOptimizationPassBase(const MathOptimizationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-math-optimization"); + } + ::llvm::StringRef getArgument() const override { return "xla-math-optimization"; } + + ::llvm::StringRef getDescription() const override { return "Optimize operations from the `math` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MathOptimizationPass"); + } + ::llvm::StringRef getName() const override { return "MathOptimizationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MathOptimizationPassBase) + +protected: + ::mlir::Pass::Option enable_avx2_{*this, "enable-avx2", ::llvm::cl::desc("Enable math approximations that emit AVX2 intrinsics."), ::llvm::cl::init(false)}; +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..da79f1c16400f309cfd2d195e720fe11a3d89b58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h @@ -0,0 +1,37 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_MEMREF_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_MEMREF_TRANSFORMS_PASSES_H_ + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +namespace xla { + +#define GEN_PASS_DECL_ALIGNEDALLOCATIONSPASS +#include "xla/mlir/memref/transforms/passes.h.inc" + +std::unique_ptr> +CreateAlignedAllocationsPass(int64_t alignment = 64); + +#define GEN_PASS_REGISTRATION +#include "xla/mlir/memref/transforms/passes.h.inc" + +} // namespace xla + +#endif // XLA_MLIR_MEMREF_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..e67b7b63485928a91462d4128a8050625014808b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/memref/transforms/passes.h.inc @@ -0,0 +1,150 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ALIGNEDALLOCATIONSPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// AlignedAllocationsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ALIGNEDALLOCATIONSPASS +struct AlignedAllocationsPassOptions { + int64_t alignment_ = 64; +}; +#undef GEN_PASS_DECL_ALIGNEDALLOCATIONSPASS +#endif // GEN_PASS_DECL_ALIGNEDALLOCATIONSPASS +#ifdef GEN_PASS_DEF_ALIGNEDALLOCATIONSPASS +namespace impl { + +template +class AlignedAllocationsPassBase : public ::mlir::OperationPass { +public: + using Base = AlignedAllocationsPassBase; + + AlignedAllocationsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AlignedAllocationsPassBase(const AlignedAllocationsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-memref-aligned-allocations"); + } + ::llvm::StringRef getArgument() const override { return "xla-memref-aligned-allocations"; } + + ::llvm::StringRef getDescription() const override { return "Add alignment attribute to all `alloc` operations."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AlignedAllocationsPass"); + } + ::llvm::StringRef getName() const override { return "AlignedAllocationsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AlignedAllocationsPassBase) + + AlignedAllocationsPassBase(const AlignedAllocationsPassOptions &options) : AlignedAllocationsPassBase() { + alignment_ = options.alignment_; + } +protected: + ::mlir::Pass::Option alignment_{*this, "alignment", ::llvm::cl::desc("Byte alignment for allocated memrefs."), ::llvm::cl::init(64)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ALIGNEDALLOCATIONSPASS +#endif // GEN_PASS_DEF_ALIGNEDALLOCATIONSPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// AlignedAllocationsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerAlignedAllocationsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateAlignedAllocationsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAlignedAllocationsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::CreateAlignedAllocationsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// MemrefTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerMemrefTransformsPasses() { + registerAlignedAllocationsPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class AlignedAllocationsPassBase : public ::mlir::OperationPass { +public: + using Base = AlignedAllocationsPassBase; + + AlignedAllocationsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AlignedAllocationsPassBase(const AlignedAllocationsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-memref-aligned-allocations"); + } + ::llvm::StringRef getArgument() const override { return "xla-memref-aligned-allocations"; } + + ::llvm::StringRef getDescription() const override { return "Add alignment attribute to all `alloc` operations."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AlignedAllocationsPass"); + } + ::llvm::StringRef getName() const override { return "AlignedAllocationsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AlignedAllocationsPassBase) + +protected: + ::mlir::Pass::Option alignment_{*this, "alignment", ::llvm::cl::desc("Byte alignment for allocated memrefs."), ::llvm::cl::init(64)}; +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attr_interfaces.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attr_interfaces.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..144c1394f1f2a5d87762ef1887c7d2764aa3afbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attr_interfaces.h.inc @@ -0,0 +1,56 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace xla { +namespace runtime { +class TraceAnnotationAttrInterface; +namespace detail { +struct TraceAnnotationAttrInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + }; + template + class Model : public Concept { + public: + using Interface = xla::runtime::TraceAnnotationAttrInterface; + Model() : Concept{} {} + + }; + template + class FallbackModel : public Concept { + public: + using Interface = xla::runtime::TraceAnnotationAttrInterface; + FallbackModel() : Concept{} {} + + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteAttr; + }; +};template +struct TraceAnnotationAttrInterfaceTrait; + +} // namespace detail +class TraceAnnotationAttrInterface : public ::mlir::AttributeInterface { +public: + using ::mlir::AttributeInterface::AttributeInterface; + template + struct Trait : public detail::TraceAnnotationAttrInterfaceTrait {}; +}; +namespace detail { + template + struct TraceAnnotationAttrInterfaceTrait : public ::mlir::AttributeInterface::Trait { + }; +}// namespace detail +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +} // namespace runtime +} // namespace xla diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attrs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attrs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..17608519265acd7c8bc6d31249e9de3d2960e817 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_attrs.h.inc @@ -0,0 +1,40 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace xla { +namespace runtime { +class HloTraceAttr; +namespace detail { +struct HloTraceAttrStorage; +} // namespace detail +class HloTraceAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static HloTraceAttr get(::mlir::MLIRContext *context, ::llvm::StringRef hlo_op); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"hlo_trace"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::StringRef getHloOp() const; +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::HloTraceAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h new file mode 100644 index 0000000000000000000000000000000000000000..5a690aacba7ac868da43902dfc0bf0f52b623c24 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h @@ -0,0 +1,43 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_IR_RT_DIALECT_H_ +#define XLA_MLIR_RUNTIME_IR_RT_DIALECT_H_ + +#include "mlir/IR/Dialect.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/IR/OpImplementation.h" // from @llvm-project // IWYU pragma: keep +#include "xla/mlir/runtime/ir/rt_interfaces.h" // IWYU pragma: keep + +// Runtime dialect definition. +#include "xla/mlir/runtime/ir/rt_dialect.h.inc" + +#define GET_TYPEDEF_CLASSES +#include "xla/mlir/runtime/ir/rt_types.h.inc" + +#define GET_ATTRDEF_CLASSES +#include "xla/mlir/runtime/ir/rt_attrs.h.inc" + +namespace xla { +namespace runtime { + +// Attribute name for marking functions exported to runtime. +static constexpr char const* kExportedAttrName = "rt.exported"; + +static constexpr char const* kRequiresBlasAttrName = "rt.requires_blas"; + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_IR_RT_DIALECT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..180cc10dcd00b449e5d4fb9f9e6576f88beec098 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_dialect.h.inc @@ -0,0 +1,46 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: rt_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace xla { +namespace runtime { + +class RuntimeDialect : public ::mlir::Dialect { + explicit RuntimeDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~RuntimeDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("rt"); + } + + /// Parse an attribute registered to this dialect. + ::mlir::Attribute parseAttribute(::mlir::DialectAsmParser &parser, + ::mlir::Type type) const override; + + /// Print an attribute registered to this dialect. + void printAttribute(::mlir::Attribute attr, + ::mlir::DialectAsmPrinter &os) const override; + + /// Parse a type registered to this dialect. + ::mlir::Type parseType(::mlir::DialectAsmParser &parser) const override; + + /// Print a type registered to this dialect. + void printType(::mlir::Type type, + ::mlir::DialectAsmPrinter &os) const override; + + /// Provides a hook for verifying dialect attributes attached to the given + /// op. + ::mlir::LogicalResult verifyOperationAttribute( + ::mlir::Operation *op, ::mlir::NamedAttribute attribute) override; +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::RuntimeDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_interfaces.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_interfaces.h new file mode 100644 index 0000000000000000000000000000000000000000..8b310a6f6bc97f55656bb5ed400b16e31ec6d03c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_interfaces.h @@ -0,0 +1,24 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_IR_RT_INTERFACES_H_ +#define XLA_MLIR_RUNTIME_IR_RT_INTERFACES_H_ + +#include "mlir/IR/Attributes.h" // from @llvm-project // IWYU pragma: keep + +#define GET_ATTR_INTERFACE_CLASSES +#include "xla/mlir/runtime/ir/rt_attr_interfaces.h.inc" + +#endif // XLA_MLIR_RUNTIME_IR_RT_INTERFACES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d15d5c5e15e1020c4c73b7ff814a4965a18248d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h @@ -0,0 +1,30 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_IR_RT_OPS_H_ +#define XLA_MLIR_RUNTIME_IR_RT_OPS_H_ + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/IR/BuiltinOps.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/IR/SymbolTable.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/Interfaces/ControlFlowInterfaces.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project // IWYU pragma: keep +#include "xla/mlir/runtime/ir/rt_dialect.h" // IWYU pragma: keep +#include "xla/mlir/runtime/ir/rt_interfaces.h" // IWYU pragma: keep + +#define GET_OP_CLASSES +#include "xla/mlir/runtime/ir/rt_ops.h.inc" + +#endif // XLA_MLIR_RUNTIME_IR_RT_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..aee835c6e2ba0d6ed8fffd127ee1db53eea55b70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_ops.h.inc @@ -0,0 +1,1229 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: rt_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace xla { +namespace runtime { +class CallOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class ExportOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class IsOkOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class SetErrorOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class SetOutputOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class TraceOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class UnsignedCastOp; +} // namespace runtime +} // namespace xla +namespace xla { +namespace runtime { +class YieldOp; +} // namespace runtime +} // namespace xla +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::CallOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CallOpGenericAdaptorBase { +public: + struct Properties { + using calleeTy = ::mlir::StringAttr; + calleeTy callee; + + auto getCallee() { + auto &propStorage = this->callee; + return ::llvm::cast<::mlir::StringAttr>(propStorage); + } + void setCallee(const ::mlir::StringAttr &propValue) { + this->callee = propValue; + } + using dynamicTy = ::mlir::UnitAttr; + dynamicTy dynamic; + + auto getDynamic() { + auto &propStorage = this->dynamic; + return ::llvm::dyn_cast_or_null<::mlir::UnitAttr>(propStorage); + } + void setDynamic(const ::mlir::UnitAttr &propValue) { + this->dynamic = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.callee == this->callee && + rhs.dynamic == this->dynamic && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + CallOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}); + + CallOpGenericAdaptorBase(CallOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getCalleeAttr(); + ::llvm::StringRef getCallee(); + ::mlir::UnitAttr getDynamicAttr(); + bool getDynamic(); +}; +} // namespace detail +template +class CallOpGenericAdaptor : public detail::CallOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CallOpGenericAdaptorBase; +public: + CallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CallOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + template >> + CallOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getCtx() { + return (*getODSOperands(0).begin()); + } + + RangeT getArguments() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CallOpAdaptor : public CallOpGenericAdaptor<::mlir::ValueRange> { +public: + using CallOpGenericAdaptor::CallOpGenericAdaptor; + CallOpAdaptor(CallOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CallOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CallOpAdaptor; + template + using GenericAdaptor = CallOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("callee"), ::llvm::StringRef("dynamic")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCalleeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCalleeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDynamicAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDynamicAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.call"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::xla::runtime::ExecutionContextType> getCtx(); + ::mlir::Operation::operand_range getArguments(); + ::mlir::OpOperand &getCtxMutable(); + ::mlir::MutableOperandRange getArgumentsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::xla::runtime::StatusType> getStatus(); + ::mlir::Operation::result_range getResults(); + static ::mlir::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::mlir::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::StringAttr getCalleeAttr(); + ::llvm::StringRef getCallee(); + ::mlir::UnitAttr getDynamicAttr(); + bool getDynamic(); + void setCalleeAttr(::mlir::StringAttr attr); + void setCallee(::llvm::StringRef attrValue); + void setDynamicAttr(::mlir::UnitAttr attr); + void setDynamic(bool attrValue); + ::mlir::Attribute removeDynamicAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type status, ::mlir::TypeRange results, ::mlir::Value ctx, ::mlir::StringAttr callee, /*optional*/::mlir::UnitAttr dynamic, ::mlir::ValueRange arguments); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, ::mlir::StringAttr callee, /*optional*/::mlir::UnitAttr dynamic, ::mlir::ValueRange arguments); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type status, ::mlir::TypeRange results, ::mlir::Value ctx, ::llvm::StringRef callee, /*optional*/bool dynamic, ::mlir::ValueRange arguments); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, ::llvm::StringRef callee, /*optional*/bool dynamic, ::mlir::ValueRange arguments); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::CallOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::ExportOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExportOpGenericAdaptorBase { +public: + struct Properties { + using function_refTy = ::mlir::FlatSymbolRefAttr; + function_refTy function_ref; + + auto getFunctionRef() { + auto &propStorage = this->function_ref; + return ::llvm::cast<::mlir::FlatSymbolRefAttr>(propStorage); + } + void setFunctionRef(const ::mlir::FlatSymbolRefAttr &propValue) { + this->function_ref = propValue; + } + using ordinalTy = ::mlir::IntegerAttr; + ordinalTy ordinal; + + auto getOrdinal() { + auto &propStorage = this->ordinal; + return ::llvm::dyn_cast_or_null<::mlir::IntegerAttr>(propStorage); + } + void setOrdinal(const ::mlir::IntegerAttr &propValue) { + this->ordinal = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.function_ref == this->function_ref && + rhs.ordinal == this->ordinal && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ExportOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}); + + ExportOpGenericAdaptorBase(ExportOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FlatSymbolRefAttr getFunctionRefAttr(); + ::llvm::StringRef getFunctionRef(); + ::mlir::IntegerAttr getOrdinalAttr(); + ::std::optional< ::llvm::APInt > getOrdinal(); +}; +} // namespace detail +template +class ExportOpGenericAdaptor : public detail::ExportOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExportOpGenericAdaptorBase; +public: + ExportOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExportOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExportOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + template >> + ExportOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExportOpAdaptor : public ExportOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExportOpGenericAdaptor::ExportOpGenericAdaptor; + ExportOpAdaptor(ExportOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ExportOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::SymbolUserOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExportOpAdaptor; + template + using GenericAdaptor = ExportOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("function_ref"), ::llvm::StringRef("ordinal")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFunctionRefAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFunctionRefAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getOrdinalAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getOrdinalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.export"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static ::mlir::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::mlir::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::FlatSymbolRefAttr getFunctionRefAttr(); + ::llvm::StringRef getFunctionRef(); + ::mlir::IntegerAttr getOrdinalAttr(); + ::std::optional< ::llvm::APInt > getOrdinal(); + void setFunctionRefAttr(::mlir::FlatSymbolRefAttr attr); + void setFunctionRef(::llvm::StringRef attrValue); + void setOrdinalAttr(::mlir::IntegerAttr attr); + void setOrdinal(::std::optional<::llvm::APInt> attrValue); + ::mlir::Attribute removeOrdinalAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, mlir::FunctionOpInterface function_ref); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, mlir::FunctionOpInterface function_ref, unsigned ordinal); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verifySymbolUses(::mlir::SymbolTableCollection &symbolTable); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + std::optional ordinal(); + mlir::FunctionOpInterface exported(mlir::SymbolTable& sym_table); +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::ExportOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::IsOkOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IsOkOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IsOkOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IsOkOpGenericAdaptorBase(IsOkOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class IsOkOpGenericAdaptor : public detail::IsOkOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IsOkOpGenericAdaptorBase; +public: + IsOkOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IsOkOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IsOkOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IsOkOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getStatus() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IsOkOpAdaptor : public IsOkOpGenericAdaptor<::mlir::ValueRange> { +public: + using IsOkOpGenericAdaptor::IsOkOpGenericAdaptor; + IsOkOpAdaptor(IsOkOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IsOkOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants> { +public: + using Op::Op; + using Op::print; + using Adaptor = IsOkOpAdaptor; + template + using GenericAdaptor = IsOkOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.is_ok"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::xla::runtime::StatusType> getStatus(); + ::mlir::OpOperand &getStatusMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::IntegerType> getOk(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type ok, ::mlir::Value status); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value status); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::IsOkOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::SetErrorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SetErrorOpGenericAdaptorBase { +public: + struct Properties { + using errorTy = ::mlir::StringAttr; + errorTy error; + + auto getError() { + auto &propStorage = this->error; + return ::llvm::cast<::mlir::StringAttr>(propStorage); + } + void setError(const ::mlir::StringAttr &propValue) { + this->error = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.error == this->error && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + SetErrorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}); + + SetErrorOpGenericAdaptorBase(SetErrorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getErrorAttr(); + ::llvm::StringRef getError(); +}; +} // namespace detail +template +class SetErrorOpGenericAdaptor : public detail::SetErrorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SetErrorOpGenericAdaptorBase; +public: + SetErrorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SetErrorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SetErrorOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + template >> + SetErrorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getCtx() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SetErrorOpAdaptor : public SetErrorOpGenericAdaptor<::mlir::ValueRange> { +public: + using SetErrorOpGenericAdaptor::SetErrorOpGenericAdaptor; + SetErrorOpAdaptor(SetErrorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SetErrorOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = SetErrorOpAdaptor; + template + using GenericAdaptor = SetErrorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("error")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getErrorAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getErrorAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.set_error"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::xla::runtime::ExecutionContextType> getCtx(); + ::mlir::OpOperand &getCtxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static ::mlir::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::mlir::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::StringAttr getErrorAttr(); + ::llvm::StringRef getError(); + void setErrorAttr(::mlir::StringAttr attr); + void setError(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value ctx, ::mlir::StringAttr error); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, ::mlir::StringAttr error); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value ctx, ::llvm::StringRef error); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, ::llvm::StringRef error); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::SetErrorOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::SetOutputOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SetOutputOpGenericAdaptorBase { +public: + struct Properties { + using indexTy = ::mlir::IntegerAttr; + indexTy index; + + auto getIndex() { + auto &propStorage = this->index; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setIndex(const ::mlir::IntegerAttr &propValue) { + this->index = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.index == this->index && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + SetOutputOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}); + + SetOutputOpGenericAdaptorBase(SetOutputOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIndexAttr(); + uint64_t getIndex(); +}; +} // namespace detail +template +class SetOutputOpGenericAdaptor : public detail::SetOutputOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SetOutputOpGenericAdaptorBase; +public: + SetOutputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SetOutputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SetOutputOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + template >> + SetOutputOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getCtx() { + return (*getODSOperands(0).begin()); + } + + ValueT getValue() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SetOutputOpAdaptor : public SetOutputOpGenericAdaptor<::mlir::ValueRange> { +public: + using SetOutputOpGenericAdaptor::SetOutputOpGenericAdaptor; + SetOutputOpAdaptor(SetOutputOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SetOutputOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SetOutputOpAdaptor; + template + using GenericAdaptor = SetOutputOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIndexAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.set_output"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::xla::runtime::ExecutionContextType> getCtx(); + ::mlir::Value getValue(); + ::mlir::OpOperand &getCtxMutable(); + ::mlir::OpOperand &getValueMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static ::mlir::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::mlir::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::IntegerAttr getIndexAttr(); + uint64_t getIndex(); + void setIndexAttr(::mlir::IntegerAttr attr); + void setIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value ctx, ::mlir::IntegerAttr index, ::mlir::Value value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, ::mlir::IntegerAttr index, ::mlir::Value value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value ctx, uint64_t index, ::mlir::Value value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value ctx, uint64_t index, ::mlir::Value value); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::SetOutputOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::TraceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TraceOpGenericAdaptorBase { +public: + struct Properties { + using annotationTy = xla::runtime::TraceAnnotationAttrInterface; + annotationTy annotation; + + auto getAnnotation() { + auto &propStorage = this->annotation; + return ::llvm::cast(propStorage); + } + void setAnnotation(const xla::runtime::TraceAnnotationAttrInterface &propValue) { + this->annotation = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.annotation == this->annotation && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + TraceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}); + + TraceOpGenericAdaptorBase(TraceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes(); + xla::runtime::TraceAnnotationAttrInterface getAnnotationAttr(); + xla::runtime::TraceAnnotationAttrInterface getAnnotation(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class TraceOpGenericAdaptor : public detail::TraceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TraceOpGenericAdaptorBase; +public: + TraceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const Properties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TraceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TraceOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + template >> + TraceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getCtx() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TraceOpAdaptor : public TraceOpGenericAdaptor<::mlir::ValueRange> { +public: + using TraceOpGenericAdaptor::TraceOpGenericAdaptor; + TraceOpAdaptor(TraceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TraceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::OpTrait::AutomaticAllocationScope, ::mlir::OpAsmOpInterface::Trait, ::mlir::RegionBranchOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TraceOpAdaptor; + template + using GenericAdaptor = TraceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("annotation")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAnnotationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAnnotationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.trace"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::xla::runtime::ExecutionContextType> getCtx(); + ::mlir::OpOperand &getCtxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Operation::result_range getResults(); + ::mlir::Region &getBody(); + static ::mlir::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::mlir::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + xla::runtime::TraceAnnotationAttrInterface getAnnotationAttr(); + xla::runtime::TraceAnnotationAttrInterface getAnnotation(); + void setAnnotationAttr(xla::runtime::TraceAnnotationAttrInterface attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, mlir::TypeRange results, mlir::Value exec_ctx, TraceAnnotationAttrInterface annotation, llvm::function_ref bodyBuilder = nullptr); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getSuccessorRegions(::mlir::RegionBranchPoint point, ::llvm::SmallVectorImpl<::mlir::RegionSuccessor> ®ions); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // OpAsmOpInterface: Allow the dialect prefix to be omitted. + static llvm::StringRef getDefaultDialect() { return "rt"; } +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::TraceOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::UnsignedCastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class UnsignedCastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + UnsignedCastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + UnsignedCastOpGenericAdaptorBase(UnsignedCastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class UnsignedCastOpGenericAdaptor : public detail::UnsignedCastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::UnsignedCastOpGenericAdaptorBase; +public: + UnsignedCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + UnsignedCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : UnsignedCastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + UnsignedCastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValue() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class UnsignedCastOpAdaptor : public UnsignedCastOpGenericAdaptor<::mlir::ValueRange> { +public: + using UnsignedCastOpGenericAdaptor::UnsignedCastOpGenericAdaptor; + UnsignedCastOpAdaptor(UnsignedCastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class UnsignedCastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants> { +public: + using Op::Op; + using Op::print; + using Adaptor = UnsignedCastOpAdaptor; + template + using GenericAdaptor = UnsignedCastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.unsigned_cast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getValue(); + ::mlir::OpOperand &getValueMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value value); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::UnsignedCastOp) + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// ::xla::runtime::YieldOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class YieldOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + YieldOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + YieldOpGenericAdaptorBase(YieldOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class YieldOpGenericAdaptor : public detail::YieldOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::YieldOpGenericAdaptorBase; +public: + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : YieldOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + YieldOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getArguments() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class YieldOpAdaptor : public YieldOpGenericAdaptor<::mlir::ValueRange> { +public: + using YieldOpGenericAdaptor::YieldOpGenericAdaptor; + YieldOpAdaptor(YieldOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class YieldOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::IsTerminator, ::mlir::RegionBranchTerminatorOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = YieldOpAdaptor; + template + using GenericAdaptor = YieldOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("rt.yield"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getArguments(); + ::mlir::MutableOperandRange getArgumentsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange arguments); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::MutableOperandRange getMutableSuccessorOperands(::mlir::RegionBranchPoint point); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::YieldOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_types.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_types.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..5a1a866feef57d4486c6f5c6ccd467ac80acca80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/rt_types.h.inc @@ -0,0 +1,53 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* TypeDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_TYPEDEF_CLASSES +#undef GET_TYPEDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace xla { +namespace runtime { +class ExecutionContextType; +class OpaqueType; +class StatusType; +class ExecutionContextType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"execution_context"}; + } + +}; +class OpaqueType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"opaque"}; + } + +}; +class StatusType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"status"}; + } + +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::ExecutionContextType) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::OpaqueType) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::StatusType) + +#endif // GET_TYPEDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib.h new file mode 100644 index 0000000000000000000000000000000000000000..c7c60418680c731aa1e1252b331510f98c8d113d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib.h @@ -0,0 +1,51 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_IR_TESTS_TESTLIB_H_ +#define XLA_MLIR_RUNTIME_IR_TESTS_TESTLIB_H_ + +#include + +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/IR/Dialect.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project + +// clang-format off +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "xla/mlir/runtime/ir/tests/testlib_dialect.h.inc" +#include "xla/mlir/runtime/ir/tests/testlib_enums.h.inc" +// clang-format on + +#define GET_ATTRDEF_CLASSES +#include "xla/mlir/runtime/ir/tests/testlib_attrs.h.inc" + +#define GET_TYPEDEF_CLASSES +#include "xla/mlir/runtime/ir/tests/testlib_types.h.inc" + +namespace xla { +namespace runtime { + +inline mlir::Type ConvertValueType(ValueType type) { + return mlir::LLVM::LLVMPointerType::get(type.getContext()); +} + +inline void AddTestlibTypeConversions(mlir::TypeConverter& converter) { + converter.addConversion(ConvertValueType); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_IR_TESTS_TESTLIB_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_attrs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_attrs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..a7cdfa3afb673320b50adde339d5c3e5e943257c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_attrs.h.inc @@ -0,0 +1,76 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace xla { +namespace runtime { +class PairOfDimsAttr; +class EnumType2Attr; +class EnumTypeAttr; +namespace detail { +struct PairOfDimsAttrStorage; +} // namespace detail +class PairOfDimsAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static PairOfDimsAttr get(::mlir::MLIRContext *context, int64_t rank, ::llvm::ArrayRef a, ::llvm::ArrayRef b); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"pair_of_dims"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getRank() const; + ::llvm::ArrayRef getA() const; + ::llvm::ArrayRef getB() const; +}; +namespace detail { +struct EnumType2AttrStorage; +} // namespace detail +class EnumType2Attr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static EnumType2Attr get(::mlir::MLIRContext *context, ::xla::runtime::EnumType2 value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"another_enum_type"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::xla::runtime::EnumType2 getValue() const; +}; +namespace detail { +struct EnumTypeAttrStorage; +} // namespace detail +class EnumTypeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static EnumTypeAttr get(::mlir::MLIRContext *context, ::xla::runtime::EnumType value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"enum_type"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::xla::runtime::EnumType getValue() const; +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::PairOfDimsAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::EnumType2Attr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::EnumTypeAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..85a786769e77074e45b15e655a1d14522719a8b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_dialect.h.inc @@ -0,0 +1,41 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: testlib.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace xla { +namespace runtime { + +class TestlibDialect : public ::mlir::Dialect { + explicit TestlibDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~TestlibDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("testlib"); + } + + /// Parse an attribute registered to this dialect. + ::mlir::Attribute parseAttribute(::mlir::DialectAsmParser &parser, + ::mlir::Type type) const override; + + /// Print an attribute registered to this dialect. + void printAttribute(::mlir::Attribute attr, + ::mlir::DialectAsmPrinter &os) const override; + + /// Parse a type registered to this dialect. + ::mlir::Type parseType(::mlir::DialectAsmParser &parser) const override; + + /// Print a type registered to this dialect. + void printType(::mlir::Type type, + ::mlir::DialectAsmPrinter &os) const override; +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::TestlibDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_enums.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_enums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..4c46557f99e491678496bf514344d4b851894a5a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_enums.h.inc @@ -0,0 +1,173 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: testlib.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace xla { +namespace runtime { +// Custom Call Testlib Enum Type. +enum class EnumType : uint32_t { + Foo = 0, + Bar = 1, + Baz = 2, +}; + +::std::optional symbolizeEnumType(uint32_t); +::llvm::StringRef stringifyEnumType(EnumType); +::std::optional symbolizeEnumType(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForEnumType() { + return 2; +} + + +inline ::llvm::StringRef stringifyEnum(EnumType enumValue) { + return stringifyEnumType(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeEnumType(str); +} +} // namespace runtime +} // namespace xla + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::xla::runtime::EnumType, ::xla::runtime::EnumType> { + template + static FailureOr<::xla::runtime::EnumType> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Custom Call Testlib Enum Type."); + + // Symbolize the keyword. + if (::std::optional<::xla::runtime::EnumType> attr = ::xla::runtime::symbolizeEnum<::xla::runtime::EnumType>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Custom Call Testlib Enum Type. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::xla::runtime::EnumType value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::xla::runtime::EnumType> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::xla::runtime::EnumType getEmptyKey() { + return static_cast<::xla::runtime::EnumType>(StorageInfo::getEmptyKey()); + } + + static inline ::xla::runtime::EnumType getTombstoneKey() { + return static_cast<::xla::runtime::EnumType>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::xla::runtime::EnumType &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::xla::runtime::EnumType &lhs, const ::xla::runtime::EnumType &rhs) { + return lhs == rhs; + } +}; +} + +namespace xla { +namespace runtime { +// Another Custom Call Testlib Enum Type. +enum class EnumType2 : uint32_t { + Foo = 0, + Bar = 1, + Baz = 2, +}; + +::std::optional symbolizeEnumType2(uint32_t); +::llvm::StringRef stringifyEnumType2(EnumType2); +::std::optional symbolizeEnumType2(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForEnumType2() { + return 2; +} + + +inline ::llvm::StringRef stringifyEnum(EnumType2 enumValue) { + return stringifyEnumType2(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeEnumType2(str); +} +} // namespace runtime +} // namespace xla + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::xla::runtime::EnumType2, ::xla::runtime::EnumType2> { + template + static FailureOr<::xla::runtime::EnumType2> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Another Custom Call Testlib Enum Type."); + + // Symbolize the keyword. + if (::std::optional<::xla::runtime::EnumType2> attr = ::xla::runtime::symbolizeEnum<::xla::runtime::EnumType2>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Another Custom Call Testlib Enum Type. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::xla::runtime::EnumType2 value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::xla::runtime::EnumType2> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::xla::runtime::EnumType2 getEmptyKey() { + return static_cast<::xla::runtime::EnumType2>(StorageInfo::getEmptyKey()); + } + + static inline ::xla::runtime::EnumType2 getTombstoneKey() { + return static_cast<::xla::runtime::EnumType2>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::xla::runtime::EnumType2 &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::xla::runtime::EnumType2 &lhs, const ::xla::runtime::EnumType2 &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_types.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_types.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..122a2ce34448232c180e4498dffc6ba6ec00d862 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/ir/tests/testlib_types.h.inc @@ -0,0 +1,43 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* TypeDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_TYPEDEF_CLASSES +#undef GET_TYPEDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace xla { +namespace runtime { +class CustomArgType; +class ValueType; +class CustomArgType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"custom_arg"}; + } + +}; +class ValueType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"value"}; + } + +}; +} // namespace runtime +} // namespace xla +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::CustomArgType) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::ValueType) + +#endif // GET_TYPEDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/calling_convention.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/calling_convention.h new file mode 100644 index 0000000000000000000000000000000000000000..6504af7e8b36e23e9733f5535d336a62f33a8874 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/calling_convention.h @@ -0,0 +1,91 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_CALLING_CONVENTION_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_CALLING_CONVENTION_H_ + +#include + +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project + +namespace xla { +namespace runtime { + +// Calling convention converts exported function types to function types with +// a well-defined ABI (e.g. tensors do not have an ABI; they must be passed +// across the function boundary as memrefs). In a nutshell it tells the XLA +// runtime how to call the compiled executable at run time, and how to return +// results back to the caller. +// +// All types in the converted function signature should have a registered +// type conversion (see `type_converter` below) to a type with defined +// argument or result ABI (see Type::ArgumentAbi and Type::ResultAbi). +// +// If conversion is not possible, calling convention must return a null value. +// +// Example: abstract executable defined in high level dialect, e.g. MHLO +// +// ```mlir +// func @compute(%arg0: tensor, +// %arg1: tensor) -> tensor { ... } +// ``` +// +// after calling convention conversion becomes: +// +// ```mlir +// func @compute(%ctx: !rt.execution_context, +// %arg0: memref, +// %arg1: memref) -> memref { ... } +// ``` +// +// Calling convention function type is not the same as the exported function +// type produced by the compilation pipeline for several reasons: +// +// 1) Compilation pipeline produces LLVM functions with LLVM types, and high +// level information is lost, e.g. all memrefs are deconstructed into +// primitive fields when passed as inputs. +// +// 2) Exported function always returns void, and uses runtime API to return +// results back to the caller (see `xla-rt-export-functions` pass). +// +// Calling convention function type is a XLA-compatible description of the +// compiled executable ABI, so that XLA runtime can correctly initialize +// CallFrame arguments, allocate memory for returned results, and then correctly +// decode results memory into the high level types (e.g. convert returned memref +// descriptor to a Tensor). +class CallingConvention + : public std::function { + using function::function; +}; + +// Returns a calling convention that only adds the execution context argument. +CallingConvention DefaultCallingConvention(); + +// Returns a calling convention that uses user-provided type converter to +// convert all inputs and results types, and adds the execution context +// argument. +CallingConvention DefaultCallingConvention(mlir::TypeConverter); + +// Returns a calling convention that (1) prepends the execution context +// argument, (2) uses the user-provided type converter to convert all inputs and +// results types, and (3) converts result types into out-params by appending +// them to the arguments. +CallingConvention ResultsToOutsCallingConvention(mlir::TypeConverter); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_CALLING_CONVENTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..91c5a9054f633142b5b8cdf0f86855f9d97f1f89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_cpu.h @@ -0,0 +1,64 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_CPU_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_CPU_H_ + +#include + +#include "xla/mlir/runtime/transforms/compilation_pipeline_options.h" +#include "xla/runtime/compiler.h" + +namespace xla { +namespace runtime { + +struct CpuPipelineOptions { + CompilationPipelineOptions common_options; + + // Byte alignment for allocated memrefs. Depending on the compiler flags + // Tensorflow requires tensors to be aligned on 16, 32 or 64 bytes. + int alignment = 0; + + // Accelerate sparse computations with CUDA threading. + // This is an experimental feature, so off by default. + int32_t xla_cpu_sparse_cuda_threads = 0; + std::string cuda_triplet = "nvptx64-nvidia-cuda"; + std::string cuda_arch = "sm_80"; + std::string cuda_features = "+ptx71"; + + // Enables math approximations that emit AVX2 intrinsics. +#ifdef __AVX2__ + bool math_avx2 = true; +#else + bool math_avx2 = false; +#endif +}; + +// Registers dialects, interfaces and dialects translations with the registry +// required by the default XLA-CPU runtime compilation pipeline. +void RegisterDefaultXlaCpuRuntimeDialects(DialectRegistry& dialects); + +// Creates default XLA-CPU runtime compilation pipeline that lowers from the +// `rt` and `memref` dialects to the LLVMIR dialect. This is a very simple +// pipeline that is mostly intended for writing tests for the XLA runtime, and +// it is expected that all end users will construct their own compilation +// pipelines from the available XLA and MLIR passes. +void CreateDefaultXlaCpuRuntimeCompilationPipeline( + PassManager& passes, const CpuPipelineOptions& opts); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_CPU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_gpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_gpu.h new file mode 100644 index 0000000000000000000000000000000000000000..a36235baff6bc332f2d7f1af99163742154a8f4b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_gpu.h @@ -0,0 +1,51 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_GPU_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_GPU_H_ + +#include "xla/mlir/runtime/transforms/compilation_pipeline_options.h" +#include "xla/runtime/compiler.h" + +namespace mlir { +class MLIRContext; +} // namespace mlir + +namespace xla { +namespace runtime { + +// Registers dialects, interfaces and dialects translations with the registry +// required by the default XLA-GPU runtime compilation pipeline. +void RegisterDefaultXlaGpuRuntimeDialects(DialectRegistry& dialects); + +void RegisterLmhloGpuDialect(DialectRegistry& dialects); + +void RegisterTestlibDialect(DialectRegistry& dialects); + +// Creates default XLA-GPU runtime compilation pipeline that lowers from the +// `rt` and `memref` dialects to the LLVMIR dialect. This is a very simple +// pipeline that is mostly intended for writing tests for the XLA runtime, and +// it is expected that all end users will construct their own compilation +// pipelines from the available XLA and MLIR passes. +void CreateDefaultXlaGpuRuntimeCompilationPipeline( + PassManager& passes, const CompilationPipelineOptions& opts, + bool add_async_passes = false); + +void AppendXlaGpuDialectRegistry(mlir::MLIRContext& context); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_GPU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_options.h new file mode 100644 index 0000000000000000000000000000000000000000..a80876fb8bcb6ac99a84d009fa5db664c009f598 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compilation_pipeline_options.h @@ -0,0 +1,52 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_OPTIONS_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_OPTIONS_H_ + +#include + +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace runtime { + +// Common options for default XLA-{CPU,GPU} compilation pipelines. +struct CompilationPipelineOptions { + // Register names for the TypeIDs used for encoding types of custom arguments + // and attributes. + std::function populate_type_id_names; + + // Add type conversions from user-defined types to LLVM types. These + // conversions are required for lowering runtime operations to the + // corresponding runtime APIs (including custom calls). + std::function populate_type_conversions; + + // Add user-defined encoding for JitRt custom call arguments and attributes. + // + // Custom encodings allow to pass dialect-specific attributes (enums and + // structs) to the custom calls, and decode them into dialect-specific runtime + // values in the custom call handlers (see custom_call_to_llvm.h for details). + std::function populate_arg_encodings; + std::function populate_ret_encodings; + std::function populate_attr_encodings; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_COMPILATION_PIPELINE_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..4db705a32bef58775046ecc489bce78bdbf31426 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/compiler.h @@ -0,0 +1,48 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_COMPILER_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_COMPILER_H_ + +#include "mlir/IR/DialectRegistry.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project + +namespace xla { +namespace runtime { + +class DialectRegistry { + public: + DialectRegistry() = default; + mlir::DialectRegistry* operator->() { return ®istry_; } + mlir::DialectRegistry& operator*() { return registry_; } + + private: + mlir::DialectRegistry registry_; +}; + +class PassManager { + public: + explicit PassManager(mlir::PassManager* pm) : pm_(pm) {} + mlir::PassManager* operator->() { return pm_; } + mlir::PassManager& operator*() { return *pm_; } + + private: + mlir::PassManager* pm_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/custom_call_encoding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/custom_call_encoding.h new file mode 100644 index 0000000000000000000000000000000000000000..3582987c1fb653cc1b831def3f162f998360f5fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/custom_call_encoding.h @@ -0,0 +1,768 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_CUSTOM_CALL_ENCODING_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_CUSTOM_CALL_ENCODING_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/SymbolTable.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Support/TypeID.h" // from @llvm-project +#include "xla/runtime/custom_call.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// Helper classes to build XLA custom calls' lowering to the LLVM dialect. +//===----------------------------------------------------------------------===// +// +// Arguments to the custom call API intrinsic are encoded as an array of opaque +// pointers and at the runtime side available as `void**`. Runtime decodes +// opaque pointers to the C++ data structures (see runtime/custom_call.h), and +// passes them to the registered callback. Argument encoding/decoding must be +// compatible, otherwise it's very easy to get a segfault because of an illegal +// memory access. +// +// Attributes are encoded into a separate opaque storage together with names, +// so the runtime side can decode the attributes it needs and check that all +// required attributes were passed to the custom call handler. +// +// Custom call attributes are encoded as module global constants, and at run +// time we only need to pass a pointer to the constant section. +// +// Custom call arguments are encoded as an array of pointers allocated on the +// stack. Each individual argument is also encoded on the stack, because +// arguments are typically run time values and we can't encode them in the +// constant section. Statically known arguments (constants) can be encoded as +// global values together with attributes. + +// Forward declare class declared below. +class Globals; +class Allocas; + +//===----------------------------------------------------------------------===// +// Custom call arguments encoding. +//===----------------------------------------------------------------------===// + +// Encodes argument into stack allocated storage according to the ABI. +class CustomCallArgEncoding { + public: + struct Encoded { + mlir::LLVM::GlobalOp type_id; // llvm.mlir.global external $type_name : i64 + + // Statically known arguments might be encoded as global constants, + // otherwise it will be `!llvm.alloca 1 x ArgType`. + std::variant value; + }; + + virtual ~CustomCallArgEncoding() = default; + + virtual mlir::LogicalResult Match(mlir::Value value, + mlir::Value conterted) const = 0; + + virtual mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, + mlir::Value value, + mlir::Value converted) const = 0; +}; + +// A set of registered custom call arguments encodings. +class CustomCallArgEncodingSet { + public: + using Encoded = CustomCallArgEncoding::Encoded; + + // Finds matching argument encoding and tries to encode the values. Returns + // failure if didn't match values to any of the argument encodings. + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, + mlir::Value value, + mlir::Value converted) const; + + template > + CustomCallArgEncodingSet &Add() { + (encodings_.emplace_back(std::make_unique()), ...); + return *this; + } + + template > + CustomCallArgEncodingSet &Add(Arg arg, Args... args) { + (encodings_.emplace_back(std::make_unique(std::forward(arg), + std::forward(args))), + ...); + return *this; + } + + private: + std::vector> encodings_; +}; + +//===----------------------------------------------------------------------===// +// Custom call results encoding. +//===----------------------------------------------------------------------===// + +// Encodes result into stack allocated storage according to the ABI. +class CustomCallRetEncoding { + public: + struct Encoded { + mlir::LLVM::GlobalOp type_id; // llvm.mlir.global external $type_name : i64 + mlir::LLVM::AllocaOp value; // !llvm.alloca 1 x ResultType + }; + + virtual ~CustomCallRetEncoding() = default; + + virtual mlir::LogicalResult Match(mlir::Type type, + mlir::Type converted) const = 0; + + virtual mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, + mlir::Type type, + mlir::Type converted) const = 0; + + virtual mlir::FailureOr Decode( + mlir::ImplicitLocOpBuilder &b, mlir::Type type, mlir::Type converted, + mlir::LLVM::AllocaOp alloca) const = 0; +}; + +// A set of registered custom call results encodings. +class CustomCallRetEncodingSet { + public: + using Encoded = CustomCallRetEncoding::Encoded; + + // Finds matching result encoding and tries to encode the values. Returns + // failure if didn't match values to any of the result encodings. + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, + mlir::Type type, mlir::Type converted) const; + + // Convert the encoded value in alloca back to a value with the converted + // type. Return failure if the convertion failed. + mlir::FailureOr Decode(mlir::ImplicitLocOpBuilder &b, + mlir::Type type, mlir::Type converted, + mlir::LLVM::AllocaOp alloca) const; + + template > + CustomCallRetEncodingSet &Add() { + (encodings_.emplace_back(std::make_unique()), ...); + return *this; + } + + template > + CustomCallRetEncodingSet &Add(Arg arg, Args... args) { + (encodings_.emplace_back(std::make_unique(std::forward(arg), + std::forward(args))), + ...); + return *this; + } + + private: + std::vector> encodings_; +}; + +//===----------------------------------------------------------------------===// +// Custom call attributes encoding. +//===----------------------------------------------------------------------===// + +// Attributes encoding packs attribute name, data type and a value into the +// module global constant, and returns values pointing to the encoded data. +struct CustomCallAttrEncoding { + static constexpr char kAttrName[] = "__rt_attr_name"; + static constexpr char kAttrValue[] = "__rt_attr_value"; + + struct Encoded { + mlir::LLVM::GlobalOp name; // llvm.mlir.global + mlir::LLVM::GlobalOp type_id; // llvm.mlir.global external $type_name : i64 + mlir::LLVM::GlobalOp value; // llvm.mlir.global + }; + + virtual ~CustomCallAttrEncoding() = default; + + virtual mlir::LogicalResult Match(mlir::SymbolTable &sym_table, + std::string_view name, + mlir::Attribute attr) const = 0; + + virtual mlir::FailureOr Encode(mlir::SymbolTable &sym_table, + Globals &g, + mlir::ImplicitLocOpBuilder &b, + std::string_view name, + mlir::Attribute attr) const = 0; +}; + +// A set of registered custom call attributes encodings. +class CustomCallAttrEncodingSet { + public: + using Encoded = CustomCallAttrEncoding::Encoded; + + // Finds matching attribute encoding and tries to encode the attribute. + // Returns failure if didn't match attribute to any of the encodings. + mlir::FailureOr Encode(mlir::SymbolTable &sym_table, Globals &g, + mlir::ImplicitLocOpBuilder &b, + std::string_view name, + mlir::Attribute attr) const; + + template > + CustomCallAttrEncodingSet &Add() { + (encodings_.emplace_back(std::make_unique()), ...); + return *this; + } + + template > + CustomCallAttrEncodingSet &Add(ConstructorArg &&arg, + ConstructorArgs &&...args) { + (encodings_.emplace_back(std::make_unique(arg, args...)), ...); + return *this; + } + + private: + std::vector> encodings_; +}; + +//===----------------------------------------------------------------------===// +// A set of helper functions for packing encoding attributes. +//===----------------------------------------------------------------------===// + +// Encodes type id as an external LLVM global of type `i64`. The global name is +// defined by the type id name registry. Internally type id implemented as an +// opaque pointer (void*), and type equality check at run time is just a pointer +// comparison. All type id symbols at run time must be resolved to the type id +// instances defined in the current process. +mlir::LLVM::GlobalOp EncodeTypeId(Globals &g, mlir::ImplicitLocOpBuilder &b, + TypeID type_id); + +// Encodes string as a module global null-terminated string constant + size. We +// reuse the encoding scheme for arrays to store sting with its size, to avoid +// computing the length of the null-terminated string at run time. +mlir::LLVM::GlobalOp EncodeString(Globals &g, mlir::ImplicitLocOpBuilder &b, + std::string_view strref, + std::string_view symbol_base); + +// Encodes scalar attribute as a global constant. +mlir::LLVM::GlobalOp EncodeScalar(Globals &g, mlir::ImplicitLocOpBuilder &b, + mlir::Attribute value, + std::string_view symbol_base); + +//===----------------------------------------------------------------------===// +// A helper class to create global constants in the module. +//===----------------------------------------------------------------------===// + +class Globals { + public: + // Global value initializer that build the initialization region. + using GlobalInitializer = + std::function; + + // Global value initializer that can return failure if it can't initialize the + // global value from the given attribute. + using FailureOrGlobalInitializer = std::function; + + Globals(mlir::ModuleOp module, TypeIDNameRegistry type_id_names) + : module_(module), + sym_table_(module_), + type_id_names_(std::move(type_id_names)) {} + + // Creates a global external variable for the type id. + mlir::LLVM::GlobalOp GetOrCreate(mlir::ImplicitLocOpBuilder &b, + TypeID type_id); + + // Creates a global null-terminated string constant. + mlir::LLVM::GlobalOp GetOrCreate(mlir::ImplicitLocOpBuilder &b, + std::string_view strref, + std::string_view symbol_base); + + // Creates a global constant value from the attribute. Attribute type must be + // a valid type compatible with LLVM globals. + mlir::LLVM::GlobalOp GetOrCreate(mlir::ImplicitLocOpBuilder &b, + mlir::TypedAttr attr, + std::string_view symbol_base); + + // Creates a global constant value of the given type from the attribute, using + // optional user-provided global constant initialization. + mlir::LLVM::GlobalOp GetOrCreate( + mlir::ImplicitLocOpBuilder &b, mlir::Attribute attr, mlir::Type type, + std::string_view symbol_base, GlobalInitializer initialize = {}, + mlir::LLVM::Linkage linkage = mlir::LLVM::Linkage::Internal); + + // Creates a global constant value of the given type from the attribute, using + // optional user-provided global constant initialization. Returns failure if + // user-provided initialization failed to initialize the global value. + mlir::FailureOr TryGetOrCreate( + mlir::ImplicitLocOpBuilder &b, mlir::Attribute attr, mlir::Type type, + std::string_view symbol_base, FailureOrGlobalInitializer initialize = {}, + mlir::LLVM::Linkage linkage = mlir::LLVM::Linkage::Internal); + + // Returns the address of the global value. + static mlir::Value AddrOf(mlir::ImplicitLocOpBuilder &b, + mlir::LLVM::GlobalOp global); + + mlir::ModuleOp module() { return module_; } + + private: + // Globals key: {attribute, encoded-type, sym-name}. We can only have global + // constants of one of the LLVM types, and there could be multiple ways to + // encode an attribute as an LLVM type, e.g. strings can be stored as null + // terminated array of bytes, or a pair of string size and and array of bytes. + using Key = std::tuple; + + mlir::LLVM::GlobalOp Find(Key key); + + mlir::ModuleOp module_; + mlir::SymbolTable sym_table_; // symbol table for the `module_` + llvm::DenseMap globals_; + + // A mapping from the TypeID to the unique type name for encoding external + // globals corresponding to types ids. + TypeIDNameRegistry type_id_names_; +}; + +//===----------------------------------------------------------------------===// +// A helper class to create alloca operations for encoded arguments. +//===----------------------------------------------------------------------===// + +class EncodingAllocas; + +// We reuse allocas for encoding custom call arguments and results, because we +// potentially can have thousands of custom calls, and we do not want to +// accidentally blow up the stack size. It means that we might encode the same +// argument multiple times, but encoding is cheap (few store operations), and +// LLVM can potentially optimize them away. +// +// TODO(ezhulenev): Use `llvm.invariant.start` and `llvm.invariant.end` to mark +// encoded arguments allocas. +class Allocas { + public: + ~Allocas(); + + mlir::LLVM::AllocaOp GetOrCreate(mlir::ImplicitLocOpBuilder &b, + mlir::Type type); + + private: + friend class EncodingAllocas; + + struct TypedAllocas { + size_t offset = 0; + llvm::SmallVector allocas; + }; + + explicit Allocas(mlir::Block *block, + llvm::DenseMap *allocas); + + mlir::Block *block_; + llvm::DenseMap *allocas_; +}; + +// Mapping from basic block to allocas. +class EncodingAllocas { + public: + Allocas GetForOperation(mlir::Operation *op); + + private: + friend class Allocas; + + llvm::DenseMap> + allocas_; +}; + +//===----------------------------------------------------------------------===// +// Custom call attributes encoding. +//===----------------------------------------------------------------------===// + +// Encodes attribute using a scheme compatible with run time attributes decoding +// (see `internal::DecodedAttrs` in the custom call header file). +// +// Returns a value of `!llvm.ptr>` (void**) type pointing to the encoded +// attributes array (array of pointers). +// +// This function is used to encode: +// +// 1. Struct attributes as aggregates of nested attributes, where the order of +// attributes matches the order defined with the `AggregateAttrDef` schema +// defined below. +// +// 2. Custom call attributes, where the attributes sorted lexicographically by +// name, to be able to efficiently decode named attributes. +// +mlir::FailureOr EncodeAttributes( + mlir::SymbolTable &sym_table, Globals &g, mlir::ImplicitLocOpBuilder &b, + const CustomCallAttrEncodingSet &encoding, std::string_view symbol_base, + llvm::ArrayRef attrs); + +struct StringAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct ScalarAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &g, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct DenseElementsAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct ArrayAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct DenseArrayAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct EmptyArrayAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct SymbolRefAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct UnitAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +struct DictionaryAttrEncoding : public CustomCallAttrEncoding { + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute) const final; + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &, + mlir::ImplicitLocOpBuilder &, + std::string_view, + mlir::Attribute) const final; +}; + +// Custom call attribute encoding that encodes enums using their underlying +// scalar type. Type id is based on the enum type passed to the runtime. +// +// This encoding can convert enum types defined in the compiler (e.g. dialect +// enums defined in MLIR) to the enum types used at run time. +template +struct EnumAttrEncoding : public CustomCallAttrEncoding { + static_assert(std::is_enum::value, "must be an enum class"); + + // Convert from the compile time enum to the run time enum. + using Converter = std::function; + + EnumAttrEncoding() { + static_assert(std::is_same::value, + "requires enum converter"); + convert = [](EnumType value) { return value; }; + } + + explicit EnumAttrEncoding(Converter convert) : convert(std::move(convert)) {} + + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute attr) const final { + return mlir::success(attr.isa()); + } + + mlir::FailureOr Encode(mlir::SymbolTable &, Globals &g, + mlir::ImplicitLocOpBuilder &b, + std::string_view name, + mlir::Attribute attr) const final { + // Convert enum underlying integral value to an attribute. + EnumType compile_time_enum = attr.cast().getValue(); + RuntimeEnumType run_time_enum = convert(compile_time_enum); + + using T = std::underlying_type_t; + T underlying_value = static_cast(run_time_enum); + + TypeID type_id = TypeID::get>(); + mlir::Attribute underlying_attr = AsAttr(b, underlying_value); + + Encoded encoded; + encoded.name = EncodeString(g, b, name, kAttrName); + encoded.type_id = EncodeTypeId(g, b, type_id); + encoded.value = EncodeScalar(g, b, underlying_attr, kAttrValue); + + return encoded; + } + + static mlir::Attribute AsAttr(mlir::ImplicitLocOpBuilder &b, uint32_t value) { + return b.getI32IntegerAttr(value); + } + + Converter convert; +}; + +// A helper type to define `AttrType` encoding scheme. +template +struct AggregateAttrDef { + template + using Extract = T (AttrType::*)() const; + + template + using Encode = Attr (mlir::Builder::*)(T); + + template + AggregateAttrDef &Add(std::string name, Extract extract, + Encode encode) { + bindings.emplace_back([=](AttrType attr, mlir::Builder &b) { + auto encoded = std::invoke(encode, b, std::invoke(extract, attr)); + return mlir::NamedAttribute(b.getStringAttr(name), encoded); + }); + return *this; + } + + AggregateAttrDef &Add(std::string name, Extract extract) { + return Add(name, extract, &mlir::Builder::getBoolAttr); + } + + AggregateAttrDef &Add(std::string name, Extract extract) { + return Add(name, extract, &mlir::Builder::getI64IntegerAttr); + } + + AggregateAttrDef &Add(std::string name, Extract extract) { + return Add(name, extract, &mlir::Builder::getStringAttr); + } + + AggregateAttrDef &Add(std::string name, + Extract> extract) { + return Add(name, extract, &mlir::Builder::getI64TensorAttr); + } + + // A list of functions to destruct `AttrType` attribute into the aggregate + // attributes that will be used for encoding. + using Bind = std::function; + llvm::SmallVector bindings; +}; + +// Custom call attribute encoding for the user-defined attributes which encodes +// them as an aggregate of primitive attributes. It uses the encoding scheme +// compatible with the custom call attributes decoding. +template +struct AggregateAttrEncoding : public CustomCallAttrEncoding { + using AttrDef = AggregateAttrDef; + + AggregateAttrEncoding(const CustomCallAttrEncodingSet &encoding, + AttrDef attrdef) + : encoding(encoding), attrdef(std::move(attrdef)) {} + + mlir::LogicalResult Match(mlir::SymbolTable &, std::string_view, + mlir::Attribute attr) const final { + return mlir::success(attr.isa()); + } + + mlir::FailureOr Encode(mlir::SymbolTable &sym_table, Globals &g, + mlir::ImplicitLocOpBuilder &b, + std::string_view name, + mlir::Attribute attr) const final { + // Extract aggregate attributes from the user-defined attributes. + llvm::SmallVector attrs; + for (auto &bind : attrdef.bindings) + attrs.emplace_back(bind(attr.cast(), b)); + + // Encode extracted attributes as an aggregate. + auto type_id = TypeID::get>(); + auto sym = "__rt_aggregate_" + AttrType::getMnemonic(); + auto aggregate = + EncodeAttributes(sym_table, g, b, encoding, sym.str(), attrs); + if (mlir::failed(aggregate)) return mlir::failure(); + + Encoded encoded; + encoded.name = EncodeString(g, b, name, kAttrName); + encoded.type_id = EncodeTypeId(g, b, type_id); + encoded.value = *aggregate; + return encoded; + } + + const CustomCallAttrEncodingSet &encoding; + AttrDef attrdef; +}; + +//===----------------------------------------------------------------------===// +// Custom call arguments encoding. +//===----------------------------------------------------------------------===// + +// Encodes scalar arguments. +class ScalarArgEncoding : public CustomCallArgEncoding { + public: + mlir::LogicalResult Match(mlir::Value, mlir::Value) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Value, + mlir::Value) const final; +}; + +// Encodes custom call arguments passed as an opaque LLVM pointer (!llvm.ptr) +// using a custom type id. Default constructed encoding encodes `!rt.opaque` +// arguments using a `void*` type id. +class OpaqueArgEncoding : public CustomCallArgEncoding { + public: + OpaqueArgEncoding(); // encodes `!rt.opaque` with `void*` type id + OpaqueArgEncoding(std::function match, TypeID type_id); + + mlir::LogicalResult Match(mlir::Value, mlir::Value) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Value, + mlir::Value) const final; + + template + static auto Match() { + return [](mlir::Value value) { return value.getType().isa(); }; + } + + private: + std::function match_; + TypeID type_id_; +}; + +// Encodes MemRef arguments according to the (Strided)MemrefView ABI. +class MemrefArgEncoding : public CustomCallArgEncoding { + public: + mlir::LogicalResult Match(mlir::Value, mlir::Value) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Value, + mlir::Value) const final; +}; + +//===----------------------------------------------------------------------===// +// Custom call results encoding. +//===----------------------------------------------------------------------===// + +// Encodes scalar operands. +class ScalarRetEncoding : public CustomCallRetEncoding { + public: + mlir::LogicalResult Match(mlir::Type, mlir::Type) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type) const final; + mlir::FailureOr Decode(mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type, + mlir::LLVM::AllocaOp) const final; +}; + +// Encodes custom call results returned as an opaque LLVM pointer (!llvm.ptr) +// using a custom type id. Default constructed encoding encodes `!rt.opaque` +// results using a `void*` type id. +class OpaqueRetEncoding : public CustomCallRetEncoding { + public: + OpaqueRetEncoding(); // encodes `!rt.opaque` with `void*` type id + OpaqueRetEncoding(std::function match, TypeID type_id); + + mlir::LogicalResult Match(mlir::Type, mlir::Type) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type) const final; + mlir::FailureOr Decode(mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type, + mlir::LLVM::AllocaOp) const final; + + template + static auto Match() { + return [](mlir::Type type) { return type.isa(); }; + } + + private: + std::function match_; + TypeID type_id_; +}; + +// Encodes MemRef results according to the MemrefView ABI. +class MemrefRetEncoding : public CustomCallRetEncoding { + public: + mlir::LogicalResult Match(mlir::Type, mlir::Type) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type) const final; + mlir::FailureOr Decode(mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type, + mlir::LLVM::AllocaOp) const final; +}; + +class AsyncValueRetEncoding : public CustomCallRetEncoding { + public: + mlir::LogicalResult Match(mlir::Type, mlir::Type) const final; + mlir::FailureOr Encode(Globals &g, Allocas &a, + mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type) const final; + mlir::FailureOr Decode(mlir::ImplicitLocOpBuilder &b, mlir::Type, + mlir::Type, + mlir::LLVM::AllocaOp) const final; +}; + +//===----------------------------------------------------------------------===// +// Default encodings for arguments, attributes and results. +//===----------------------------------------------------------------------===// + +// TODO(ezhulenev): Use `Populate...` functions for adding default encodings. + +CustomCallArgEncodingSet DefaultArgEncodings(); +CustomCallAttrEncodingSet DefaultAttrEncodings(); +CustomCallRetEncodingSet DefaultRetEncodings(); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_CUSTOM_CALL_ENCODING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/jit_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/jit_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..9da954c97ffd25e4d1087aedab34bc46b921d7a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/jit_compiler.h @@ -0,0 +1,206 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_JIT_COMPILER_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_JIT_COMPILER_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "llvm/Support/SourceMgr.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "xla/mlir/runtime/transforms/calling_convention.h" +#include "xla/mlir/runtime/transforms/specialization.h" +#include "xla/mlir/runtime/transforms/type_converter.h" +#include "xla/runtime/arguments.h" +#include "xla/runtime/compiler.h" +#include "xla/runtime/constraints.h" +#include "xla/runtime/executable.h" +#include "xla/runtime/symbolic_shape.h" + +namespace xla { +namespace runtime { + +// JitCompiler manages parsing, specialization and compilation of a single XLA +// module to the XLA runtime executable. It owns the MLIR context where the +// module is created, and handlers to capture all compilation diagnostics +// messages. +// +// TODO(ezhulenev): Allow constructing JitCompiler (and JitExecutable) from the +// MLIR module directly without serializing it to string first. +class JitCompiler { + public: + using SymbolicShape = SymbolicShapesResolver::SymbolicShape; + + struct Options { + // Register dialects that are allowed in the serialized module. + std::function register_dialects; + + // Create a pass pipeline that is called whenever the compiled module + // gets specialized. This pipeline can use refined shape information and + // symbolic shape attributes to do the shape inference and canonicalization. + // + // Original input module might have an undefined calling convention (e.g. + // XLA runtime does not support unranked tensors), and specialization can be + // required as a precondition for compilation. + std::function create_specialization_pipeline; + + // Create a pass pipeline that lowers compiled module from high level + // dialects to the LLVM dialect. XLA runtime will use the LLVM ORC compiler + // API to compile the LLVM module at run time + // (https://llvm.org/docs/ORCv2.html). + // + // This compilation pipeline must export functions invocable by the runtime + // (convert them to an ABI compatible with the calling convention advertised + // to XLA through the `calling_convention` type conversion), and for + // that it usually must include `xla-rt-export-functions` pass. + std::function create_compilation_pipeline; + + // LLVM optimization level when JIT compiling a module. + llvm::CodeGenOptLevel jit_code_opt_level = llvm::CodeGenOptLevel::Default; + + // Runtime symbols binding allows to pass user-defined bindings for symbols + // at JIT compilation time, e.g. to bind type ids or custom calls. + ExecutionEngine::SymbolsBinding symbols_binding; + + // Calling convention defines an ABI for XLA runtime to call an executable. + // See `CallingConvention` documentation for details. + CallingConvention calling_convention = DefaultCallingConvention(); + + // Type converter converts MLIR types to the corresponding run-time types. + // Executable uses its own type hierarchy, parallel to MLIR's, so that it + // doesn't depend on any parts of the MLIR after compilation produces an + // executable artifact, because keeping MLIR context alive can be expensive + // in terms of memory usage. + // + // As a side effect, it allows loading AOT compiled executables from the + // object files without any dependencies on MLIR. + // + // Default type converter knows how to convert canonical MLIR types + // (memrefs, tensors, etc...). All user-defined types used at the compiled + // function boundary (arguments or results) should register a custom type + // conversion. + // + // When we compile the input IR, we first apply the `calling_convention` to + // get the MLIR function type for the exported function(s), and then we + // convert it to the corresponding run-time function type. + TypeConverter type_converter; + }; + + // Instantiates compiler from the serialized mlir source. + static absl::StatusOr> Instantiate( + Options opts, std::string_view mlir_module, + absl::Span exported); + + // Instantiates compiler from the mlir module. + static absl::StatusOr> Instantiate( + Options opts, mlir::ModuleOp mlir_module, + absl::Span exported); + + // Makes an executable from an instance of the JitCompiler. This is the end of + // life for the `JitCompiler`, it effectively converts the MLIR module + // to the executable (function pointer) using LLVM JIT code generation. + // Optional specialization identifier specifies if the compiled executable is + // a default one, or a specialization. + static absl::StatusOr Compile( + std::unique_ptr compiler, + std::string_view memory_region_name, + std::optional specialization = std::nullopt); + + // Specialize the exported function given by 'ordinal' to the arguments: + // + // - update all unknown dimensions according to the resolved symbolic shapes + // - attach symbolic shape attribute to the operands + // - sink small constants into the function body + // + // After the exported function's signature is updated, and all constant + // arguments are materialized in the function body, runs the user-provided + // specialization pipeline to optimize the module based on the new + // information in the IR. + // + // Returns an error if arguments are not compatible with the exported + // function's signature. + absl::Status Specialize(unsigned ordinal, ArgumentsRef arguments, + llvm::ArrayRef symbolic_shapes, + llvm::ArrayRef constraints, + const SpecializationListener* listener = nullptr); + + const Options& options() const { return opts_; } + + std::string_view name() const { + return module().getName().value_or(""); + } + + mlir::ModuleOp module() const { + assert(module_ && "failed to parse the mlir module"); + return *module_; + } + + size_t num_exported() const { return exported_.size(); } + + absl::Span exported() const { + return exported_; + } + + mlir::FunctionOpInterface exported(unsigned ordinal) const { + assert(exported_[ordinal] && "failed to resolve exported function"); + return exported_[ordinal]; + } + + private: + JitCompiler(Options opts, std::string_view mlir_module); + JitCompiler(Options opts, mlir::ModuleOp mlir_module); + + absl::Status ComputeOrdinalsForExportedFunctions( + absl::Span exported); + + absl::Status Error(std::string_view error) { + // TODO(ezhulenev): Pass diagnstic as a status payload. + return absl::InternalError(absl::StrCat(error, ":\n", diagnostic_)); + } + + Options opts_; + std::unique_ptr owned_context_; // set if context is owned + mlir::MLIRContext* context_; + + std::string diagnostic_; + llvm::raw_string_ostream diagnostic_os_; + + llvm::SourceMgr source_mgr_; + mlir::SourceMgrDiagnosticHandler handler_; + + mlir::OwningOpRef module_; // null if failed to parse + std::vector exported_; // empty if failed to parse + + bool specialized_; +}; + +// Adds "rt.export" with ordinal 0 to the "main" function in `module`. +// This is done by performing a run of the OrdinalAssignment pass using +// the given `mlir_context`. +absl::Status ExportMainWithOrdinal0(mlir::ModuleOp module, + mlir::MLIRContext& mlir_context); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_JIT_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..8fa0918dc1ee138e6e59c8189d6b914f8451ccbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h @@ -0,0 +1,108 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_PASSES_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_PASSES_H_ + +#include +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "xla/mlir/runtime/ir/rt_ops.h" // IWYU pragma: keep + +namespace xla { +namespace runtime { + +#define GEN_PASS_DECL_ORDINALASSIGNMENT +#define GEN_PASS_DECL_EXPORTFUNCTIONS +#define GEN_PASS_DECL_CONVERTCUSTOMCALLS +#define GEN_PASS_DECL_CONVERTASSERTS +#define GEN_PASS_DECL_CONVERTRUNTIMETOLLVMPASS + +#include "xla/mlir/runtime/transforms/passes.h.inc" + +//===-----------------------------------------------------------------------===/ +// Transformations targeting `rt` dialect. +//===-----------------------------------------------------------------------===/ + +std::unique_ptr> +CreateOrdinalAssignmentPass(); + +std::unique_ptr> +CreateExportRuntimeFunctionsPass(); + +std::unique_ptr> +CreateConvertCustomCallsPass(); + +std::unique_ptr> +CreateAddInitializationsPass(); + +std::unique_ptr> CreateConvertAssertsPass(); + +//===-----------------------------------------------------------------------===/ +// Conversions targeting `rt` dialect. +//===-----------------------------------------------------------------------===/ + +class TypeIDNameRegistry; +class CustomCallArgEncodingSet; +class CustomCallAttrEncodingSet; +class CustomCallRetEncodingSet; + +// Extension points for converting `rt` dialect to the LLVM dialect. +// +// Runtime custom calls is an extension mechanism for enabling compiled programs +// to call into the APIs provided by the user. It relies on converting +// values and attributes to the LLVM types (structs and pointers) with a +// well-defined memory layout, so that they can be passed across the function +// boundary and safely decoded (without dependency on C++ ABI). +// +// All user-defined types (values and attributes) that are passed to the custom +// calls must define the argument or attribute encoding. +struct ConvertRuntimeToLLvmOpts { + // Register names for the TypeIDs used for encoding types of custom arguments + // and attributes. + std::function populate_type_id_names; + + // Add type conversions for user-defined types to the corresponding LLVM + // types. Conversion pass uses these extra conversions to convert arguments + // of the entrypoint function and values passed to the custom calls. Custom + // call argument encoding can further refine how values of LLVM types passed + // to the custom call handlers by passing custom encoding (see below). + std::function populate_type_conversions; + + // Add user-defined arguments encoding to the custom call lowering. + std::function populate_arg_encodings; + + // Add user-defined attributes type encoding to the custom call lowering. + std::function populate_ret_encodings; + + // Add user-defined attributes type encoding to the custom call lowering. + std::function populate_attr_encodings; +}; + +std::unique_ptr> +CreateConvertRuntimeToLLVMPass(ConvertRuntimeToLLvmOpts opts = {}); + +//===-----------------------------------------------------------------------===/ + +#define GEN_PASS_REGISTRATION +#include "xla/mlir/runtime/transforms/passes.h.inc" + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_PASSES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..c9f453588d465d56a73726c00b22f255da686e51 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/passes.h.inc @@ -0,0 +1,776 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ADDINITIALIZATIONS +#define GEN_PASS_DECL_CONVERTASSERTS +#define GEN_PASS_DECL_CONVERTCUSTOMCALLS +#define GEN_PASS_DECL_CONVERTRUNTIMETOLLVMPASS +#define GEN_PASS_DECL_EXPORTFUNCTIONS +#define GEN_PASS_DECL_ORDINALASSIGNMENT +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// AddInitializations +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ADDINITIALIZATIONS +#undef GEN_PASS_DECL_ADDINITIALIZATIONS +#endif // GEN_PASS_DECL_ADDINITIALIZATIONS +#ifdef GEN_PASS_DEF_ADDINITIALIZATIONS +namespace impl { + +template +class AddInitializationsBase : public ::mlir::OperationPass { +public: + using Base = AddInitializationsBase; + + AddInitializationsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddInitializationsBase(const AddInitializationsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-add-initializations"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-add-initializations"; } + + ::llvm::StringRef getDescription() const override { return "Add initialization custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddInitializations"); + } + ::llvm::StringRef getName() const override { return "AddInitializations"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddInitializationsBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ADDINITIALIZATIONS +#endif // GEN_PASS_DEF_ADDINITIALIZATIONS + +//===----------------------------------------------------------------------===// +// ConvertAsserts +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTASSERTS +#undef GEN_PASS_DECL_CONVERTASSERTS +#endif // GEN_PASS_DECL_CONVERTASSERTS +#ifdef GEN_PASS_DEF_CONVERTASSERTS +namespace impl { + +template +class ConvertAssertsBase : public ::mlir::OperationPass { +public: + using Base = ConvertAssertsBase; + + ConvertAssertsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertAssertsBase(const ConvertAssertsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-convert-asserts"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-convert-asserts"; } + + ::llvm::StringRef getDescription() const override { return "Converts asserts in exported functions to run-time errors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAsserts"); + } + ::llvm::StringRef getName() const override { return "ConvertAsserts"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAssertsBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTASSERTS +#endif // GEN_PASS_DEF_CONVERTASSERTS + +//===----------------------------------------------------------------------===// +// ConvertCustomCalls +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCUSTOMCALLS +#undef GEN_PASS_DECL_CONVERTCUSTOMCALLS +#endif // GEN_PASS_DECL_CONVERTCUSTOMCALLS +#ifdef GEN_PASS_DEF_CONVERTCUSTOMCALLS +namespace impl { + +template +class ConvertCustomCallsBase : public ::mlir::OperationPass { +public: + using Base = ConvertCustomCallsBase; + + ConvertCustomCallsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertCustomCallsBase(const ConvertCustomCallsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-convert-custom-calls"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-convert-custom-calls"; } + + ::llvm::StringRef getDescription() const override { return "Converts custom calls to explicit `rt.custom_call` operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertCustomCalls"); + } + ::llvm::StringRef getName() const override { return "ConvertCustomCalls"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertCustomCallsBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTCUSTOMCALLS +#endif // GEN_PASS_DEF_CONVERTCUSTOMCALLS + +//===----------------------------------------------------------------------===// +// ConvertRuntimeToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTRUNTIMETOLLVMPASS +#undef GEN_PASS_DECL_CONVERTRUNTIMETOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTRUNTIMETOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTRUNTIMETOLLVMPASS +namespace impl { + +template +class ConvertRuntimeToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertRuntimeToLLVMPassBase; + + ConvertRuntimeToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertRuntimeToLLVMPassBase(const ConvertRuntimeToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert RT dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertRuntimeToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertRuntimeToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertRuntimeToLLVMPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTRUNTIMETOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTRUNTIMETOLLVMPASS + +//===----------------------------------------------------------------------===// +// ExportFunctions +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_EXPORTFUNCTIONS +#undef GEN_PASS_DECL_EXPORTFUNCTIONS +#endif // GEN_PASS_DECL_EXPORTFUNCTIONS +#ifdef GEN_PASS_DEF_EXPORTFUNCTIONS +namespace impl { + +template +class ExportFunctionsBase : public ::mlir::OperationPass { +public: + using Base = ExportFunctionsBase; + + ExportFunctionsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ExportFunctionsBase(const ExportFunctionsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-export-functions"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-export-functions"; } + + ::llvm::StringRef getDescription() const override { return "Exports function(s) to Xla runtime"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ExportFunctions"); + } + ::llvm::StringRef getName() const override { return "ExportFunctions"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ExportFunctionsBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_EXPORTFUNCTIONS +#endif // GEN_PASS_DEF_EXPORTFUNCTIONS + +//===----------------------------------------------------------------------===// +// OrdinalAssignment +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ORDINALASSIGNMENT +#undef GEN_PASS_DECL_ORDINALASSIGNMENT +#endif // GEN_PASS_DECL_ORDINALASSIGNMENT +#ifdef GEN_PASS_DEF_ORDINALASSIGNMENT +namespace impl { + +template +class OrdinalAssignmentBase : public ::mlir::OperationPass { +public: + using Base = OrdinalAssignmentBase; + + OrdinalAssignmentBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OrdinalAssignmentBase(const OrdinalAssignmentBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-ordinal-assignment"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-ordinal-assignment"; } + + ::llvm::StringRef getDescription() const override { return "Assigns ordinals to all exported functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OrdinalAssignment"); + } + ::llvm::StringRef getName() const override { return "OrdinalAssignment"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OrdinalAssignmentBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ORDINALASSIGNMENT +#endif // GEN_PASS_DEF_ORDINALASSIGNMENT +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// AddInitializations Registration +//===----------------------------------------------------------------------===// + +inline void registerAddInitializations() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateAddInitializationsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAddInitializationsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateAddInitializationsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertAsserts Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertAsserts() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateConvertAssertsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertAssertsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateConvertAssertsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertCustomCalls Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertCustomCalls() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateConvertCustomCallsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertCustomCallsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateConvertCustomCallsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertRuntimeToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertRuntimeToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::runtime::CreateConvertRuntimeToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertRuntimeToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::xla::runtime::CreateConvertRuntimeToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ExportFunctions Registration +//===----------------------------------------------------------------------===// + +inline void registerExportFunctions() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateExportRuntimeFunctionsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerExportFunctionsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateExportRuntimeFunctionsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// OrdinalAssignment Registration +//===----------------------------------------------------------------------===// + +inline void registerOrdinalAssignment() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateOrdinalAssignmentPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerOrdinalAssignmentPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return xla::runtime::CreateOrdinalAssignmentPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RuntimeTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerRuntimeTransformsPasses() { + registerAddInitializations(); + registerConvertAsserts(); + registerConvertCustomCalls(); + registerConvertRuntimeToLLVMPass(); + registerExportFunctions(); + registerOrdinalAssignment(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class AddInitializationsBase : public ::mlir::OperationPass { +public: + using Base = AddInitializationsBase; + + AddInitializationsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddInitializationsBase(const AddInitializationsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-add-initializations"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-add-initializations"; } + + ::llvm::StringRef getDescription() const override { return "Add initialization custom calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddInitializations"); + } + ::llvm::StringRef getName() const override { return "AddInitializations"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddInitializationsBase) + +protected: +}; + +template +class ConvertAssertsBase : public ::mlir::OperationPass { +public: + using Base = ConvertAssertsBase; + + ConvertAssertsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertAssertsBase(const ConvertAssertsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-convert-asserts"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-convert-asserts"; } + + ::llvm::StringRef getDescription() const override { return "Converts asserts in exported functions to run-time errors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAsserts"); + } + ::llvm::StringRef getName() const override { return "ConvertAsserts"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAssertsBase) + +protected: +}; + +template +class ConvertCustomCallsBase : public ::mlir::OperationPass { +public: + using Base = ConvertCustomCallsBase; + + ConvertCustomCallsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertCustomCallsBase(const ConvertCustomCallsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-convert-custom-calls"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-convert-custom-calls"; } + + ::llvm::StringRef getDescription() const override { return "Converts custom calls to explicit `rt.custom_call` operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertCustomCalls"); + } + ::llvm::StringRef getName() const override { return "ConvertCustomCalls"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertCustomCallsBase) + +protected: +}; + +template +class ConvertRuntimeToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertRuntimeToLLVMPassBase; + + ConvertRuntimeToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertRuntimeToLLVMPassBase(const ConvertRuntimeToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert RT dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertRuntimeToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertRuntimeToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertRuntimeToLLVMPassBase) + +protected: +}; + +template +class ExportFunctionsBase : public ::mlir::OperationPass { +public: + using Base = ExportFunctionsBase; + + ExportFunctionsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ExportFunctionsBase(const ExportFunctionsBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-export-functions"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-export-functions"; } + + ::llvm::StringRef getDescription() const override { return "Exports function(s) to Xla runtime"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ExportFunctions"); + } + ::llvm::StringRef getName() const override { return "ExportFunctions"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ExportFunctionsBase) + +protected: +}; + +template +class OrdinalAssignmentBase : public ::mlir::OperationPass { +public: + using Base = OrdinalAssignmentBase; + + OrdinalAssignmentBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OrdinalAssignmentBase(const OrdinalAssignmentBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-rt-ordinal-assignment"); + } + ::llvm::StringRef getArgument() const override { return "xla-rt-ordinal-assignment"; } + + ::llvm::StringRef getDescription() const override { return "Assigns ordinals to all exported functions"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OrdinalAssignment"); + } + ::llvm::StringRef getName() const override { return "OrdinalAssignment"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OrdinalAssignmentBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/specialization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/specialization.h new file mode 100644 index 0000000000000000000000000000000000000000..592a3dbd1020c9d58c88f8eff34e2f74ddf19273 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/specialization.h @@ -0,0 +1,69 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_SPECIALIZATION_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_SPECIALIZATION_H_ + +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/Interfaces/FunctionInterfaces.h" // from @llvm-project +#include "xla/runtime/arguments.h" +#include "xla/runtime/constraints.h" +#include "xla/runtime/symbolic_shape.h" + +namespace xla { +namespace runtime { + +// TODO(ezhulenev): A lot of specialization code is written with an assumption +// that we can only specialize Tensor arguments. Make this extendable +// to support user-defined types and user-defined specializations. + +// Symbolic shape attached to the argument as a dense i64 array attribute. +// TODO(ezhulenev): Change symbolic shape attribute type to match the comment. +constexpr const char* kSymbolicShapeAttrName = "rt.symbolic_shape"; + +// Listener class to control notifications during specialization. +struct SpecializationListener { + virtual ~SpecializationListener() {} + + // Called at the end of module specialization. + // - 'operands' is a reference to the specialized operands' types. + // - `attrs` is a list of attributes attached to operands. + virtual void notifyModuleSpecialized( + llvm::ArrayRef operands, + llvm::ArrayRef attrs) const {} + + // Called once for every value-specialized argument. + virtual void notifyValueSpecialized(unsigned index, mlir::Type type, + mlir::Attribute value) const {} +}; + +// Specializes function to the runtime arguments: +// +// - updates all unknown dimensions according to the resolved symbolic shapes +// - attaches symbolic shape attribute to the operands +// - for value-specialized operands sinks small constants into the function body +// +// Returns error if arguments are not compatible with the function signature. +absl::Status SpecializeFunction( + mlir::FunctionOpInterface func, ArgumentsRef arguments, + llvm::ArrayRef symbolic_shapes, + llvm::ArrayRef constraints, + const SpecializationListener* listener = nullptr); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_SPECIALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/type_converter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/type_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..2c99b81fa8b1d08c40055abf6d7e42b4d6192d5d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/transforms/type_converter.h @@ -0,0 +1,87 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_TRANSFORMS_TYPE_CONVERTER_H_ +#define XLA_MLIR_RUNTIME_TRANSFORMS_TYPE_CONVERTER_H_ + +#include +#include + +#include "absl/status/statusor.h" +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "xla/runtime/types.h" + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// Type conversion from the compile time types to the run-time types. +//===----------------------------------------------------------------------===// + +// Type converter converts MLIR types known at compile time to the corresponding +// types used at run time. It provides default conversions for the canonical +// types (memrefs, tensors, etc...) and allows users to register custom +// conversions for user-defined types. +class TypeConverter { + public: + // Conversion function must return run time type corresponding to the compile + // time type if the conversion is successful, or `nullptr` if failed. + using ConversionFn = std::function(mlir::Type)>; + + TypeConverter() = default; + + template + explicit TypeConverter(Fns&&... fn) { + (AddConversion(std::forward(fn)), ...); + } + + // Adds a type conversion function with a type predicate. + // + // Example: + // + // AddConversion([](mlir::TensorType) -> std::unique_ptr { ... }); + // + // The conversion function will match only the tensor type, and return empty + // result for all other types, and the type converter will try the next + // conversion function (see `Convert` implementation). + template > + void AddConversion(Fn&& fn) { + using ArgType = typename FnTraits::template arg_t<0>; + conversions_.emplace_back( + [fn = std::forward(fn)](mlir::Type type) -> std::unique_ptr { + if (auto arg = type.dyn_cast()) return fn(arg); + return {}; + }); + } + + // Converts MLIR element type to the PrimitiveType. + static absl::StatusOr ConvertElementType(mlir::Type type); + + // Converts MLIR type to the runtime type. Returns error if conversion was not + // successful and the type has no corresponding run time type. + absl::StatusOr> Convert(mlir::Type type) const; + + // Converts MLIR function type to the runtime function type. Returns error if + // function has unsupported operands or results types. + absl::StatusOr Convert(mlir::FunctionType type) const; + + private: + llvm::SmallVector conversions_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_TRANSFORMS_TYPE_CONVERTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/async_runtime_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/async_runtime_api.h new file mode 100644 index 0000000000000000000000000000000000000000..a07b4640f1eb31fa11c8839a143783cfff3dc913 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/async_runtime_api.h @@ -0,0 +1,60 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_UTILS_ASYNC_RUNTIME_API_H_ +#define XLA_MLIR_RUNTIME_UTILS_ASYNC_RUNTIME_API_H_ + +#include "absl/functional/any_invocable.h" +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/Mangling.h" +#include "xla/runtime/async_runtime.h" +#include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime +#include "tfrt/concurrency/chain.h" // from @tf_runtime + +namespace xla { +namespace runtime { + +// Converts MLIR Async Runtime token into the TFRT async chain, and drops the +// reference count on the token. +tsl::AsyncValueRef ConvertAsyncTokenToChain( + AsyncRuntime::Token* token); + +// Extracts a payload from the MLIR Async Runtime `value` and emplaces it into +// the TFRT async value `dst` using a user provided emplace function. Drops the +// reference on the runtime value after it is no longer needed. +void ExtractAsyncValue( + AsyncRuntime::Value* value, tsl::AsyncValue* dst, + absl::AnyInvocable emplace_fn); + +// A version of the `ExtractAsyncValue` function defined above that takes an +// additional opaque pointer that will be passed to the emplace function when +// async value will become ready. It is the caller responsibility to ensure that +// the pointed object will stay alive. +void ExtractAsyncValue( + AsyncRuntime::Value* value, tsl::AsyncValue* dst, void* context, + llvm::function_ref emplace_fn); + +// Builds a symbol map from the Async Runtime API functions. +llvm::orc::SymbolMap AsyncRuntimeApiSymbolMap( + llvm::orc::MangleAndInterner mangle); + +// TODO(ezhulenev): This should not be a part of async runtime api library. +llvm::orc::SymbolMap AsyncRuntimeMemoryAllocationSymbolMap( + llvm::orc::MangleAndInterner mangle); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_UTILS_ASYNC_RUNTIME_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/c_runner_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/c_runner_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..7a7910c141ab2d31bf74ef93d685542b4de68db0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/c_runner_utils.h @@ -0,0 +1,48 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_UTILS_C_RUNNER_UTILS_H_ +#define XLA_MLIR_RUNTIME_UTILS_C_RUNNER_UTILS_H_ + +#include + +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/Mangling.h" +#include "mlir/ExecutionEngine/CRunnerUtils.h" // from @llvm-project + +namespace xla { +namespace runtime { + +inline llvm::orc::SymbolMap CRunnerUtilsSymbolMap( + llvm::orc::MangleAndInterner mangle) { + llvm::orc::SymbolMap symbol_map; + + auto bind = [&](std::string_view name, auto symbol_ptr) { + symbol_map[mangle(name)] = {llvm::orc::ExecutorAddr::fromPtr(symbol_ptr), + llvm::JITSymbolFlags()}; + }; + +#ifndef _WIN32 + // TODO(b/246980307): fails to link on windows because it's marked dllimport. + bind("memrefCopy", &memrefCopy); +#endif + + return symbol_map; +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_UTILS_C_RUNNER_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/constraints.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/constraints.h new file mode 100644 index 0000000000000000000000000000000000000000..99cd314cfac38f365a405543a531a663911ce53d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/constraints.h @@ -0,0 +1,49 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_UTILS_CONSTRAINTS_H_ +#define XLA_MLIR_RUNTIME_UTILS_CONSTRAINTS_H_ + +#include "absl/status/statusor.h" +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/Interfaces/FunctionInterfaces.h" // from @llvm-project +#include "xla/runtime/constraints.h" + +namespace xla { +namespace runtime { +// Returns arguments constraints inferred from the function signature. +absl::StatusOr> GetArgumentsConstraints( + mlir::FunctionOpInterface func); + +// Resolves argument constraint based on the argument type, if constraint is +// fully satisfied by the type, returns `kResolved`. +absl::StatusOr ResolveArgumentConstraint( + ArgumentConstraint constraint, mlir::Type type); + +// Returns true iff the value of given type can be sunk into the function body +// at run time via value specialization. +inline bool SupportsValueSpecialization(mlir::Type type) { + // TODO(ezhulenev): Add support for sinking `memref` values once the value + // specialization will support it. + mlir::TensorType tensor = type.dyn_cast(); + return tensor && (tensor.getRank() == 0 || tensor.getRank() == 1) && + (tensor.getElementType().isInteger(32) || + tensor.getElementType().isInteger(64)); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_UTILS_CONSTRAINTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/custom_calls.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/custom_calls.h new file mode 100644 index 0000000000000000000000000000000000000000..1b50fda35390b2f9e127f2e99577392d62782713 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/custom_calls.h @@ -0,0 +1,74 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_UTILS_CUSTOM_CALLS_H_ +#define XLA_MLIR_RUNTIME_UTILS_CUSTOM_CALLS_H_ + +#include +#include + +#include "llvm/ADT/StringRef.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project +#include "mlir/IR/SymbolTable.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project + +namespace xla { +namespace runtime { + +// A helper class to create XLA runtime custom call declarations in the given +// symbol table. This class ensures that for each unique combination of the +// custom call target and function signature we create exaclty one custom call +// funcation declaration. +class CustomCallDeclarations { + public: + explicit CustomCallDeclarations(mlir::SymbolTable sym_table); + + // Returns existing custom call declaration or creates a new one. + mlir::func::FuncOp GetOrCreate(mlir::ImplicitLocOpBuilder& b, + llvm::StringRef target, + mlir::FunctionType type); + + // Returns existing custom call declaration or creates a new one with a + // function type constructed from `inputs` and `results`. + mlir::func::FuncOp GetOrCreate(mlir::ImplicitLocOpBuilder& b, + llvm::StringRef target, mlir::TypeRange inputs, + mlir::TypeRange results); + + // Returns existing custom call declaration or creates a new one with a + // function type constructed from the `op` operands and results. + mlir::func::FuncOp GetOrCreate(mlir::ImplicitLocOpBuilder& b, + llvm::StringRef target, mlir::Operation* op); + + mlir::SymbolTable& sym_table() { return sym_table_; } + + private: + mlir::SymbolTable sym_table_; + + using Key = std::pair; + llvm::DenseMap custom_calls_; +}; + +// Appends all attributes from the list to the operation. +void AppendCustomCallAttrs(mlir::Operation* op, + llvm::ArrayRef attrs); + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_UTILS_CUSTOM_CALLS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/float_16bits.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/float_16bits.h new file mode 100644 index 0000000000000000000000000000000000000000..51b5ac419cb5bd8a015e0c4ff0db96aa22d8be13 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/runtime/utils/float_16bits.h @@ -0,0 +1,51 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_RUNTIME_UTILS_FLOAT_16BITS_H_ +#define XLA_MLIR_RUNTIME_UTILS_FLOAT_16BITS_H_ + +#include + +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/Mangling.h" + +// Provided by compiler-rt and MLIR. +// Converts an F32 value to a BF16. +extern "C" uint16_t __truncsfbf2(float); +// Converts an F64 value to a BF16. +extern "C" uint16_t __truncdfbf2(double); + +namespace xla { +namespace runtime { + +inline llvm::orc::SymbolMap Float16bitsSymbolMap( + llvm::orc::MangleAndInterner mangle) { + llvm::orc::SymbolMap symbol_map; + + auto bind = [&](std::string_view name, auto symbol_ptr) { + symbol_map[mangle(name)] = {llvm::orc::ExecutorAddr::fromPtr(symbol_ptr), + llvm::JITSymbolFlags()}; + }; + + bind("__truncsfbf2", &__truncsfbf2); + bind("__truncdfbf2", &__truncdfbf2); + + return symbol_map; +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_MLIR_RUNTIME_UTILS_FLOAT_16BITS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/utils/error_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/utils/error_util.h new file mode 100644 index 0000000000000000000000000000000000000000..ddf85ec63fdb6630625bcb417f58a7fdb55d156d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/utils/error_util.h @@ -0,0 +1,72 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_MLIR_UTILS_ERROR_UTIL_H_ +#define XLA_MLIR_UTILS_ERROR_UTIL_H_ + +#include + +#include "absl/status/status.h" +#include "llvm/Support/SourceMgr.h" +#include "llvm/Support/raw_ostream.h" +#include "mlir/IR/Diagnostics.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project + +// Error utilities for MLIR when interacting with code using Status returns. +namespace mlir { +// Diagnostic handler that collects all the diagnostics reported and can +// produce a Status to return to callers. This is for the case where MLIR +// functions are called from a function that will return a Status: MLIR code +// still uses the default error reporting, and the final return function can +// return the Status constructed from the diagnostics collected. +class BaseScopedDiagnosticHandler : public SourceMgrDiagnosticHandler { + public: + explicit BaseScopedDiagnosticHandler(MLIRContext* context, + bool propagate = false, + bool filter_stack = false); + // On destruction error consumption is verified. + ~BaseScopedDiagnosticHandler(); + // Returns whether any errors were reported. + bool ok() const; + + // Returns Status corresponding to the diagnostics reported. This consumes + // the diagnostics reported and returns a Status of type Unknown. It is + // required to consume the error status, if there is one, before destroying + // the object. + absl::Status ConsumeStatus(); + + // Returns the combination of the passed in status and consumed diagnostics. + // This consumes the diagnostics reported and either appends the diagnostics + // to the error message of 'status' (if 'status' is already an error state), + // or returns an Unknown status (if diagnostics reported), otherwise OK. + absl::Status Combine(absl::Status status); + + protected: + LogicalResult handler(Diagnostic* diag); + + // String stream to assemble the final error message. + std::string diag_str_; + llvm::raw_string_ostream diag_stream_; + + // A SourceMgr to use for the base handler class. + llvm::SourceMgr source_mgr_; + + // Whether to propagate diagnostics to the old diagnostic handler. + bool propagate_; +}; +} // namespace mlir + +#endif // XLA_MLIR_UTILS_ERROR_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..17197dfe1c5c2f8c1ec64accb3534fd3b5a08f6b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h @@ -0,0 +1,38 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the operations and types used in the XLAFramework dialect. +// +#ifndef XLA_MLIR_XLA_CPU_IR_XLA_CPU_H_ +#define XLA_MLIR_XLA_CPU_IR_XLA_CPU_H_ + +#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Dialect.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/OpImplementation.h" // from @llvm-project +#include "mlir/Interfaces/InferTypeOpInterface.h" // from @llvm-project + +#define GET_OP_CLASSES +#include "xla/mlir/xla_cpu/ir/xla_cpu.h.inc" +#include "xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc" +#include "xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc" +#define GET_ATTRDEF_CLASSES +#include "xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc" +#undef GET_OP_CLASSES + +#endif // XLA_MLIR_XLA_CPU_IR_XLA_CPU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..27e64b9788908511baba86881ac4f4d925e147e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu.h.inc @@ -0,0 +1,2028 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: xla_cpu_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace xla_cpu { +class AddDependencyOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class AllReduceOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class AllToAllOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class CollectivePermuteOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class ConvolutionOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class FftOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class InfeedOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class MemRefElementCastOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class OutfeedOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class PartitionIdOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class ReplicaIdOp; +} // namespace xla_cpu +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class RngBitGeneratorOp; +} // namespace xla_cpu +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::AddDependencyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AddDependencyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AddDependencyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AddDependencyOpGenericAdaptorBase(AddDependencyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AddDependencyOpGenericAdaptor : public detail::AddDependencyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AddDependencyOpGenericAdaptorBase; +public: + AddDependencyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AddDependencyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AddDependencyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AddDependencyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getToken() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AddDependencyOpAdaptor : public AddDependencyOpGenericAdaptor<::mlir::ValueRange> { +public: + using AddDependencyOpGenericAdaptor::AddDependencyOpGenericAdaptor; + AddDependencyOpAdaptor(AddDependencyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AddDependencyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::bufferization::BufferizableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AddDependencyOpAdaptor; + template + using GenericAdaptor = AddDependencyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.add_dependency"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getOperand(); + ::mlir::Value getToken(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 0; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return false; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (opOperand.getOperandNumber() == 0 || opOperand.getOperandNumber() == 1) + return {}; + return {{getOperation()->getOpResult(0), + bufferization::BufferRelation::Unknown, /*isDefinite=*/false}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::AddDependencyOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::AllReduceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceOpGenericAdaptorBase(AllReduceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::IntegerAttr getChannelHandleAttr(); + uint64_t getChannelHandle(); + ::mlir::IntegerAttr getUseGlobalDeviceIdsAttr(); + uint32_t getUseGlobalDeviceIds(); + ::mlir::IntegerAttr getReductionKindAttr(); + ::llvm::APInt getReductionKind(); +}; +} // namespace detail +template +class AllReduceOpGenericAdaptor : public detail::AllReduceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceOpGenericAdaptorBase; +public: + AllReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getDsts() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllReduceOpAdaptor : public AllReduceOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceOpGenericAdaptor::AllReduceOpGenericAdaptor; + AllReduceOpAdaptor(AllReduceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceOpAdaptor; + template + using GenericAdaptor = AllReduceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("reduction_kind"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getReductionKindAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getReductionKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.all_reduce"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::Operation::operand_range getDsts(); + ::mlir::MutableOperandRange getOperandMutable(); + ::mlir::MutableOperandRange getDstsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::IntegerAttr getChannelHandleAttr(); + uint64_t getChannelHandle(); + ::mlir::IntegerAttr getUseGlobalDeviceIdsAttr(); + uint32_t getUseGlobalDeviceIds(); + ::mlir::IntegerAttr getReductionKindAttr(); + ::llvm::APInt getReductionKind(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::IntegerAttr attr); + void setChannelHandle(uint64_t attrValue); + void setUseGlobalDeviceIdsAttr(::mlir::IntegerAttr attr); + void setUseGlobalDeviceIds(uint32_t attrValue); + void setReductionKindAttr(::mlir::IntegerAttr attr); + void setReductionKind(::llvm::APInt attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operand, ::mlir::ValueRange dsts, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::IntegerAttr channel_handle, ::mlir::IntegerAttr use_global_device_ids, ::mlir::IntegerAttr reduction_kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operand, ::mlir::ValueRange dsts, ::mlir::DenseIntElementsAttr replica_groups, uint64_t channel_handle, uint32_t use_global_device_ids, ::llvm::APInt reduction_kind); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 4 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state); + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state); + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state); + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::AllReduceOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::AllToAllOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllOpGenericAdaptorBase(AllToAllOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::IntegerAttr getChannelIdPresentAttr(); + uint32_t getChannelIdPresent(); + ::mlir::IntegerAttr getOpIdAttr(); + uint64_t getOpId(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + ::mlir::IntegerAttr getConcatDimensionAttr(); + ::std::optional getConcatDimension(); + ::mlir::IntegerAttr getSplitCountAttr(); + ::std::optional getSplitCount(); +}; +} // namespace detail +template +class AllToAllOpGenericAdaptor : public detail::AllToAllOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllOpGenericAdaptorBase; +public: + AllToAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getDst() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllOpAdaptor : public AllToAllOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllOpGenericAdaptor::AllToAllOpGenericAdaptor; + AllToAllOpAdaptor(AllToAllOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllOpAdaptor; + template + using GenericAdaptor = AllToAllOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id_present"), ::llvm::StringRef("concat_dimension"), ::llvm::StringRef("op_id"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("split_count"), ::llvm::StringRef("split_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdPresentAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdPresentAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConcatDimensionAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConcatDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getOpIdAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getOpIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getSplitCountAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getSplitCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getSplitDimensionAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getSplitDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.all_to_all"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::Operation::operand_range getDst(); + ::mlir::MutableOperandRange getOperandMutable(); + ::mlir::MutableOperandRange getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::IntegerAttr getChannelIdPresentAttr(); + uint32_t getChannelIdPresent(); + ::mlir::IntegerAttr getOpIdAttr(); + uint64_t getOpId(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + ::mlir::IntegerAttr getConcatDimensionAttr(); + ::std::optional getConcatDimension(); + ::mlir::IntegerAttr getSplitCountAttr(); + ::std::optional getSplitCount(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelIdPresentAttr(::mlir::IntegerAttr attr); + void setChannelIdPresent(uint32_t attrValue); + void setOpIdAttr(::mlir::IntegerAttr attr); + void setOpId(uint64_t attrValue); + void setSplitDimensionAttr(::mlir::IntegerAttr attr); + void setSplitDimension(::std::optional attrValue); + void setConcatDimensionAttr(::mlir::IntegerAttr attr); + void setConcatDimension(::std::optional attrValue); + void setSplitCountAttr(::mlir::IntegerAttr attr); + void setSplitCount(::std::optional attrValue); + ::mlir::Attribute removeSplitDimensionAttr(); + ::mlir::Attribute removeConcatDimensionAttr(); + ::mlir::Attribute removeSplitCountAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operand, ::mlir::ValueRange dst, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::IntegerAttr channel_id_present, ::mlir::IntegerAttr op_id, /*optional*/::mlir::IntegerAttr split_dimension, /*optional*/::mlir::IntegerAttr concat_dimension, /*optional*/::mlir::IntegerAttr split_count); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operand, ::mlir::ValueRange dst, ::mlir::DenseIntElementsAttr replica_groups, uint32_t channel_id_present, uint64_t op_id, /*optional*/::mlir::IntegerAttr split_dimension, /*optional*/::mlir::IntegerAttr concat_dimension, /*optional*/::mlir::IntegerAttr split_count); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() < getNumOperands() / 2; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() >= getNumOperands() / 2; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (bufferizesToMemoryRead(opOperand, state)) return {}; + return {{getOperation()->getOpResult(opOperand.getOperandNumber() - getNumOperands() / 2), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::AllToAllOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::CollectivePermuteOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteOpGenericAdaptorBase(CollectivePermuteOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::IntegerAttr getChannelHandleAttr(); + uint64_t getChannelHandle(); +}; +} // namespace detail +template +class CollectivePermuteOpGenericAdaptor : public detail::CollectivePermuteOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteOpGenericAdaptorBase; +public: + CollectivePermuteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getDst() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteOpAdaptor : public CollectivePermuteOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteOpGenericAdaptor::CollectivePermuteOpGenericAdaptor; + CollectivePermuteOpAdaptor(CollectivePermuteOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::bufferization::BufferizableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteOpAdaptor; + template + using GenericAdaptor = CollectivePermuteOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("source_target_pairs")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getSourceTargetPairsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getSourceTargetPairsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.collective_permute"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::ShapedType> getOperand(); + ::mlir::TypedValue<::mlir::ShapedType> getDst(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::IntegerAttr getChannelHandleAttr(); + uint64_t getChannelHandle(); + void setSourceTargetPairsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::IntegerAttr attr); + void setChannelHandle(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value operand, ::mlir::Value dst, ::mlir::DenseIntElementsAttr source_target_pairs, ::mlir::IntegerAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value operand, ::mlir::Value dst, ::mlir::DenseIntElementsAttr source_target_pairs, uint64_t channel_handle); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 0; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 1; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (opOperand.getOperandNumber() == 0) return {}; + return {{getOperation()->getOpResult(0), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::CollectivePermuteOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::ConvolutionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvolutionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvolutionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvolutionOpGenericAdaptorBase(ConvolutionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::IntegerAttr getInputBatchDimensionAttr(); + uint64_t getInputBatchDimension(); + ::mlir::IntegerAttr getInputFeatureDimensionAttr(); + uint64_t getInputFeatureDimension(); + ::mlir::ArrayAttr getInputSpatialDimensionsAttr(); + ::mlir::ArrayAttr getInputSpatialDimensions(); + ::mlir::IntegerAttr getKernelInputFeatureDimensionAttr(); + uint64_t getKernelInputFeatureDimension(); + ::mlir::IntegerAttr getKernelOutputFeatureDimensionAttr(); + uint64_t getKernelOutputFeatureDimension(); + ::mlir::ArrayAttr getKernelSpatialDimensionsAttr(); + ::mlir::ArrayAttr getKernelSpatialDimensions(); + ::mlir::IntegerAttr getOutputBatchDimensionAttr(); + uint64_t getOutputBatchDimension(); + ::mlir::IntegerAttr getOutputFeatureDimensionAttr(); + uint64_t getOutputFeatureDimension(); + ::mlir::ArrayAttr getOutputSpatialDimensionsAttr(); + ::mlir::ArrayAttr getOutputSpatialDimensions(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class ConvolutionOpGenericAdaptor : public detail::ConvolutionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvolutionOpGenericAdaptorBase; +public: + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvolutionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvolutionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getKernel() { + return (*getODSOperands(1).begin()); + } + + ValueT getDst() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvolutionOpAdaptor : public ConvolutionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvolutionOpGenericAdaptor::ConvolutionOpGenericAdaptor; + ConvolutionOpAdaptor(ConvolutionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvolutionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::bufferization::BufferizableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvolutionOpAdaptor; + template + using GenericAdaptor = ConvolutionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_group_count"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("inputBatchDimension"), ::llvm::StringRef("inputFeatureDimension"), ::llvm::StringRef("inputSpatialDimensions"), ::llvm::StringRef("kernelInputFeatureDimension"), ::llvm::StringRef("kernelOutputFeatureDimension"), ::llvm::StringRef("kernelSpatialDimensions"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("outputBatchDimension"), ::llvm::StringRef("outputFeatureDimension"), ::llvm::StringRef("outputSpatialDimensions"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getInputBatchDimensionAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getInputBatchDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getInputFeatureDimensionAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getInputFeatureDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getInputSpatialDimensionsAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getInputSpatialDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getKernelInputFeatureDimensionAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getKernelInputFeatureDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getKernelOutputFeatureDimensionAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getKernelOutputFeatureDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getKernelSpatialDimensionsAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getKernelSpatialDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getOutputBatchDimensionAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getOutputBatchDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getOutputFeatureDimensionAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getOutputFeatureDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getOutputSpatialDimensionsAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getOutputSpatialDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(13); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 13); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(14); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 14); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(15); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 15); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(16); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 16); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.convolution"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::ShapedType> getInput(); + ::mlir::TypedValue<::mlir::ShapedType> getKernel(); + ::mlir::TypedValue<::mlir::ShapedType> getDst(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getKernelMutable(); + ::mlir::OpOperand &getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::IntegerAttr getInputBatchDimensionAttr(); + uint64_t getInputBatchDimension(); + ::mlir::IntegerAttr getInputFeatureDimensionAttr(); + uint64_t getInputFeatureDimension(); + ::mlir::ArrayAttr getInputSpatialDimensionsAttr(); + ::mlir::ArrayAttr getInputSpatialDimensions(); + ::mlir::IntegerAttr getKernelInputFeatureDimensionAttr(); + uint64_t getKernelInputFeatureDimension(); + ::mlir::IntegerAttr getKernelOutputFeatureDimensionAttr(); + uint64_t getKernelOutputFeatureDimension(); + ::mlir::ArrayAttr getKernelSpatialDimensionsAttr(); + ::mlir::ArrayAttr getKernelSpatialDimensions(); + ::mlir::IntegerAttr getOutputBatchDimensionAttr(); + uint64_t getOutputBatchDimension(); + ::mlir::IntegerAttr getOutputFeatureDimensionAttr(); + uint64_t getOutputFeatureDimension(); + ::mlir::ArrayAttr getOutputSpatialDimensionsAttr(); + ::mlir::ArrayAttr getOutputSpatialDimensions(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setInputBatchDimensionAttr(::mlir::IntegerAttr attr); + void setInputBatchDimension(uint64_t attrValue); + void setInputFeatureDimensionAttr(::mlir::IntegerAttr attr); + void setInputFeatureDimension(uint64_t attrValue); + void setInputSpatialDimensionsAttr(::mlir::ArrayAttr attr); + void setKernelInputFeatureDimensionAttr(::mlir::IntegerAttr attr); + void setKernelInputFeatureDimension(uint64_t attrValue); + void setKernelOutputFeatureDimensionAttr(::mlir::IntegerAttr attr); + void setKernelOutputFeatureDimension(uint64_t attrValue); + void setKernelSpatialDimensionsAttr(::mlir::ArrayAttr attr); + void setOutputBatchDimensionAttr(::mlir::IntegerAttr attr); + void setOutputBatchDimension(uint64_t attrValue); + void setOutputFeatureDimensionAttr(::mlir::IntegerAttr attr); + void setOutputFeatureDimension(uint64_t attrValue); + void setOutputSpatialDimensionsAttr(::mlir::ArrayAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value input, ::mlir::Value kernel, ::mlir::Value dst, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::IntegerAttr inputBatchDimension, ::mlir::IntegerAttr inputFeatureDimension, ::mlir::ArrayAttr inputSpatialDimensions, ::mlir::IntegerAttr kernelInputFeatureDimension, ::mlir::IntegerAttr kernelOutputFeatureDimension, ::mlir::ArrayAttr kernelSpatialDimensions, ::mlir::IntegerAttr outputBatchDimension, ::mlir::IntegerAttr outputFeatureDimension, ::mlir::ArrayAttr outputSpatialDimensions, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value input, ::mlir::Value kernel, ::mlir::Value dst, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, uint64_t inputBatchDimension, uint64_t inputFeatureDimension, ::mlir::ArrayAttr inputSpatialDimensions, uint64_t kernelInputFeatureDimension, uint64_t kernelOutputFeatureDimension, ::mlir::ArrayAttr kernelSpatialDimensions, uint64_t outputBatchDimension, uint64_t outputFeatureDimension, ::mlir::ArrayAttr outputSpatialDimensions, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 17 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() < 2; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 2; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (opOperand.getOperandNumber() < 2) return {}; + return {{getOperation()->getOpResult(0), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::ConvolutionOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::FftOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FftOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FftOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FftOpGenericAdaptorBase(FftOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getFftTypeAttr(); + uint32_t getFftType(); + ::mlir::ArrayAttr getFftLengthAttr(); + ::mlir::ArrayAttr getFftLength(); +}; +} // namespace detail +template +class FftOpGenericAdaptor : public detail::FftOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FftOpGenericAdaptorBase; +public: + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FftOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FftOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getDst() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FftOpAdaptor : public FftOpGenericAdaptor<::mlir::ValueRange> { +public: + using FftOpGenericAdaptor::FftOpGenericAdaptor; + FftOpAdaptor(FftOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FftOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::bufferization::BufferizableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FftOpAdaptor; + template + using GenericAdaptor = FftOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("fft_length"), ::llvm::StringRef("fft_type")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFftLengthAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFftLengthAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFftTypeAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFftTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.fft"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::ShapedType> getOperand(); + ::mlir::TypedValue<::mlir::ShapedType> getDst(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getFftTypeAttr(); + uint32_t getFftType(); + ::mlir::ArrayAttr getFftLengthAttr(); + ::mlir::ArrayAttr getFftLength(); + void setFftTypeAttr(::mlir::IntegerAttr attr); + void setFftType(uint32_t attrValue); + void setFftLengthAttr(::mlir::ArrayAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value operand, ::mlir::Value dst, ::mlir::IntegerAttr fft_type, ::mlir::ArrayAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value operand, ::mlir::Value dst, uint32_t fft_type, ::mlir::ArrayAttr fft_length); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 0; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 1; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (opOperand.getOperandNumber() == 0) return {}; + return {{getOperation()->getOpResult(0), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::FftOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::InfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + InfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + InfeedOpGenericAdaptorBase(InfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + ::mlir::ArrayAttr getLayoutAttr(); + ::std::optional< ::mlir::ArrayAttr > getLayout(); +}; +} // namespace detail +template +class InfeedOpGenericAdaptor : public detail::InfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InfeedOpGenericAdaptorBase; +public: + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + InfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getDst() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InfeedOpAdaptor : public InfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using InfeedOpGenericAdaptor::InfeedOpGenericAdaptor; + InfeedOpAdaptor(InfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class InfeedOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = InfeedOpAdaptor; + template + using GenericAdaptor = InfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("config"), ::llvm::StringRef("layout")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.infeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getDst(); + ::mlir::MutableOperandRange getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + ::mlir::ArrayAttr getLayoutAttr(); + ::std::optional< ::mlir::ArrayAttr > getLayout(); + void setConfigAttr(::mlir::StringAttr attr); + void setConfig(::llvm::StringRef attrValue); + void setLayoutAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeLayoutAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange dst, ::mlir::StringAttr config, /*optional*/::mlir::ArrayAttr layout); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange dst, ::llvm::StringRef config, /*optional*/::mlir::ArrayAttr layout); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return false; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return true; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + return {{getOperation()->getOpResult(0), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::InfeedOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::MemRefElementCastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MemRefElementCastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MemRefElementCastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MemRefElementCastOpGenericAdaptorBase(MemRefElementCastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class MemRefElementCastOpGenericAdaptor : public detail::MemRefElementCastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MemRefElementCastOpGenericAdaptorBase; +public: + MemRefElementCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MemRefElementCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MemRefElementCastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MemRefElementCastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSrc() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MemRefElementCastOpAdaptor : public MemRefElementCastOpGenericAdaptor<::mlir::ValueRange> { +public: + using MemRefElementCastOpGenericAdaptor::MemRefElementCastOpGenericAdaptor; + MemRefElementCastOpAdaptor(MemRefElementCastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MemRefElementCastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = MemRefElementCastOpAdaptor; + template + using GenericAdaptor = MemRefElementCastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.memref_element_cast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getSrc(); + ::mlir::OpOperand &getSrcMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getDst(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dst, ::mlir::Value src); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value src); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::MemRefElementCastOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::OutfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OutfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OutfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OutfeedOpGenericAdaptorBase(OutfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + ::mlir::ArrayAttr getResultTypeAttr(); + ::mlir::ArrayAttr getResultType(); +}; +} // namespace detail +template +class OutfeedOpGenericAdaptor : public detail::OutfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OutfeedOpGenericAdaptorBase; +public: + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OutfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OutfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OutfeedOpAdaptor : public OutfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using OutfeedOpGenericAdaptor::OutfeedOpGenericAdaptor; + OutfeedOpAdaptor(OutfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OutfeedOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = OutfeedOpAdaptor; + template + using GenericAdaptor = OutfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("config"), ::llvm::StringRef("result_type")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getResultTypeAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getResultTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.outfeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::MutableOperandRange getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + ::mlir::ArrayAttr getResultTypeAttr(); + ::mlir::ArrayAttr getResultType(); + void setConfigAttr(::mlir::StringAttr attr); + void setConfig(::llvm::StringRef attrValue); + void setResultTypeAttr(::mlir::ArrayAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operand, ::mlir::StringAttr config, ::mlir::ArrayAttr result_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operand, ::mlir::StringAttr config, ::mlir::ArrayAttr result_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operand, ::llvm::StringRef config, ::mlir::ArrayAttr result_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operand, ::llvm::StringRef config, ::mlir::ArrayAttr result_type); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return true; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return false; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + return {}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::OutfeedOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::PartitionIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PartitionIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PartitionIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PartitionIdOpGenericAdaptorBase(PartitionIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PartitionIdOpGenericAdaptor : public detail::PartitionIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PartitionIdOpGenericAdaptorBase; +public: + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PartitionIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PartitionIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PartitionIdOpAdaptor : public PartitionIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using PartitionIdOpGenericAdaptor::PartitionIdOpGenericAdaptor; + PartitionIdOpAdaptor(PartitionIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PartitionIdOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = PartitionIdOpAdaptor; + template + using GenericAdaptor = PartitionIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.partition_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +public: +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::PartitionIdOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::ReplicaIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReplicaIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReplicaIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReplicaIdOpGenericAdaptorBase(ReplicaIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReplicaIdOpGenericAdaptor : public detail::ReplicaIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReplicaIdOpGenericAdaptorBase; +public: + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReplicaIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReplicaIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReplicaIdOpAdaptor : public ReplicaIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReplicaIdOpGenericAdaptor::ReplicaIdOpGenericAdaptor; + ReplicaIdOpAdaptor(ReplicaIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReplicaIdOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReplicaIdOpAdaptor; + template + using GenericAdaptor = ReplicaIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.replica_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +public: +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::ReplicaIdOp) + +namespace mlir { +namespace xla_cpu { + +//===----------------------------------------------------------------------===// +// ::mlir::xla_cpu::RngBitGeneratorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RngBitGeneratorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RngBitGeneratorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RngBitGeneratorOpGenericAdaptorBase(RngBitGeneratorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::Attribute getRngAlgorithmAttr(); + ::mlir::Attribute getRngAlgorithm(); +}; +} // namespace detail +template +class RngBitGeneratorOpGenericAdaptor : public detail::RngBitGeneratorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RngBitGeneratorOpGenericAdaptorBase; +public: + RngBitGeneratorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RngBitGeneratorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RngBitGeneratorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RngBitGeneratorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getState() { + return (*getODSOperands(0).begin()); + } + + ValueT getDstState() { + return (*getODSOperands(1).begin()); + } + + ValueT getDst() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RngBitGeneratorOpAdaptor : public RngBitGeneratorOpGenericAdaptor<::mlir::ValueRange> { +public: + using RngBitGeneratorOpGenericAdaptor::RngBitGeneratorOpGenericAdaptor; + RngBitGeneratorOpAdaptor(RngBitGeneratorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RngBitGeneratorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::bufferization::BufferizableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = RngBitGeneratorOpAdaptor; + template + using GenericAdaptor = RngBitGeneratorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("rng_algorithm")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getRngAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getRngAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("xla_cpu.rng_bit_generator"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::ShapedType> getState(); + ::mlir::TypedValue<::mlir::ShapedType> getDstState(); + ::mlir::TypedValue<::mlir::ShapedType> getDst(); + ::mlir::OpOperand &getStateMutable(); + ::mlir::OpOperand &getDstStateMutable(); + ::mlir::OpOperand &getDstMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Attribute getRngAlgorithmAttr(); + ::mlir::Attribute getRngAlgorithm(); + void setRngAlgorithmAttr(::mlir::Attribute attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value state, ::mlir::Value dst_state, ::mlir::Value dst, ::mlir::Attribute rng_algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Declarations for BufferizableOpInterface: + bool bufferizesToMemoryRead(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() == 0; + } + bool bufferizesToMemoryWrite(OpOperand &opOperand, + const bufferization::AnalysisState &state) { + return opOperand.getOperandNumber() != 0; + } + bufferization::AliasingValueList getAliasingValues( + OpOperand &opOperand, const bufferization::AnalysisState &state) { + if (opOperand.getOperandNumber() == 0) return {}; + return {{getOperation()->getOpResult(opOperand.getOperandNumber()-1), + bufferization::BufferRelation::Equivalent}}; + } + LogicalResult bufferize(RewriterBase &rewriter, + const bufferization::BufferizationOptions &options); +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::RngBitGeneratorOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..79746d9a766d3bff0399c5eb3eee2e6aec9ce27d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_attrdefs.h.inc @@ -0,0 +1,40 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace xla_cpu { +class ReductionKindAttr; +namespace detail { +struct ReductionKindAttrStorage; +} // namespace detail +class ReductionKindAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ReductionKindAttr get(::mlir::MLIRContext *context, ::mlir::xla_cpu::ReductionKind value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"reduction_kind"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::xla_cpu::ReductionKind getValue() const; +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::ReductionKindAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..c2f82f26e914b8f98046a4b77ee437b387710705 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_dialect.h.inc @@ -0,0 +1,26 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: xla_cpu_dialect.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace xla_cpu { + +class XlaCpuDialect : public ::mlir::Dialect { + explicit XlaCpuDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~XlaCpuDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("xla_cpu"); + } +}; +} // namespace xla_cpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::xla_cpu::XlaCpuDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..ec0b11bb12a5eae440febc06fe2c2c3bf1c553ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir/xla_cpu/ir/xla_cpu_enums.h.inc @@ -0,0 +1,92 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: xla_cpu_enums.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace xla_cpu { +// Type of reduction to apply. +enum class ReductionKind : uint32_t { + ALL_REDUCE_SUM = 0, + ALL_REDUCE_PRODUCT = 1, + ALL_REDUCE_MIN = 2, + ALL_REDUCE_MAX = 3, +}; + +::std::optional symbolizeReductionKind(uint32_t); +::llvm::StringRef stringifyReductionKind(ReductionKind); +::std::optional symbolizeReductionKind(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForReductionKind() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(ReductionKind enumValue) { + return stringifyReductionKind(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeReductionKind(str); +} +} // namespace xla_cpu +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::xla_cpu::ReductionKind, ::mlir::xla_cpu::ReductionKind> { + template + static FailureOr<::mlir::xla_cpu::ReductionKind> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Type of reduction to apply."); + + // Symbolize the keyword. + if (::std::optional<::mlir::xla_cpu::ReductionKind> attr = ::mlir::xla_cpu::symbolizeEnum<::mlir::xla_cpu::ReductionKind>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Type of reduction to apply. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::xla_cpu::ReductionKind value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::xla_cpu::ReductionKind> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::xla_cpu::ReductionKind getEmptyKey() { + return static_cast<::mlir::xla_cpu::ReductionKind>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::xla_cpu::ReductionKind getTombstoneKey() { + return static_cast<::mlir::xla_cpu::ReductionKind>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::xla_cpu::ReductionKind &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::xla_cpu::ReductionKind &lhs, const ::mlir::xla_cpu::ReductionKind &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/deallocation/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/deallocation/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..183082fc54e04d4beb3eeaa40a1b3852e466a4ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/deallocation/transforms/passes.h @@ -0,0 +1,71 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H +#define MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H + +#include + +#include "mlir/Conversion/LLVMCommon/TypeConverter.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { +namespace deallocation { + +// Pass to split bufferization.alloc_tensor ops to optimize buffer reuse. +std::unique_ptr> +createSplitAllocTensorsPass(); + +// Pass to insert deallocations (in the form of `deallocation.retain`) ops. Most +// deallocations are typically converted to `memref.dealloc` by +// canonicalization. +std::unique_ptr> createDeallocatePass(); + +// Pass to annotate ops with debug information. +std::unique_ptr> +createDeallocationAnnotationPass(); + +// Pass to annotate buffer arguments with aliasing information. +std::unique_ptr> +createXlaBufferArgRewritePass(); + +// Pass to reuse buffers (hoisting, double buffering, dealloc/alloc +// coalescing). +std::unique_ptr> +createBufferReusePass(); + +// Lowers retain to SCF. +std::unique_ptr> +createDeallocationToScfPass(); + +// Convert `deallocation` ops to LLVM. +std::unique_ptr> +createConvertDeallocationOpsToLLVM(); + +std::unique_ptr> +createDeallocationSimplificationPass(); + +void populateDeallocationToLLVMConversionPatterns(LLVMTypeConverter& converter, + RewritePatternSet& patterns); + +#define GEN_PASS_REGISTRATION +#include "deallocation/transforms/passes.h.inc" + +} // namespace deallocation +} // namespace mlir + +#endif // MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/gml_st/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/gml_st/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..12b02debc705faf60b097b80bf9f522ccf10cf8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/gml_st/transforms/passes.h @@ -0,0 +1,251 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H +#define MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H + +#include +#include +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // IWYU pragma: keep +#include "mlir/IR/BuiltinOps.h" +#include "mlir/Pass/Pass.h" + +namespace mlir::gml_st { + +#define GEN_PASS_DECL +#include "gml_st/transforms/passes.h.inc" + +/// Pass to fuse producers into a tiled consumer. +std::unique_ptr> createFusionPass( + StringRef producer = "", StringRef consumer = ""); + +/// Pass to match, tile, and fuse softmax implementations. +std::unique_ptr> createTilingSoftmaxPass( + ArrayRef tileSizes); +std::unique_ptr> createTilingSoftmaxPass(); + +/// Pass to tile the root operation and to greedily fuse producers into it. +std::unique_ptr> createGreedyFusionPass( + ArrayRef tileSizes); +std::unique_ptr> createGreedyFusionPass(); + +// Pass to collapse dimensions of bcasts, reductions, and cwise ops. +std::unique_ptr> createCollapseShapePass(); +std::unique_ptr> createCollapseShapePass( + const CollapseShapePassOptions &options); + +// Pass to tile all tileable ops to size 1. +std::unique_ptr> createTileByOnePass(); + +/// Pass to compose tensor.extract_slice/insert_slice ops. +std::unique_ptr> +createComposeExtractInsertSlicePass(); + +/// Pass to vectorize compute ops and scf.for loops that are tiled perfectly. +std::unique_ptr> createVectorizeForCPUPass( + int64_t numElementsThreshold = 1024); + +/// Pass to vectorize `memref.copy`. +std::unique_ptr> createVectorizeCopyPass( + int64_t numElementsThreshold = 8); + +/// Pass to remove redundant `memref.copy` ops. +std::unique_ptr> createNaiveCopyRemovalPass(); + +/// Pass to gradually lower vector ops to SCF. +std::unique_ptr> createLowerVectorsPass( + bool enableAVX2 = true, bool flatten = false); + +/// Pass to pack linalg.matmul as linalg.mmt4d. +std::unique_ptr> createPackMatmulPass(); + +/// Pass to transform a thlo.scatter op for CPU backend. +std::unique_ptr> createTransformScatterForCpuPass(); + +/// Pass to transform a dot operation for CPU backend. +std::unique_ptr> createTransformDotForCpuPass( + ArrayRef tileSizes = {}, StringRef cpuName = ""); + +/// Pass to transform tensor.pack/unpack ops for CPU backend. +std::unique_ptr> createTransformPackForCpuPass(); + +/// Pass to transform a linalg.mmt4d op for CPU backend. +std::unique_ptr> createTransformMmt4DForCpuPass(); + +/// Pass to fuse linalg on tensor operations. +std::unique_ptr> createFusionOfTensorOpsPass(); + +/// Pass to convert ops on tensors with 1 element to scalar ops. +std::unique_ptr> createScalarizationPass( + bool scalarizeAllThlo = true); + +/// Pass to transform elementwise ops for CPU backend. +std::unique_ptr> +createTransformElementwiseForCpuPass(int64_t vectorSize = 8, + bool fuseDegenerateReshapes = false); + +/// Pass to transform a linalg.reduce op for CPU backend. +std::unique_ptr createTransformReduceForCpuPass( + const TransformReduceForCpuPassOptions &option = {}); + +/// Pass to create fusion clusters. +std::unique_ptr> +createFusionPlanningForCpuPass(int64_t vectorSize = 8); + +/// Pass to outline fusion regions into functions. +std::unique_ptr> createFusionOutliningPass(); + +/// Pass to inline fusion clusters. +std::unique_ptr> +createInlineFusionClustersPass(); + +/// Pass with canonicalization patterns for linalg ops. +std::unique_ptr> +createOptimizeLinalgOpsPass(); + +/// Pass to rewrite tensor.from_elements into tensor.insert. +std::unique_ptr> +createRewriteFromElementsOpPass(); + +/// Pass to rewrite scf.forall to scf.for. +std::unique_ptr> +createRewriteForallOpPass(); + +/// Pass to add debug info to be propagated into LLVM backend. +std::unique_ptr> createAddDebugInfoPass(); + +/// Pass to print stats about tileable ops. +std::unique_ptr> createCollectStatsPass( + int64_t level = 0); + +/// Pass to remove all transformed labels from tiled ops. +std::unique_ptr> +createRemoveLabelPass(); + +/// Populate pattern to remove single/zero iteration scf.forall dimensions. +void populateCollapseForallOpDimensionsPattern(RewritePatternSet &patterns); + +struct GmlStCPUTilingOptions + : public mlir::PassPipelineOptions { + GmlStCPUTilingOptions() = default; + GmlStCPUTilingOptions(const GmlStCPUTilingOptions &opts) { + this->lowerToMmt4d = opts.lowerToMmt4d; + this->matmulTileSizes = opts.matmulTileSizes; + this->reduction1DTileSize = opts.reduction1DTileSize; + this->reduction1DSplitRatio = opts.reduction1DSplitRatio; + this->reduction2DParallelDimTileSize = opts.reduction2DParallelDimTileSize; + this->reduction2DReductionDimTileSize = + opts.reduction2DReductionDimTileSize; + this->vectorSize = opts.vectorSize; + this->statsDetailLevel = opts.statsDetailLevel; + this->cpuName = opts.cpuName; + this->inlineFusionClusters = opts.inlineFusionClusters; + } + + Option vectorSize{*this, "vector-size", + llvm::cl::desc("Vector size for a 1D reduction."), + llvm::cl::init(8)}; + + Option reductionEnableHeuristic{ + *this, "reduction-enable-heuristic", + llvm::cl::desc("Enable tiling parameters heuristic for reductions."), + llvm::cl::init(false)}; + + Option reduction1DTileSize{ + *this, "reduction-1d-tile-size", + llvm::cl::desc("Tile size for a 1D reduction."), llvm::cl::init(32)}; + + Option reduction1DSplitRatio{ + *this, "reduction-1d-split-ratio", + llvm::cl::desc("Ratio used to split the reduction dimension"), + llvm::cl::init(8)}; + + Option reduction2DParallelDimTileSize{ + *this, "reduction-2d-parallel-dim-tile-size", + llvm::cl::desc("Tile size for the parallel dimension of a 2D reduction."), + llvm::cl::init(4)}; + + Option reduction2DReductionDimTileSize{ + *this, "reduction-2d-reduction-dim-tile-size", + llvm::cl::desc( + "Tile size for the reduction dimension of a 2D reduction."), + llvm::cl::init(4)}; + + ListOption matmulTileSizes{ + *this, "matmul-tile-sizes", + llvm::cl::desc("Tile sizes for `linalg.matmul`. Leave empty to determine " + "sizes automatically."), + llvm::cl::list_init({}), llvm::cl::ZeroOrMore}; + + Option vectorizationSizeThreshold{ + *this, "vectorization-size-threshold", + llvm::cl::desc("Threshold size for vectorization."), llvm::cl::init(128)}; + + Option vectorizationTiledSizeThreshold{ + *this, "vectorization-tiled-size-threshold", + llvm::cl::desc("Threshold size for vectorization after tiling."), + llvm::cl::init(1024)}; + + Option lowerToMmt4d{ + *this, "lower-to-mmt4d", + llvm::cl::desc("Enable the specific code generation (packing) for matmul " + "operations."), + llvm::cl::init(false)}; + + Option cpuName{ + *this, "cpu", + llvm::cl::desc("CPU name, similar to llc's -mcpu flag. e.g. 'znver2', " + "'skylake-avx512'."), + llvm::cl::init("")}; + + Option statsDetailLevel{ + *this, "stats-detail-level", + llvm::cl::desc("Detail level for collecting IR statistics."), + llvm::cl::init(0)}; + + Option fuseDegenerateReshapes{ + *this, "fuse-degenerate-reshapes", + llvm::cl::desc("Fuse through tensor.expand/collapse_shape"), + llvm::cl::init(false)}; + + Option inlineFusionClusters{ + *this, "inline-fusion-clusters", + llvm::cl::desc("Inline fusion clusters at the end of the pipeline."), + llvm::cl::init(true)}; +}; + +// Returns default "optimized" tiling parameters. +GmlStCPUTilingOptions getDefaultCPUPipelineOptions( + StringRef cpuName, int64_t statsDetailLevel = 0); + +// Adds tiling-fusion-vectorization passes for tHLO/Linalg ops mix. +void addCPUTilingPipeline(OpPassManager &pm, + const GmlStCPUTilingOptions &options); + +// Adds tiling-fusion-vectorization passes for tHLO/Linalg ops mix with the +// "optimized" tiling parameters. +void addDefaultCPUTilingPipeline(OpPassManager &pm, StringRef cpuName, + int64_t statsDetailLevel = 0); + +#define GEN_PASS_REGISTRATION +#include "gml_st/transforms/passes.h.inc" + +} // namespace mlir::gml_st + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/lhlo/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/lhlo/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..8225dfa238ccf23fd62df4da5e2c812033a29a3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/lhlo/transforms/passes.h @@ -0,0 +1,65 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_LHLO_TRANSFORMS_PASSES_H +#define MLIR_HLO_LHLO_TRANSFORMS_PASSES_H + +#include + +#include "llvm/ADT/ArrayRef.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { + +class ModuleOp; +class Operation; +template +class OperationPass; +class Pass; +namespace func { +class FuncOp; +} // namespace func +namespace lmhlo { +class FusionOp; +} // namespace lmhlo + +namespace lmhlo { + +#define GEN_PASS_DECL +#include "lhlo/transforms/lmhlo_passes.h.inc" + +// Lowers from LHLO dialect to Affine dialect. +std::unique_ptr> createLhloLegalizeToAffinePass(); + +// Lowers from LHLO dialect to GPU dialect. +std::unique_ptr> createLegalizeToGpuPass(); + +// Lowers from LHLO dialect to parallel loops. +std::unique_ptr> +createLegalizeLhloToParallelLoopsPass(); + +// Legalizes tensor load ops that are inserted during mhlo to lmhlo conversion. +std::unique_ptr> createLegalizeToTensorOpPass(); + +// Input inline fusion pass for fusion codegen +std::unique_ptr> createInputInlineFusionPass(); + +#define GEN_PASS_REGISTRATION +#include "lhlo/transforms/lmhlo_passes.h.inc" + +} // namespace lmhlo +} // namespace mlir + +#endif // MLIR_HLO_LHLO_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/mhlo/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/mhlo/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..946c56ae18ab1bad1ac6995caa83cc7b6f8ba935 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/mhlo/transforms/passes.h @@ -0,0 +1,212 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_MHLO_TRANSFORMS_PASSES_H +#define MLIR_HLO_MHLO_TRANSFORMS_PASSES_H + +#include +#include + +#include "mlir/Pass/Pass.h" + +namespace mlir { + +class ModuleOp; +class Operation; +template +class OperationPass; +class Pass; +namespace func { +class FuncOp; +} // namespace func +namespace lmhlo { +class FusionOp; +} // namespace lmhlo + +namespace mhlo { + +#define GEN_PASS_DECL +#include "mhlo/transforms/mhlo_passes.h.inc" + +/// Lowers HLO control flow ops to SCF. +std::unique_ptr> createLegalizeControlFlowPass(); + +/// Lowers sort to SCF & arith. +std::unique_ptr> createLegalizeSortPass(); + +/// Lowers from HLO dialect to Standard dialect. +std::unique_ptr> createLegalizeToStdPass(); + +/// Lowers from the CHLO dialect to the HLO dialect. +std::unique_ptr> createChloLegalizeToHloPass( + bool legalizeBroadcasts = true, bool expandCompositions = true); + +// Lowers from sparse ops in CHLO dialect to Linalg dialect. +std::unique_ptr> createLegalizeSparseOperationsPass( + bool legalizeToCustomCalls = true); + +// Canonicalize reduction ops to be suitable for codegen. +std::unique_ptr> +createHloCanonicalizeReductionPass(); + +// Expand feature rich mhlo ops to simpler mhlo ops. +std::unique_ptr> +createMhloExpandOpsSimplifierPass(); + +// Rewrites scatter into transposes, reshapes and a simpler scatter. +std::unique_ptr> createHloCanonicalizeScatterPass(); + +// Rewrites gather into transposes, reshapes and a simpler gather. +std::unique_ptr> createHloCanonicalizeGatherPass(); + +// Rewrites dot operands that contain unit dimension. +std::unique_ptr> createHloCanonicalizeDotPass(); + +/// Lowers from HLO dialect to LHLO dialect allocating/deallocating temporary +/// buffers if necessary. +std::unique_ptr> createLegalizeToLhloPass(); + +/// Lowers from HLO dialect to Memref dialect allocating/deallocating temporary +/// buffers if necessary. +std::unique_ptr> createLegalizeToMemrefPass(); + +/// Lowers from HLO dialect to Arithmetic dialect. +std::unique_ptr> createLegalizeToArithmeticPass(); + +// Lowers shape operations from HLO dialect to Standard dialect. +std::unique_ptr> +createLegalizeHloShapeOpsToStandardPass(); + +/// Lowers from MHLO dialect to THLO dialect. +std::unique_ptr> createLegalizeMHLOToTHLOPass( + bool enableExperimentalOps = false); + +/// Lowers from HLO dialect to Linalg dialect. +std::unique_ptr> createLegalizeHloToLinalgPass( + bool enablePrimitiveOps = false); + +/// Lowers from HLO dialects dim operations. +std::unique_ptr> +createLegalizeShapeComputationsPass(); + +// Sinks constants implicitly captured in control flow regions. This is +// necessary to export to XLA. +std::unique_ptr> +createSinkConstantsToControlFlowPass(); + +/// Lowers trigonometric operations from the standard dialect to approximations +/// that do not use intrinsics. +std::unique_ptr> +createLegalizeTrigonometricToApproximationPass(); + +// Move dynamic broadcasts up over element-wise operations and broadcast the +// operands rather than the result. This will eventually allow for larger +// fusions. +std::unique_ptr> createBroadcastPropagationPass(); + +// Transformations that helps in restricting maximum rank among tensors in the +// pass. +std::unique_ptr> createRestrictMaxRankPass(); + +// Prepare moving dynamic broadcasts up over element-wise operations and +// broadcast the operands rather than the result. This will eventually allow for +// larger fusions. +std::unique_ptr> createMergeAssumingOpsPass(); + +// Iteratively reifies all shape computations in the function. +std::unique_ptr> createShapeReificationPass(); + +/// Creates a pass to analyze shapes and to use that information for +/// shape-related optimizations. +std::unique_ptr> +createSymbolicShapeOptimizationPass(); + +// Pass to simplify shape ops. +std::unique_ptr> createShapeSimplification(); + +// Fuse shape constraints and merge all assuming regions. +std::unique_ptr> createConstraintFusionPass(); + +// Group reduction and parallel dimensions of reduction operations and realize +// them through equivalent 1D or 2D reductions. +std::unique_ptr> createGroupReductionDimensionsPass( + bool preferColumnsReductions = true); + +/// Rank specialization passes: +/// - Find compatible operations and group them together in one rank +/// specialization cluster. +/// - Lower rank specialization clusters to SCF and ranked operations. +std::unique_ptr> +createRankSpecializationClusterPass(); +std::unique_ptr> createRankSpecializationToSCFPass( + int64_t maxTargetRank = 5); + +std::unique_ptr> createOptimizeMhloPass(); +std::unique_ptr> createLowerComplexPass(); + +std::unique_ptr> +createLegalizeBroadcastToBroadcastInDimPass(); +std::unique_ptr<::mlir::Pass> createLegalizeGeneralDotPass(); +std::unique_ptr> +createLegalizeCreateTokenToAfterAllPass(); +std::unique_ptr> +createLegalizeCrossReplicaSumToAllReducePass(); +std::unique_ptr> +createLegalizeDotGeneralToDotPass(); +std::unique_ptr> +createLegalizeDotToDotGeneralPass(); +std::unique_ptr> +createLegalizeEinsumToDotGeneralPass(); +std::unique_ptr> +createLegalizeGatherToTorchIndexSelectPass(); +std::unique_ptr> +createLegalizeTorchIndexSelectToGatherPass(); +std::unique_ptr> createFlattenTuplePass(); + +// Creates a pass for expanding mhlo.tuple ops. +std::unique_ptr> createExpandHloTuplesPass( + const std::string& entryFunctionName = "main"); + +// Creates a pass for collapsing the mhlo.map if the map only has elementwise +// op. +std::unique_ptr> createCollapseElementwiseMapPass(); + +// Pass to replace unsigned types with signless integers. +std::unique_ptr> createConvertToSignlessPass(); + +/// Creates pass for rewriting sparse mhlo ops. +std::unique_ptr> createSparseRewritingPass(); + +// Legalizes from the MHLO dialect to the StableHLO dialect. +std::unique_ptr> createHloLegalizeToStablehloPass(); + +// Legalizes from the StableHLO dialect to the MHLO dialect. +std::unique_ptr> createStablehloLegalizeToHloPass(); + +// Legalizes from the Shape dialect to the MHLO dialect. +std::unique_ptr> createShapeLegalizeToHloPass(); + +// Test passes. +std::unique_ptr createTestInferShapedTypeMethodsPass(); +std::unique_ptr createTestMaterializeBroadcastsPass(); +std::unique_ptr createTestUnfuseBatchNormPass(); + +#define GEN_PASS_REGISTRATION +#include "mhlo/transforms/mhlo_passes.h.inc" + +} // namespace mhlo +} // namespace mlir + +#endif // MLIR_HLO_MHLO_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/thlo/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/thlo/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..7ac8499f71474289d54fa8dc1d03bd610647edf9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/thlo/transforms/passes.h @@ -0,0 +1,46 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_THLO_TRANSFORMS_PASSES_H +#define MLIR_HLO_THLO_TRANSFORMS_PASSES_H + +#include + +#include "mlir/Pass/Pass.h" + +namespace mlir { + +template +class OperationPass; + +namespace func { +class FuncOp; +} // namespace func + +namespace thlo { + +#define GEN_PASS_DECL_THLOLEGALIZESORTPASS +#include "thlo/transforms/thlo_passes.h.inc" + +/// Lowers sort to Arith, MemRef, and SCF +std::unique_ptr> createLegalizeSortPass(); + +#define GEN_PASS_REGISTRATION +#include "thlo/transforms/thlo_passes.h.inc" + +} // namespace thlo +} // namespace mlir + +#endif // MLIR_HLO_THLO_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..d18c60320525faec6d36fbf74c699925cbbf8367 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/all_passes/transforms/passes.h @@ -0,0 +1,126 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_TRANSFORMS_PASSES_H +#define MLIR_HLO_TRANSFORMS_PASSES_H + +#include +#include + +#include "mlir/Pass/Pass.h" + +namespace mlir { +class ModuleOp; +class MLIRContext; +class ConversionTarget; +class DialectRegistry; +class PassManager; + +namespace func { +class FuncOp; +} // namespace func +namespace bufferization { +class BufferizeTypeConverter; +} // namespace bufferization + +using BufferizeDialectsCallback = std::function; +using BufferizePatternsCallback = std::function; + +//===----------------------------------------------------------------------===// +// Passes +//===----------------------------------------------------------------------===// + +#define GEN_PASS_DECL_BUFFERPACKING +#define GEN_PASS_DECL_FINALBUFFERIZEPASS +#define GEN_PASS_DECL_PROPAGATESTATICSHAPESTOKERNELPASS +#define GEN_PASS_DECL_TILELOOPSPASS +#define GEN_PASS_DECL_GENERICHOSTTOLLVMPASS +#include "transforms/passes.h.inc" + +/// Creates a pass that merges smaller buffer into bigger buffer to optimize +/// memory consumption. +std::unique_ptr> createBufferPackingPass( + unsigned windowSize = 5); + +/// Creates a pass that tests the useranges of the UserangeAnalysis. +std::unique_ptr> createTestUserangePass(); + +/// Creates a pass that prints the analysis results of ShapeComponentsAnalysis. +std::unique_ptr> +createTestShapeComponentAnalysisPass(); + +/// Creates a pass that computes the allocated memory. +std::unique_ptr> createMemoryCountPass(); + +// Pass to lower index cast on tensors to tensor dialect. +std::unique_ptr> createLowerIndexCastPass(); + +// Pass to tranform compute computations (hlo and linalg) on values to their +// corresponding counterparts on buffers. Also bufferizes function signatures. +std::unique_ptr> createComputeOpAndFuncBufferizePass(); + +// Pass to tranform computations on values to their corresponding parts on +// buffers. +std::unique_ptr> createFinalBufferizePass(); + +std::unique_ptr> createFinalBufferizePass( + uint64_t alignment, BufferizeDialectsCallback dc = {}, + BufferizePatternsCallback pc = {}); + +// Pass to propagate static shapes to kernel, reducing the kernel arguments +// from a flattened memref to a single pointer. The pointer is converted to +// `pointer_type`, if provided. +std::unique_ptr> +createPropagateStaticShapesToKernelPass(Type pointerType = {}); + +// Creates a pass for collapsing multidimensional parallel loops into 1D loops. +std::unique_ptr> createCollapseParallelLoopsTo1DPass(); + +// Creates a TileLoopsPass with tiles sizes provided through `tile_sizes` +// and unroll factors provided through `unroll_factors`. +std::unique_ptr> createTileLoopsPass( + ArrayRef tileSizes = {}, ArrayRef unrollFactors = {}); + +// Detensorizes loop-carried variables and block arguments of scf.while, scf.for +// and scf.if. +std::unique_ptr> createDetensorizeScfOpsPass(); + +/// Registers the test pass for erasing transform dialect ops. +void registerTestHloTransformDialectEraseSchedulePass(); + +/// Registers the test pass for applying transform dialect ops. +void registerTestHloTransformDialectInterpreterPass(); + +namespace hlo { +std::unique_ptr> createOneShotBufferizePass(); + +std::unique_ptr> createGenericHostToLLVMPass( + const GenericHostToLLVMPassOptions& options = {}); + +std::unique_ptr> createUnbufferizePass(); +std::unique_ptr> createAllocToArgPass(); + +// Unrolls scf.for loops with static iteration count no larger than 8. +std::unique_ptr createUnrollLoopsPass(); + +#define GEN_PASS_REGISTRATION +#include "transforms/passes.h.inc" + +} // namespace hlo +} // namespace mlir + +#endif // MLIR_HLO_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/chlo_legalize_to_hlo/mhlo/transforms/rewriters.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/chlo_legalize_to_hlo/mhlo/transforms/rewriters.h new file mode 100644 index 0000000000000000000000000000000000000000..2d5bbfa8887653582238e8e4985f31aa16393ee9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/chlo_legalize_to_hlo/mhlo/transforms/rewriters.h @@ -0,0 +1,231 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H +#define MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H + +#include +#include + +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +namespace bufferization { +class BufferizeTypeConverter; +} // namespace bufferization +namespace mhlo { + +// Rewrite patterns for broadcast to equivalent broadcast_in_dim legalization. +void populateBroadcastToBroadcastInDimPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering a general dot product. +void populateGeneralDotOpLoweringPatterns(RewritePatternSet *patterns, + MLIRContext *ctx); + +// Collection of rewrite patterns for lowering complex operations to equivalent +// float operations. +void populateComplexLoweringPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +void populateOptimizeMhloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for create_token to equivalent after_all legalization. +void populateCreateTokenToAfterAllPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for cross-replica-sum to equivalent all_reduce legalization. +void populateCrossReplicaSumToAllReducePatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for dot to equivalent dot_general legalization. +void populateDotToDotGeneralPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for einsum to equivalent dot_general legalization. +void populateEinsumToDotGeneralPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for gather to equivalent torch index select legalization. +void populateGatherToTorchIndexSelectPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for torch index select to equivalent gather legalization. +void populateTorchIndexSelectToGatherPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +void populateMhloToStdPatterns(RewritePatternSet *patterns, MLIRContext *ctx); + +// Collection of rewrite patterns for lowering all mhlo ops to their +// lmhlo counterparts. +void populateDynamicHloToLhloConversionPattern( + MLIRContext *context, bufferization::BufferizeTypeConverter *converter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to LHLO dialect. +void populateHloToLhloConversionPattern( + MLIRContext *context, bufferization::BufferizeTypeConverter *converter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to arithmetic dialect. +void populateHloToArithmeticConversionPatterns(RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering pointwise HLO ops with scalar +// arguments to arithmetic dialect. +void populateScalarHloToArithmeticConversionPatterns( + MLIRContext *context, TypeConverter &typeConverter, + RewritePatternSet *patterns, + llvm::function_ref filterFn = nullptr); + +// Collection of rewrite patterns for lowering of shape operations from the HLO +// dialect to the standard dialect. +void populateHloShapeOpsToStandardConversionPattern( + MLIRContext *context, TypeConverter &typeConverter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to Linalg dialect. +void populateHloToLinalgConversionPattern(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns, + bool enablePrimitiveOps = false); + +// Collection of rewrite patterns for lowering of HLO dim operations. +void populateShapeComputationPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Converter to signless intergers to be used with linalg conversion patterns. +std::unique_ptr createHloToLinalgTypeConverter(); + +// Sets up legality definitions for materializing broadcasts. +void setupMaterializeBroadcastsLegality(MLIRContext *context, + ConversionTarget *conversionTarget); + +// Populates a collection of rewrite patterns for materializing broadcast +// attributes to equivalent sequences of ops. +void populateMaterializeBroadcastsPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populates a collection of rewrite patterns to realize element-wise operations +// on ranked tensors where possible. +void populateTransformUnrankedHloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +void populateDynamicShapeFusionPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// batch_norm_inference into constituent HLO ops. +void populateUnfuseBatchNormInferencePattern(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// batch_norm_training into constituent HLO ops. +void populateUnfuseBatchNormTrainingPattern(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// // batch_norm_inference and batch_norm_training into constituent HLO ops. +inline void populateUnfuseBatchNormPatterns(MLIRContext *context, + RewritePatternSet *patterns) { + populateUnfuseBatchNormInferencePattern(context, patterns); + populateUnfuseBatchNormTrainingPattern(context, patterns); +} + +// Populates patterns that translate the trigonometric operations from the +// standard dialect to approximations that do not use intrinsics. +void populateTrigonometricToApproximationPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate patterns to prepare moving dynamic broadcasts up over element-wise +// operations and broadcast the operands rather than the result. This will +// eventually allow for larger fusions. +void populateMergeAssumingOpsPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate patterns for iterative shape reification. +void populateShapeReificationPatterns(MLIRContext *, RewritePatternSet *); + +// Populate patterns to group reduction and parallel dimensions of reduction +// operations and realize them through equivalent 1D or 2D reductions. +void populateGroupReductionDimensionsPatterns(MLIRContext *context, + RewritePatternSet *patterns, + bool preferColumnsReductions); + +/// Populate rank specialization clustering and lowering patterns. +void populateRankSpecializationClusterPatterns(MLIRContext *context, + RewritePatternSet *patterns); +void populateRankSpecializationToSCFPatterns(MLIRContext *context, + RewritePatternSet *patterns, + int64_t maxTargetRank); + +/// Populate sparse tensor specific rewriting patterns. +void populateSparseRewritingPatterns(RewritePatternSet *patterns, + MLIRContext *ctx); + +/// Populates sparse ops in CHLO to linalg rewriting patterns. +void populateLegalizeSparseCHLOPatterns(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns); + +/// Populate sparse ops to mhlo.CustomCall patterns. +void populateLegalizeSparseOpsToCustomCallPatterns(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns); + +} // namespace mhlo + +namespace chlo { + +// Populates a collection of conversion patterns for legalizing broadcasting +// client-HLO to their non-broadcasting counterparts. +void populateChloBroadcastingPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populates a collection of conversion patterns for legalizing client-HLO to +// HLO by decomposing client-operations to corresponding sequences of more +// primitive operations. This does not include the +// PopulateChloBroadcastingPatterns above. +void populateDecomposeChloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +} // namespace chlo + +namespace stablehlo { + +// Populates MHLO ops to StableHLO ops rewriting patterns. +// Also see `stablehlo::registerFuncOpsForTypeConversion` for helper patterns +// which make sure `func.func`, `func.call` and `func.return` which involve +// illegal types also get converted. +void populateHloToStablehloPatterns(RewritePatternSet *patterns, + TypeConverter *converter, + MLIRContext *context, + bool allowExperimentalFeatures); + +// Populates StableHLO ops to MHLO ops rewriting patterns. +// Also see `stablehlo::registerFuncOpsForTypeConversion` for helper patterns +// which make sure `func.func`, `func.call` and `func.return` which involve +// illegal types also get converted. +void populateStablehloToHloPatterns(RewritePatternSet *patterns, + TypeConverter *converter, + MLIRContext *context); + +} // namespace stablehlo + +} // namespace mlir + +#endif // MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/convert_op_folder/utils/convert_op_folder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/convert_op_folder/utils/convert_op_folder.h new file mode 100644 index 0000000000000000000000000000000000000000..1186a3014c12577c26acd6ca64bfb2cdf1e45d10 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/convert_op_folder/utils/convert_op_folder.h @@ -0,0 +1,33 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_UTILS_CONVERT_OP_FOLDER_H +#define MLIR_HLO_UTILS_CONVERT_OP_FOLDER_H + +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/IR/BuiltinTypes.h" + +namespace mlir { +namespace hlo { + +// Converts the given elements attr to the specified elements type. +// Requires type of the elements and new_type to be either integer or float +// type. +mlir::ElementsAttr convertElementsAttr(const mlir::ElementsAttr& elements, + mlir::Type newType); +} // namespace hlo +} // namespace mlir + +#endif // MLIR_HLO_UTILS_CONVERT_OP_FOLDER_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation/deallocation/IR/deallocation_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation/deallocation/IR/deallocation_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..74dec9c2e8ee43889160d977293590655d7d7b30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation/deallocation/IR/deallocation_ops.h @@ -0,0 +1,37 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_DEALLOACTION_DEALLOCATION_OPS_H +#define MLIR_HLO_DEALLOACTION_DEALLOCATION_OPS_H + +#include "mlir/Bytecode/BytecodeOpInterface.h" +#include "mlir/IR/Attributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/IR/OpImplementation.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" + +#define GET_TYPEDEF_CLASSES +#include "deallocation/IR/deallocation_typedefs.h.inc" +#undef GET_TYPEDEF_CLASSES + +#define GET_OP_CLASSES +#include "deallocation/IR/deallocation_dialect.h.inc" +#include "deallocation/IR/deallocation_ops.h.inc" +#undef GET_OP_CLASSES + +#endif // MLIR_HLO_DEALLOACTION_DEALLOCATION_OPS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..9f448a9f30aa6ddba72c87ee83a2a8168ea7698f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_dialect.h.inc @@ -0,0 +1,33 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: deallocation_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace deallocation { + +class DeallocationDialect : public ::mlir::Dialect { + explicit DeallocationDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~DeallocationDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("deallocation"); + } + + /// Parse a type registered to this dialect. + ::mlir::Type parseType(::mlir::DialectAsmParser &parser) const override; + + /// Print a type registered to this dialect. + void printType(::mlir::Type type, + ::mlir::DialectAsmPrinter &os) const override; +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::DeallocationDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..fa935dae952a569a500bab6e0ec7e0fcdf56a4d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_ops.h.inc @@ -0,0 +1,567 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: deallocation_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace deallocation { +class FreeOp; +} // namespace deallocation +} // namespace mlir +namespace mlir { +namespace deallocation { +class GetBufferOp; +} // namespace deallocation +} // namespace mlir +namespace mlir { +namespace deallocation { +class NullOp; +} // namespace deallocation +} // namespace mlir +namespace mlir { +namespace deallocation { +class OwnOp; +} // namespace deallocation +} // namespace mlir +namespace mlir { +namespace deallocation { +class RetainOp; +} // namespace deallocation +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace deallocation { + +//===----------------------------------------------------------------------===// +// ::mlir::deallocation::FreeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FreeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FreeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FreeOpGenericAdaptorBase(FreeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class FreeOpGenericAdaptor : public detail::FreeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FreeOpGenericAdaptorBase; +public: + FreeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FreeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FreeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FreeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getAlloc() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FreeOpAdaptor : public FreeOpGenericAdaptor<::mlir::ValueRange> { +public: + using FreeOpGenericAdaptor::FreeOpGenericAdaptor; + FreeOpAdaptor(FreeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FreeOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = FreeOpAdaptor; + template + using GenericAdaptor = FreeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("deallocation.free"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::deallocation::OwnershipIndicatorType> getAlloc(); + ::mlir::OpOperand &getAllocMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value alloc); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value alloc); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::FreeOp) + +namespace mlir { +namespace deallocation { + +//===----------------------------------------------------------------------===// +// ::mlir::deallocation::GetBufferOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GetBufferOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GetBufferOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GetBufferOpGenericAdaptorBase(GetBufferOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class GetBufferOpGenericAdaptor : public detail::GetBufferOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GetBufferOpGenericAdaptorBase; +public: + GetBufferOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GetBufferOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GetBufferOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GetBufferOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getAlloc() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GetBufferOpAdaptor : public GetBufferOpGenericAdaptor<::mlir::ValueRange> { +public: + using GetBufferOpGenericAdaptor::GetBufferOpGenericAdaptor; + GetBufferOpAdaptor(GetBufferOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GetBufferOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GetBufferOpAdaptor; + template + using GenericAdaptor = GetBufferOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("deallocation.get_buffer"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getAlloc(); + ::mlir::OpOperand &getAllocMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::IndexType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value alloc); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value alloc); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::GetBufferOp) + +namespace mlir { +namespace deallocation { + +//===----------------------------------------------------------------------===// +// ::mlir::deallocation::NullOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class NullOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + NullOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + NullOpGenericAdaptorBase(NullOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class NullOpGenericAdaptor : public detail::NullOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::NullOpGenericAdaptorBase; +public: + NullOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + NullOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : NullOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + NullOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class NullOpAdaptor : public NullOpGenericAdaptor<::mlir::ValueRange> { +public: + using NullOpGenericAdaptor::NullOpGenericAdaptor; + NullOpAdaptor(NullOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class NullOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = NullOpAdaptor; + template + using GenericAdaptor = NullOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("deallocation.null"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::deallocation::OwnershipIndicatorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::NullOp) + +namespace mlir { +namespace deallocation { + +//===----------------------------------------------------------------------===// +// ::mlir::deallocation::OwnOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OwnOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OwnOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OwnOpGenericAdaptorBase(OwnOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class OwnOpGenericAdaptor : public detail::OwnOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OwnOpGenericAdaptorBase; +public: + OwnOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OwnOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OwnOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OwnOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMemref() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OwnOpAdaptor : public OwnOpGenericAdaptor<::mlir::ValueRange> { +public: + using OwnOpGenericAdaptor::OwnOpGenericAdaptor; + OwnOpAdaptor(OwnOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OwnOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = OwnOpAdaptor; + template + using GenericAdaptor = OwnOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("deallocation.own"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::BaseMemRefType> getMemref(); + ::mlir::OpOperand &getMemrefMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::deallocation::OwnershipIndicatorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value memref); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value memref); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value memref); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::OwnOp) + +namespace mlir { +namespace deallocation { + +//===----------------------------------------------------------------------===// +// ::mlir::deallocation::RetainOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RetainOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RetainOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RetainOpGenericAdaptorBase(RetainOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RetainOpGenericAdaptor : public detail::RetainOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RetainOpGenericAdaptorBase; +public: + RetainOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RetainOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RetainOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RetainOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getRetained() { + return getODSOperands(0); + } + + RangeT getAllocs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RetainOpAdaptor : public RetainOpGenericAdaptor<::mlir::ValueRange> { +public: + using RetainOpGenericAdaptor::RetainOpGenericAdaptor; + RetainOpAdaptor(RetainOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RetainOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = RetainOpAdaptor; + template + using GenericAdaptor = RetainOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("operandSegmentSizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("deallocation.retain"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getRetained(); + ::mlir::Operation::operand_range getAllocs(); + ::mlir::MutableOperandRange getRetainedMutable(); + ::mlir::MutableOperandRange getAllocsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Operation::result_range getResultAllocs(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange result_allocs, ::mlir::ValueRange retained, ::mlir::ValueRange allocs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::RetainOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_typedefs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_typedefs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..0202436a6b483d4e71d2850143aa982a4ac15122 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_ops_inc_gen/deallocation/IR/deallocation_typedefs.h.inc @@ -0,0 +1,33 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* TypeDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_TYPEDEF_CLASSES +#undef GET_TYPEDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace deallocation { +class OwnershipIndicatorType; +class OwnershipIndicatorType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"ownership"}; + } + +}; +} // namespace deallocation +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::deallocation::OwnershipIndicatorType) + +#endif // GET_TYPEDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..aefb8ff03ce03d5e9a24e0f6d3bb5db051567534 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/analysis.h @@ -0,0 +1,58 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef MLIR_HLO_DEALLOCATION_TRANSFORMS_ANALYSIS_H +#define MLIR_HLO_DEALLOCATION_TRANSFORMS_ANALYSIS_H + +#include "deallocation/utils/util.h" +#include "mlir/IR/Value.h" + +namespace mlir { +namespace deallocation { + +class DeallocationAnalysis { + public: + // Returns the set of all possible values that may back the given value. A + // value `A` is considered to back another value `B` if + // a) `A` is an alloc or a bbarg + // b) `B` depends on `A` (possibly indirectly) + // + // For example, in this IR: + // + // func.func @foo(%arg0: memref) -> memref { + // %c0 = arith.constant 0 : index + // %c4 = arith.constant 4 : index + // %c1 = arith.constant 1 : index + // %ret = scf.for %i = %c0 to %c4 step %c1 iter_args(%x = %arg0) + // -> memref { + // %y = some.op(%x) : memref -> memref + // scf.yield %y : memref + // } + // func.return %ret : memref + // } + // + // `getBackingMemory(%ret)` is {`%arg0`, `%x`, `%y`}. + const breaks_if_you_move_ops::ValueSet& getBackingMemory(Value source); + + private: + void collectBackingMemory(Value source, DenseSet& visited, + breaks_if_you_move_ops::ValueSet& results); + + DenseMap backingMemory; +}; + +} // namespace deallocation +} // namespace mlir + +#endif // MLIR_HLO_DEALLOCATION_TRANSFORMS_ANALYSIS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..183082fc54e04d4beb3eeaa40a1b3852e466a4ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes/deallocation/transforms/passes.h @@ -0,0 +1,71 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H +#define MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H + +#include + +#include "mlir/Conversion/LLVMCommon/TypeConverter.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { +namespace deallocation { + +// Pass to split bufferization.alloc_tensor ops to optimize buffer reuse. +std::unique_ptr> +createSplitAllocTensorsPass(); + +// Pass to insert deallocations (in the form of `deallocation.retain`) ops. Most +// deallocations are typically converted to `memref.dealloc` by +// canonicalization. +std::unique_ptr> createDeallocatePass(); + +// Pass to annotate ops with debug information. +std::unique_ptr> +createDeallocationAnnotationPass(); + +// Pass to annotate buffer arguments with aliasing information. +std::unique_ptr> +createXlaBufferArgRewritePass(); + +// Pass to reuse buffers (hoisting, double buffering, dealloc/alloc +// coalescing). +std::unique_ptr> +createBufferReusePass(); + +// Lowers retain to SCF. +std::unique_ptr> +createDeallocationToScfPass(); + +// Convert `deallocation` ops to LLVM. +std::unique_ptr> +createConvertDeallocationOpsToLLVM(); + +std::unique_ptr> +createDeallocationSimplificationPass(); + +void populateDeallocationToLLVMConversionPatterns(LLVMTypeConverter& converter, + RewritePatternSet& patterns); + +#define GEN_PASS_REGISTRATION +#include "deallocation/transforms/passes.h.inc" + +} // namespace deallocation +} // namespace mlir + +#endif // MLIR_HLO_DEALLOCATION_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes_inc_gen/deallocation/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes_inc_gen/deallocation/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..ca44cf2a305117dc3ebad64ad3f8ce1fb9016f9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_passes_inc_gen/deallocation/transforms/passes.h.inc @@ -0,0 +1,1032 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ANNOTATEDEALLOCATIONPASS +#define GEN_PASS_DECL_BUFFERREUSEPASS +#define GEN_PASS_DECL_CONVERTDEALLOCATIONOPSTOLLVMPASS +#define GEN_PASS_DECL_DEALLOCATEPASS +#define GEN_PASS_DECL_DEALLOCATIONSIMPLIFICATIONPASS +#define GEN_PASS_DECL_DEALLOCATIONTOSCFPASS +#define GEN_PASS_DECL_SPLITALLOCTENSORSPASS +#define GEN_PASS_DECL_XLABUFFERARGREWRITEPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// AnnotateDeallocationPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ANNOTATEDEALLOCATIONPASS +#undef GEN_PASS_DECL_ANNOTATEDEALLOCATIONPASS +#endif // GEN_PASS_DECL_ANNOTATEDEALLOCATIONPASS +#ifdef GEN_PASS_DEF_ANNOTATEDEALLOCATIONPASS +namespace impl { + +template +class AnnotateDeallocationPassBase : public ::mlir::OperationPass { +public: + using Base = AnnotateDeallocationPassBase; + + AnnotateDeallocationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AnnotateDeallocationPassBase(const AnnotateDeallocationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-annotation"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-annotation"; } + + ::llvm::StringRef getDescription() const override { return "Annotate ops with deallocation debug information."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AnnotateDeallocationPass"); + } + ::llvm::StringRef getName() const override { return "AnnotateDeallocationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AnnotateDeallocationPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ANNOTATEDEALLOCATIONPASS +#endif // GEN_PASS_DEF_ANNOTATEDEALLOCATIONPASS + +//===----------------------------------------------------------------------===// +// BufferReusePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_BUFFERREUSEPASS +#undef GEN_PASS_DECL_BUFFERREUSEPASS +#endif // GEN_PASS_DECL_BUFFERREUSEPASS +#ifdef GEN_PASS_DEF_BUFFERREUSEPASS +namespace impl { + +template +class BufferReusePassBase : public ::mlir::OperationPass { +public: + using Base = BufferReusePassBase; + + BufferReusePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + BufferReusePassBase(const BufferReusePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-buffer-reuse"); + } + ::llvm::StringRef getArgument() const override { return "hlo-buffer-reuse"; } + + ::llvm::StringRef getDescription() const override { return "Reuse buffers."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("BufferReusePass"); + } + ::llvm::StringRef getName() const override { return "BufferReusePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(BufferReusePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_BUFFERREUSEPASS +#endif // GEN_PASS_DEF_BUFFERREUSEPASS + +//===----------------------------------------------------------------------===// +// ConvertDeallocationOpsToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTDEALLOCATIONOPSTOLLVMPASS +#undef GEN_PASS_DECL_CONVERTDEALLOCATIONOPSTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTDEALLOCATIONOPSTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTDEALLOCATIONOPSTOLLVMPASS +namespace impl { + +template +class ConvertDeallocationOpsToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertDeallocationOpsToLLVMPassBase; + + ConvertDeallocationOpsToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertDeallocationOpsToLLVMPassBase(const ConvertDeallocationOpsToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-convert-deallocation-ops-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "hlo-convert-deallocation-ops-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert `deallocation` ops to LLVM"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertDeallocationOpsToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertDeallocationOpsToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertDeallocationOpsToLLVMPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTDEALLOCATIONOPSTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTDEALLOCATIONOPSTOLLVMPASS + +//===----------------------------------------------------------------------===// +// DeallocatePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_DEALLOCATEPASS +#undef GEN_PASS_DECL_DEALLOCATEPASS +#endif // GEN_PASS_DECL_DEALLOCATEPASS +#ifdef GEN_PASS_DEF_DEALLOCATEPASS +namespace impl { + +template +class DeallocatePassBase : public ::mlir::OperationPass { +public: + using Base = DeallocatePassBase; + + DeallocatePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocatePassBase(const DeallocatePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocate"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocate"; } + + ::llvm::StringRef getDescription() const override { return "Deallocate buffers by inserting `deallocation.retain` ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocatePass"); + } + ::llvm::StringRef getName() const override { return "DeallocatePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::deallocation::DeallocationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocatePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_DEALLOCATEPASS +#endif // GEN_PASS_DEF_DEALLOCATEPASS + +//===----------------------------------------------------------------------===// +// DeallocationSimplificationPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_DEALLOCATIONSIMPLIFICATIONPASS +#undef GEN_PASS_DECL_DEALLOCATIONSIMPLIFICATIONPASS +#endif // GEN_PASS_DECL_DEALLOCATIONSIMPLIFICATIONPASS +#ifdef GEN_PASS_DEF_DEALLOCATIONSIMPLIFICATIONPASS +namespace impl { + +template +class DeallocationSimplificationPassBase : public ::mlir::OperationPass { +public: + using Base = DeallocationSimplificationPassBase; + + DeallocationSimplificationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocationSimplificationPassBase(const DeallocationSimplificationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-simplification"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-simplification"; } + + ::llvm::StringRef getDescription() const override { return "Simplifies deallocation.retain ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocationSimplificationPass"); + } + ::llvm::StringRef getName() const override { return "DeallocationSimplificationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::deallocation::DeallocationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocationSimplificationPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_DEALLOCATIONSIMPLIFICATIONPASS +#endif // GEN_PASS_DEF_DEALLOCATIONSIMPLIFICATIONPASS + +//===----------------------------------------------------------------------===// +// DeallocationToScfPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_DEALLOCATIONTOSCFPASS +#undef GEN_PASS_DECL_DEALLOCATIONTOSCFPASS +#endif // GEN_PASS_DECL_DEALLOCATIONTOSCFPASS +#ifdef GEN_PASS_DEF_DEALLOCATIONTOSCFPASS +namespace impl { + +template +class DeallocationToScfPassBase : public ::mlir::OperationPass { +public: + using Base = DeallocationToScfPassBase; + + DeallocationToScfPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocationToScfPassBase(const DeallocationToScfPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lowers retain to scf."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocationToScfPass"); + } + ::llvm::StringRef getName() const override { return "DeallocationToScfPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::scf::SCFDialect>(); + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocationToScfPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_DEALLOCATIONTOSCFPASS +#endif // GEN_PASS_DEF_DEALLOCATIONTOSCFPASS + +//===----------------------------------------------------------------------===// +// SplitAllocTensorsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SPLITALLOCTENSORSPASS +#undef GEN_PASS_DECL_SPLITALLOCTENSORSPASS +#endif // GEN_PASS_DECL_SPLITALLOCTENSORSPASS +#ifdef GEN_PASS_DEF_SPLITALLOCTENSORSPASS +namespace impl { + +template +class SplitAllocTensorsPassBase : public ::mlir::OperationPass { +public: + using Base = SplitAllocTensorsPassBase; + + SplitAllocTensorsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SplitAllocTensorsPassBase(const SplitAllocTensorsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-split-alloc-tensors"); + } + ::llvm::StringRef getArgument() const override { return "hlo-split-alloc-tensors"; } + + ::llvm::StringRef getDescription() const override { return "Split bufferization.alloc_tensor ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SplitAllocTensorsPass"); + } + ::llvm::StringRef getName() const override { return "SplitAllocTensorsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::bufferization::BufferizationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SplitAllocTensorsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_SPLITALLOCTENSORSPASS +#endif // GEN_PASS_DEF_SPLITALLOCTENSORSPASS + +//===----------------------------------------------------------------------===// +// XlaBufferArgRewritePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_XLABUFFERARGREWRITEPASS +#undef GEN_PASS_DECL_XLABUFFERARGREWRITEPASS +#endif // GEN_PASS_DECL_XLABUFFERARGREWRITEPASS +#ifdef GEN_PASS_DEF_XLABUFFERARGREWRITEPASS +namespace impl { + +template +class XlaBufferArgRewritePassBase : public ::mlir::OperationPass { +public: + using Base = XlaBufferArgRewritePassBase; + + XlaBufferArgRewritePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + XlaBufferArgRewritePassBase(const XlaBufferArgRewritePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-xla-buffer-arg-rewrite"); + } + ::llvm::StringRef getArgument() const override { return "hlo-xla-buffer-arg-rewrite"; } + + ::llvm::StringRef getDescription() const override { return "Rewrites XLA framework buffer arguments with alias information"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("XlaBufferArgRewritePass"); + } + ::llvm::StringRef getName() const override { return "XlaBufferArgRewritePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(XlaBufferArgRewritePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_XLABUFFERARGREWRITEPASS +#endif // GEN_PASS_DEF_XLABUFFERARGREWRITEPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// AnnotateDeallocationPass Registration +//===----------------------------------------------------------------------===// + +inline void registerAnnotateDeallocationPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationAnnotationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAnnotateDeallocationPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationAnnotationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// BufferReusePass Registration +//===----------------------------------------------------------------------===// + +inline void registerBufferReusePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createBufferReusePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerBufferReusePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createBufferReusePass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertDeallocationOpsToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertDeallocationOpsToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createConvertDeallocationOpsToLLVM(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertDeallocationOpsToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createConvertDeallocationOpsToLLVM(); + }); +} + +//===----------------------------------------------------------------------===// +// DeallocatePass Registration +//===----------------------------------------------------------------------===// + +inline void registerDeallocatePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocatePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerDeallocatePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocatePass(); + }); +} + +//===----------------------------------------------------------------------===// +// DeallocationSimplificationPass Registration +//===----------------------------------------------------------------------===// + +inline void registerDeallocationSimplificationPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationSimplificationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerDeallocationSimplificationPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationSimplificationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// DeallocationToScfPass Registration +//===----------------------------------------------------------------------===// + +inline void registerDeallocationToScfPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationToScfPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerDeallocationToScfPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createDeallocationToScfPass(); + }); +} + +//===----------------------------------------------------------------------===// +// SplitAllocTensorsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerSplitAllocTensorsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createSplitAllocTensorsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSplitAllocTensorsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createSplitAllocTensorsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// XlaBufferArgRewritePass Registration +//===----------------------------------------------------------------------===// + +inline void registerXlaBufferArgRewritePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createXlaBufferArgRewritePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerXlaBufferArgRewritePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::deallocation::createXlaBufferArgRewritePass(); + }); +} + +//===----------------------------------------------------------------------===// +// Deallocation Registration +//===----------------------------------------------------------------------===// + +inline void registerDeallocationPasses() { + registerAnnotateDeallocationPass(); + registerBufferReusePass(); + registerConvertDeallocationOpsToLLVMPass(); + registerDeallocatePass(); + registerDeallocationSimplificationPass(); + registerDeallocationToScfPass(); + registerSplitAllocTensorsPass(); + registerXlaBufferArgRewritePass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class AnnotateDeallocationPassBase : public ::mlir::OperationPass { +public: + using Base = AnnotateDeallocationPassBase; + + AnnotateDeallocationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AnnotateDeallocationPassBase(const AnnotateDeallocationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-annotation"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-annotation"; } + + ::llvm::StringRef getDescription() const override { return "Annotate ops with deallocation debug information."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AnnotateDeallocationPass"); + } + ::llvm::StringRef getName() const override { return "AnnotateDeallocationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AnnotateDeallocationPassBase) + +protected: +}; + +template +class BufferReusePassBase : public ::mlir::OperationPass { +public: + using Base = BufferReusePassBase; + + BufferReusePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + BufferReusePassBase(const BufferReusePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-buffer-reuse"); + } + ::llvm::StringRef getArgument() const override { return "hlo-buffer-reuse"; } + + ::llvm::StringRef getDescription() const override { return "Reuse buffers."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("BufferReusePass"); + } + ::llvm::StringRef getName() const override { return "BufferReusePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(BufferReusePassBase) + +protected: +}; + +template +class ConvertDeallocationOpsToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertDeallocationOpsToLLVMPassBase; + + ConvertDeallocationOpsToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertDeallocationOpsToLLVMPassBase(const ConvertDeallocationOpsToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-convert-deallocation-ops-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "hlo-convert-deallocation-ops-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert `deallocation` ops to LLVM"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertDeallocationOpsToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertDeallocationOpsToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertDeallocationOpsToLLVMPassBase) + +protected: +}; + +template +class DeallocatePassBase : public ::mlir::OperationPass { +public: + using Base = DeallocatePassBase; + + DeallocatePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocatePassBase(const DeallocatePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocate"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocate"; } + + ::llvm::StringRef getDescription() const override { return "Deallocate buffers by inserting `deallocation.retain` ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocatePass"); + } + ::llvm::StringRef getName() const override { return "DeallocatePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::deallocation::DeallocationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocatePassBase) + +protected: +}; + +template +class DeallocationSimplificationPassBase : public ::mlir::OperationPass { +public: + using Base = DeallocationSimplificationPassBase; + + DeallocationSimplificationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocationSimplificationPassBase(const DeallocationSimplificationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-simplification"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-simplification"; } + + ::llvm::StringRef getDescription() const override { return "Simplifies deallocation.retain ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocationSimplificationPass"); + } + ::llvm::StringRef getName() const override { return "DeallocationSimplificationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::deallocation::DeallocationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocationSimplificationPassBase) + +protected: +}; + +template +class DeallocationToScfPassBase : public ::mlir::OperationPass { +public: + using Base = DeallocationToScfPassBase; + + DeallocationToScfPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + DeallocationToScfPassBase(const DeallocationToScfPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-deallocation-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "hlo-deallocation-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lowers retain to scf."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("DeallocationToScfPass"); + } + ::llvm::StringRef getName() const override { return "DeallocationToScfPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::scf::SCFDialect>(); + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DeallocationToScfPassBase) + +protected: +}; + +template +class SplitAllocTensorsPassBase : public ::mlir::OperationPass { +public: + using Base = SplitAllocTensorsPassBase; + + SplitAllocTensorsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SplitAllocTensorsPassBase(const SplitAllocTensorsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-split-alloc-tensors"); + } + ::llvm::StringRef getArgument() const override { return "hlo-split-alloc-tensors"; } + + ::llvm::StringRef getDescription() const override { return "Split bufferization.alloc_tensor ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SplitAllocTensorsPass"); + } + ::llvm::StringRef getName() const override { return "SplitAllocTensorsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::bufferization::BufferizationDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SplitAllocTensorsPassBase) + +protected: +}; + +template +class XlaBufferArgRewritePassBase : public ::mlir::OperationPass { +public: + using Base = XlaBufferArgRewritePassBase; + + XlaBufferArgRewritePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + XlaBufferArgRewritePassBase(const XlaBufferArgRewritePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("hlo-xla-buffer-arg-rewrite"); + } + ::llvm::StringRef getArgument() const override { return "hlo-xla-buffer-arg-rewrite"; } + + ::llvm::StringRef getDescription() const override { return "Rewrites XLA framework buffer arguments with alias information"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("XlaBufferArgRewritePass"); + } + ::llvm::StringRef getName() const override { return "XlaBufferArgRewritePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(XlaBufferArgRewritePassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_utils/deallocation/utils/util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_utils/deallocation/utils/util.h new file mode 100644 index 0000000000000000000000000000000000000000..14ff8ec0798a859c8eea38bc8ab2603311e619f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/deallocation_utils/deallocation/utils/util.h @@ -0,0 +1,150 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_DEALLOCATION_UTILS_UTIL_H_ +#define MLIR_HLO_DEALLOCATION_UTILS_UTIL_H_ + +#include +#include + +#include "llvm/ADT/EquivalenceClasses.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" + +namespace mlir { +namespace deallocation { + +struct RegionEdge { + // The op in the predecessor that holds the values that are passed. This is + // either the parent op or a terminator in the predecessor region. + Operation* predecessorOp; + // The index in `opWithOperands`' operands where `operands` start. + int64_t predecessorOperandIndex; + // The op or region where the values are passed. If the successor is the + // parent region, this is the parent op. + llvm::PointerUnion successorOpOrRegion; + // The index in the successor's arguments or op results where `operands` + // start. + int64_t successorValueIndex; + RegionBranchPoint predecessorRegionPoint = RegionBranchPoint::parent(); + RegionBranchPoint successorRegionPoint = RegionBranchPoint::parent(); + + ValueRange getPredecessorOperands() const { + return predecessorOp->getOperands().drop_front(predecessorOperandIndex); + } + + Value getPredecessorOperand(unsigned successorIndex) const { + return getPredecessorOperands()[successorIndex - successorValueIndex]; + } + + ValueRange getSuccessorValues() const { + if (successorOpOrRegion.is()) { + return successorOpOrRegion.get()->getResults().drop_front( + successorValueIndex); + } + return successorOpOrRegion.get()->getArguments().drop_front( + successorValueIndex); + } + + Value getSuccessorValue(unsigned predecessorIndex) const { + return getSuccessorValues()[predecessorIndex - predecessorOperandIndex]; + } +}; + +// Returns predecessors of the given region. +SmallVector getPredecessorRegions(RegionBranchOpInterface op, + RegionBranchPoint index); + +SmallVector getSuccessorRegions(RegionBranchOpInterface op, + RegionBranchPoint index); + +// Replaces the op with a new op with proper return types. The old op is not +// removed and it still has uses. +RegionBranchOpInterface moveRegionsToNewOpButKeepOldOp( + RegionBranchOpInterface op); + +namespace detail { +// An arbitrary deterministic Value order. +struct ValueComparator { + bool operator()(const Value& lhs, const Value& rhs) const { + if (lhs == rhs) return false; + + // Block arguments are less than results. + bool lhsIsBBArg = lhs.isa(); + if (lhsIsBBArg != rhs.isa()) { + return lhsIsBBArg; + } + + Region* lhsRegion; + Region* rhsRegion; + if (lhsIsBBArg) { + auto lhsBBArg = llvm::cast(lhs); + auto rhsBBArg = llvm::cast(rhs); + if (lhsBBArg.getArgNumber() != rhsBBArg.getArgNumber()) { + return lhsBBArg.getArgNumber() < rhsBBArg.getArgNumber(); + } + lhsRegion = lhsBBArg.getParentRegion(); + rhsRegion = rhsBBArg.getParentRegion(); + assert(lhsRegion != rhsRegion && + "lhsRegion == rhsRegion implies lhs == rhs"); + } else if (lhs.getDefiningOp() == rhs.getDefiningOp()) { + return llvm::cast(lhs).getResultNumber() < + llvm::cast(rhs).getResultNumber(); + } else { + lhsRegion = lhs.getDefiningOp()->getParentRegion(); + rhsRegion = rhs.getDefiningOp()->getParentRegion(); + if (lhsRegion == rhsRegion) { + return lhs.getDefiningOp()->isBeforeInBlock(rhs.getDefiningOp()); + } + } + + // lhsRegion != rhsRegion, so if we look at their ancestor chain, they + // - have different heights + // - or there's a spot where their region numbers differ + // - or their parent regions are the same and their parent ops are + // different. + while (lhsRegion && rhsRegion) { + if (lhsRegion->getRegionNumber() != rhsRegion->getRegionNumber()) { + return lhsRegion->getRegionNumber() < rhsRegion->getRegionNumber(); + } + if (lhsRegion->getParentRegion() == rhsRegion->getParentRegion()) { + return lhsRegion->getParentOp()->isBeforeInBlock( + rhsRegion->getParentOp()); + } + lhsRegion = lhsRegion->getParentRegion(); + rhsRegion = rhsRegion->getParentRegion(); + } + if (rhsRegion) return true; + assert(lhsRegion && "this should only happen if lhs == rhs"); + return false; + } +}; +} // namespace detail + +namespace breaks_if_you_move_ops { + +// The comparator depends on the location of ops, so if you insert an op into +// a set and then move it, it may end up in the wrong location. +using ValueEquivalenceClasses = + llvm::EquivalenceClasses; +using ValueSet = std::set; +template +using ValueMap = std::map; + +} // namespace breaks_if_you_move_ops + +} // namespace deallocation +} // namespace mlir + +#endif // MLIR_HLO_DEALLOCATION_UTILS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st/gml_st/IR/gml_st_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st/gml_st/IR/gml_st_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..55ade3e4c4a76a6db2d20d88f78f39c36e9d0377 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st/gml_st/IR/gml_st_ops.h @@ -0,0 +1,36 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the operations used in the GML ST dialect. + +#ifndef MLIR_HLO_GML_ST_IR_GML_ST_OPS_H +#define MLIR_HLO_GML_ST_IR_GML_ST_OPS_H + +#include "mlir/Bytecode/BytecodeOpInterface.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" +#include "mlir/Interfaces/DestinationStyleOpInterface.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" + +// Generated dialect declarations. +#include "gml_st/IR/gml_st_dialect.h.inc" + +// Generated operation classes. +#define GET_OP_CLASSES +#include "gml_st/IR/gml_st_ops.h.inc" + +#endif // MLIR_HLO_GML_ST_IR_GML_ST_OPS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_bufferizable_op_interface/gml_st/interfaces/bufferizable_op_interface_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_bufferizable_op_interface/gml_st/interfaces/bufferizable_op_interface_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..54739c5b3acc768c32110427a8168402cf13e195 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_bufferizable_op_interface/gml_st/interfaces/bufferizable_op_interface_impl.h @@ -0,0 +1,29 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_INTERFACES_BUFFERIZABLE_OP_INTERFACE_IMPL_H +#define MLIR_HLO_GML_ST_INTERFACES_BUFFERIZABLE_OP_INTERFACE_IMPL_H + +namespace mlir { +class DialectRegistry; + +namespace gml_st { + +void registerBufferizableOpInterfaceExternalModels(DialectRegistry ®istry); + +} // namespace gml_st +} // namespace mlir + +#endif diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..9fecd03349f09e7085088bd316a9568f83dacd80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_dialect.h.inc @@ -0,0 +1,26 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: gml_st_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace gml_st { + +class GmlStDialect : public ::mlir::Dialect { + explicit GmlStDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~GmlStDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("gml_st"); + } +}; +} // namespace gml_st +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::gml_st::GmlStDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..78d354f426ea5c14ba34868d1f6ea5957c4f495c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_ops_inc_gen/gml_st/IR/gml_st_ops.h.inc @@ -0,0 +1,298 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: gml_st_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace gml_st { +class FusionOp; +} // namespace gml_st +} // namespace mlir +namespace mlir { +namespace gml_st { +class YieldOp; +} // namespace gml_st +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace gml_st { + +//===----------------------------------------------------------------------===// +// ::mlir::gml_st::FusionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FusionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FusionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FusionOpGenericAdaptorBase(FusionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseI64ArrayAttr getParallelTileSizesAttr(); + ::std::optional<::llvm::ArrayRef> getParallelTileSizes(); + ::mlir::DenseI64ArrayAttr getReductionTileSizesAttr(); + ::std::optional<::llvm::ArrayRef> getReductionTileSizes(); + ::mlir::Region &getRegion(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class FusionOpGenericAdaptor : public detail::FusionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FusionOpGenericAdaptorBase; +public: + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FusionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FusionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getInits() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FusionOpAdaptor : public FusionOpGenericAdaptor<::mlir::ValueRange> { +public: + using FusionOpGenericAdaptor::FusionOpGenericAdaptor; + FusionOpAdaptor(FusionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FusionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::DestinationStyleOpInterface::Trait, ::mlir::OpTrait::IsIsolatedFromAbove> { +public: + using Op::Op; + using Op::print; + using Adaptor = FusionOpAdaptor; + template + using GenericAdaptor = FusionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("parallel_tile_sizes"), ::llvm::StringRef("reduction_tile_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getParallelTileSizesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getParallelTileSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getReductionTileSizesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getReductionTileSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("gml_st.fusion"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getInits(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getInitsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Operation::result_range getResults(); + ::mlir::Region &getRegion(); + ::mlir::DenseI64ArrayAttr getParallelTileSizesAttr(); + ::std::optional<::llvm::ArrayRef> getParallelTileSizes(); + ::mlir::DenseI64ArrayAttr getReductionTileSizesAttr(); + ::std::optional<::llvm::ArrayRef> getReductionTileSizes(); + void setParallelTileSizesAttr(::mlir::DenseI64ArrayAttr attr); + void setParallelTileSizes(::std::optional<::llvm::ArrayRef> attrValue); + void setReductionTileSizesAttr(::mlir::DenseI64ArrayAttr attr); + void setReductionTileSizes(::std::optional<::llvm::ArrayRef> attrValue); + ::mlir::Attribute removeParallelTileSizesAttr(); + ::mlir::Attribute removeReductionTileSizesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange results, ::mlir::ValueRange inputs, ::mlir::ValueRange inits, /*optional*/::mlir::DenseI64ArrayAttr parallel_tile_sizes, /*optional*/::mlir::DenseI64ArrayAttr reduction_tile_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + /// Return terminator of the region body. + YieldOp getTerminator(); + + // Implement method necessary for DestinationStyleOpInterface. + mlir::MutableOperandRange getDpsInitsMutable() { + return getInitsMutable(); + } +}; +} // namespace gml_st +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::gml_st::FusionOp) + +namespace mlir { +namespace gml_st { + +//===----------------------------------------------------------------------===// +// ::mlir::gml_st::YieldOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class YieldOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + YieldOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + YieldOpGenericAdaptorBase(YieldOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class YieldOpGenericAdaptor : public detail::YieldOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::YieldOpGenericAdaptorBase; +public: + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : YieldOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + YieldOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getValues() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class YieldOpAdaptor : public YieldOpGenericAdaptor<::mlir::ValueRange> { +public: + using YieldOpGenericAdaptor::YieldOpGenericAdaptor; + YieldOpAdaptor(YieldOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class YieldOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::RegionBranchTerminatorOpInterface::Trait, ::mlir::OpTrait::ReturnLike, ::mlir::OpTrait::IsTerminator> { +public: + using Op::Op; + using Op::print; + using Adaptor = YieldOpAdaptor; + template + using GenericAdaptor = YieldOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("gml_st.yield"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getValues(); + ::mlir::MutableOperandRange getValuesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange values); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + ::mlir::MutableOperandRange getMutableSuccessorOperands(::mlir::RegionBranchPoint point); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace gml_st +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::gml_st::YieldOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/fusion/fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/fusion/fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..b1b9181108e0e8354652bfb31515efb09132c248 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/fusion/fusion.h @@ -0,0 +1,83 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_FUSION_FUSION_H +#define MLIR_HLO_GML_ST_TRANSFORMS_FUSION_FUSION_H + +#include + +#include "gml_st/transforms/peeling/peeling.h" +#include "gml_st/transforms/tiling/tiling.h" +#include "mlir/Dialect/SCF/Transforms/TileUsingInterface.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/IR/PatternMatch.h" + +namespace mlir::gml_st { + +struct FusionCluster { + SetVector operations; + Operation *root; + // Map from Value of the fusion cluster argument to the root dimensions. + llvm::SmallVector>> argDimsMapping; +}; +// Cluster producers and consumers around the root op. +FusionCluster getFusionCluster( + Operation *op, llvm::function_ref producerFilterFn, + llvm::function_ref consumerFilterFn); + +// Creates gml_st.fusion op with a region with ops from the fusion cluster. +// Operands of the ops in the region are replaced with region arguments to +// isolate the fusion cluster form above. Usages of the ops are replaces with +// the fusion op results. +FailureOr wrapFusionCluster( + PatternRewriter &rewriter, const FusionCluster &fusionCluster); + +// Replaces gml_st.fusion op with ops from the region. +LogicalResult inlineFusionCluster(FusionOp fusionOp, PatternRewriter &rewriter); + +// Adds patterns to duplicate linalg.fill and tensor.empty that used as init +// parameters. +void populateDuplicateInitOpsPatterns(RewritePatternSet &patterns); + +// Fuses an op into `tensor.extract_slice` and performs the necessary updates to +// the surrounding loop if any. +FailureOr fuse(PatternRewriter &rewriter, + tensor::ExtractSliceOp materializeOp); + +// Finds `tensor.extract_slice` ops in the block and fuses ops into them. +// Verifies that fusion candidate doesn't have any uses except the one +// `tensor.extract_slice` in the block to avoid exponential code growth. +void fuseGreedily(PatternRewriter &rewriter, ArrayRef blocks, + llvm::function_ref filterFn = nullptr); + +// Tiles the op to gml_st.parallel and fuses greedily according to the filter. +FailureOr tileUsingSCFForallOpAndFuseGreedily( + PatternRewriter &rewriter, Operation *op, const scf::SCFTilingOptions &opts, + llvm::function_ref fuseFilterFn = nullptr); + +// Tiles the op to scf.for and fuses greedily according to the filter. +FailureOr tileUsingSCFForOpAndFuseGreedily( + PatternRewriter &rewriter, Operation *op, const scf::SCFTilingOptions &opts, + llvm::function_ref fuseFilterFn = nullptr); + +// Tiles the op to 1 for all dimensions and fuses greedily according to the +// filter function. +LogicalResult tilePeeledOpsToScalars( + PatternRewriter &rewriter, const GmlStPeelingResult &peelingResult, + llvm::function_ref fuseFilterFn = nullptr); + +} // namespace mlir::gml_st + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_FUSION_FUSION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..12b02debc705faf60b097b80bf9f522ccf10cf8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/passes.h @@ -0,0 +1,251 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H +#define MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H + +#include +#include +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // IWYU pragma: keep +#include "mlir/IR/BuiltinOps.h" +#include "mlir/Pass/Pass.h" + +namespace mlir::gml_st { + +#define GEN_PASS_DECL +#include "gml_st/transforms/passes.h.inc" + +/// Pass to fuse producers into a tiled consumer. +std::unique_ptr> createFusionPass( + StringRef producer = "", StringRef consumer = ""); + +/// Pass to match, tile, and fuse softmax implementations. +std::unique_ptr> createTilingSoftmaxPass( + ArrayRef tileSizes); +std::unique_ptr> createTilingSoftmaxPass(); + +/// Pass to tile the root operation and to greedily fuse producers into it. +std::unique_ptr> createGreedyFusionPass( + ArrayRef tileSizes); +std::unique_ptr> createGreedyFusionPass(); + +// Pass to collapse dimensions of bcasts, reductions, and cwise ops. +std::unique_ptr> createCollapseShapePass(); +std::unique_ptr> createCollapseShapePass( + const CollapseShapePassOptions &options); + +// Pass to tile all tileable ops to size 1. +std::unique_ptr> createTileByOnePass(); + +/// Pass to compose tensor.extract_slice/insert_slice ops. +std::unique_ptr> +createComposeExtractInsertSlicePass(); + +/// Pass to vectorize compute ops and scf.for loops that are tiled perfectly. +std::unique_ptr> createVectorizeForCPUPass( + int64_t numElementsThreshold = 1024); + +/// Pass to vectorize `memref.copy`. +std::unique_ptr> createVectorizeCopyPass( + int64_t numElementsThreshold = 8); + +/// Pass to remove redundant `memref.copy` ops. +std::unique_ptr> createNaiveCopyRemovalPass(); + +/// Pass to gradually lower vector ops to SCF. +std::unique_ptr> createLowerVectorsPass( + bool enableAVX2 = true, bool flatten = false); + +/// Pass to pack linalg.matmul as linalg.mmt4d. +std::unique_ptr> createPackMatmulPass(); + +/// Pass to transform a thlo.scatter op for CPU backend. +std::unique_ptr> createTransformScatterForCpuPass(); + +/// Pass to transform a dot operation for CPU backend. +std::unique_ptr> createTransformDotForCpuPass( + ArrayRef tileSizes = {}, StringRef cpuName = ""); + +/// Pass to transform tensor.pack/unpack ops for CPU backend. +std::unique_ptr> createTransformPackForCpuPass(); + +/// Pass to transform a linalg.mmt4d op for CPU backend. +std::unique_ptr> createTransformMmt4DForCpuPass(); + +/// Pass to fuse linalg on tensor operations. +std::unique_ptr> createFusionOfTensorOpsPass(); + +/// Pass to convert ops on tensors with 1 element to scalar ops. +std::unique_ptr> createScalarizationPass( + bool scalarizeAllThlo = true); + +/// Pass to transform elementwise ops for CPU backend. +std::unique_ptr> +createTransformElementwiseForCpuPass(int64_t vectorSize = 8, + bool fuseDegenerateReshapes = false); + +/// Pass to transform a linalg.reduce op for CPU backend. +std::unique_ptr createTransformReduceForCpuPass( + const TransformReduceForCpuPassOptions &option = {}); + +/// Pass to create fusion clusters. +std::unique_ptr> +createFusionPlanningForCpuPass(int64_t vectorSize = 8); + +/// Pass to outline fusion regions into functions. +std::unique_ptr> createFusionOutliningPass(); + +/// Pass to inline fusion clusters. +std::unique_ptr> +createInlineFusionClustersPass(); + +/// Pass with canonicalization patterns for linalg ops. +std::unique_ptr> +createOptimizeLinalgOpsPass(); + +/// Pass to rewrite tensor.from_elements into tensor.insert. +std::unique_ptr> +createRewriteFromElementsOpPass(); + +/// Pass to rewrite scf.forall to scf.for. +std::unique_ptr> +createRewriteForallOpPass(); + +/// Pass to add debug info to be propagated into LLVM backend. +std::unique_ptr> createAddDebugInfoPass(); + +/// Pass to print stats about tileable ops. +std::unique_ptr> createCollectStatsPass( + int64_t level = 0); + +/// Pass to remove all transformed labels from tiled ops. +std::unique_ptr> +createRemoveLabelPass(); + +/// Populate pattern to remove single/zero iteration scf.forall dimensions. +void populateCollapseForallOpDimensionsPattern(RewritePatternSet &patterns); + +struct GmlStCPUTilingOptions + : public mlir::PassPipelineOptions { + GmlStCPUTilingOptions() = default; + GmlStCPUTilingOptions(const GmlStCPUTilingOptions &opts) { + this->lowerToMmt4d = opts.lowerToMmt4d; + this->matmulTileSizes = opts.matmulTileSizes; + this->reduction1DTileSize = opts.reduction1DTileSize; + this->reduction1DSplitRatio = opts.reduction1DSplitRatio; + this->reduction2DParallelDimTileSize = opts.reduction2DParallelDimTileSize; + this->reduction2DReductionDimTileSize = + opts.reduction2DReductionDimTileSize; + this->vectorSize = opts.vectorSize; + this->statsDetailLevel = opts.statsDetailLevel; + this->cpuName = opts.cpuName; + this->inlineFusionClusters = opts.inlineFusionClusters; + } + + Option vectorSize{*this, "vector-size", + llvm::cl::desc("Vector size for a 1D reduction."), + llvm::cl::init(8)}; + + Option reductionEnableHeuristic{ + *this, "reduction-enable-heuristic", + llvm::cl::desc("Enable tiling parameters heuristic for reductions."), + llvm::cl::init(false)}; + + Option reduction1DTileSize{ + *this, "reduction-1d-tile-size", + llvm::cl::desc("Tile size for a 1D reduction."), llvm::cl::init(32)}; + + Option reduction1DSplitRatio{ + *this, "reduction-1d-split-ratio", + llvm::cl::desc("Ratio used to split the reduction dimension"), + llvm::cl::init(8)}; + + Option reduction2DParallelDimTileSize{ + *this, "reduction-2d-parallel-dim-tile-size", + llvm::cl::desc("Tile size for the parallel dimension of a 2D reduction."), + llvm::cl::init(4)}; + + Option reduction2DReductionDimTileSize{ + *this, "reduction-2d-reduction-dim-tile-size", + llvm::cl::desc( + "Tile size for the reduction dimension of a 2D reduction."), + llvm::cl::init(4)}; + + ListOption matmulTileSizes{ + *this, "matmul-tile-sizes", + llvm::cl::desc("Tile sizes for `linalg.matmul`. Leave empty to determine " + "sizes automatically."), + llvm::cl::list_init({}), llvm::cl::ZeroOrMore}; + + Option vectorizationSizeThreshold{ + *this, "vectorization-size-threshold", + llvm::cl::desc("Threshold size for vectorization."), llvm::cl::init(128)}; + + Option vectorizationTiledSizeThreshold{ + *this, "vectorization-tiled-size-threshold", + llvm::cl::desc("Threshold size for vectorization after tiling."), + llvm::cl::init(1024)}; + + Option lowerToMmt4d{ + *this, "lower-to-mmt4d", + llvm::cl::desc("Enable the specific code generation (packing) for matmul " + "operations."), + llvm::cl::init(false)}; + + Option cpuName{ + *this, "cpu", + llvm::cl::desc("CPU name, similar to llc's -mcpu flag. e.g. 'znver2', " + "'skylake-avx512'."), + llvm::cl::init("")}; + + Option statsDetailLevel{ + *this, "stats-detail-level", + llvm::cl::desc("Detail level for collecting IR statistics."), + llvm::cl::init(0)}; + + Option fuseDegenerateReshapes{ + *this, "fuse-degenerate-reshapes", + llvm::cl::desc("Fuse through tensor.expand/collapse_shape"), + llvm::cl::init(false)}; + + Option inlineFusionClusters{ + *this, "inline-fusion-clusters", + llvm::cl::desc("Inline fusion clusters at the end of the pipeline."), + llvm::cl::init(true)}; +}; + +// Returns default "optimized" tiling parameters. +GmlStCPUTilingOptions getDefaultCPUPipelineOptions( + StringRef cpuName, int64_t statsDetailLevel = 0); + +// Adds tiling-fusion-vectorization passes for tHLO/Linalg ops mix. +void addCPUTilingPipeline(OpPassManager &pm, + const GmlStCPUTilingOptions &options); + +// Adds tiling-fusion-vectorization passes for tHLO/Linalg ops mix with the +// "optimized" tiling parameters. +void addDefaultCPUTilingPipeline(OpPassManager &pm, StringRef cpuName, + int64_t statsDetailLevel = 0); + +#define GEN_PASS_REGISTRATION +#include "gml_st/transforms/passes.h.inc" + +} // namespace mlir::gml_st + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/peeling/peeling.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/peeling/peeling.h new file mode 100644 index 0000000000000000000000000000000000000000..da3412b8b9901f0ad9e01fa23a2b97ba636aadb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/peeling/peeling.h @@ -0,0 +1,51 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_PEELING_PEELING_H +#define MLIR_HLO_GML_ST_TRANSFORMS_PEELING_PEELING_H + +#include "gml_st/IR/gml_st_ops.h" +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/IR/PatternMatch.h" + +namespace mlir { +namespace gml_st { + +struct GmlStPeelingResult { + scf::ForallOp mainLoop = nullptr; + SmallVector tailLoops = {}; +}; + +/// Rewrite a scf::ForallOp with bounds/step that potentially do not divide +/// evenly into a scf::ForallOp where the step divides the iteration space +/// evenly, followed by another scf::ForallOp for the last (partial) +/// iteration (if any). This transformation is called "loop peeling". +/// +/// These functions peel all loops in the loop nest by calling +/// peelAndCanonicalizeGmlStLoop. Additionally, they mark all loops (main and +/// remainder loops) as peeled, so the same loop is not rewritten a second time. +GmlStPeelingResult peelAllLoops(scf::ForallOp loop, + mlir::PatternRewriter &rewriter); + +struct SCFForPeelingResult { + scf::ForOp mainLoop = nullptr; + scf::ForOp tailLoop = nullptr; +}; +SCFForPeelingResult peelSCFForOp(RewriterBase &rewriter, scf::ForOp); + +} // namespace gml_st +} // namespace mlir + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_PEELING_PEELING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/scalarization/scalarization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/scalarization/scalarization.h new file mode 100644 index 0000000000000000000000000000000000000000..9455aa1c95eb18ff9518ded5c611717c2290d230 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/scalarization/scalarization.h @@ -0,0 +1,58 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_SCALARIZATION_SCALARIZATION_H +#define MLIR_HLO_GML_ST_TRANSFORMS_SCALARIZATION_SCALARIZATION_H + +#include "mlir/Dialect/Linalg/IR/Linalg.h" +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/IR/PatternMatch.h" +#include "thlo/IR/thlo_ops.h" + +namespace mlir { +namespace gml_st { + +/// Rewrites thlo.concatenate, returns `failure` if IR was not changed. +LogicalResult scalarizeConcatenateOp(thlo::ConcatenateOp concatenateOp, + PatternRewriter &rewriter); + +/// Rewrites thlo.dynamic_broadcast_in_dim, returns `failure` if IR was not +/// changed. +LogicalResult scalarizeDynamicBroadcastInDimOp( + thlo::DynamicBroadcastInDimOp broadcastOp, PatternRewriter &rewriter); + +/// Rewrites thlo.gather, returns `failure` if IR was not changed. +LogicalResult scalarizeGatherOp(thlo::GatherOp gatherOp, + PatternRewriter &rewriter); + +/// Rewrites LinalgOp interface ops, returns `failure` if IR was not changed. +LogicalResult scalarizeLinalgOp(linalg::LinalgOp linalgOp, + PatternRewriter &rewriter); + +/// Rewrites thlo.reverse, returns `failure` if IR was not changed. +LogicalResult scalarizeReverseOp(thlo::ReverseOp reverseOp, + PatternRewriter &rewriter); + +/// Rewrites thlo.scatter, returns `failure` if IR was not changed. +LogicalResult scalarizeScatterOp(thlo::ScatterOp scatterOp, + PatternRewriter &rewriter); + +FailureOr rewriteScatterOpAsIfOp(thlo::ScatterOp scatterOp, + PatternRewriter &rewriter); + +} // namespace gml_st +} // namespace mlir + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_SCALARIZATION_SCALARIZATION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/tiling/tiling.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/tiling/tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..47d852dcdf1aac3f3435f66ce9b871c403b3dc4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/tiling/tiling.h @@ -0,0 +1,50 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_TILING_TILING_H +#define MLIR_HLO_GML_ST_TRANSFORMS_TILING_TILING_H + +#include + +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/Dialect/SCF/Transforms/TileUsingInterface.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Interfaces/TilingInterface.h" + +namespace mlir::gml_st { + +// Creates SCFTilingOptions from the list of tile sizes. +scf::SCFTilingOptions getSCFTilingOptions(MLIRContext *context, + ArrayRef tileSizes); + +/// Returns `failure`, when there occurs a problem during tiling. If the tile +/// sizes are smaller then the iteration domain of the op, it will still create +/// an `scf.forall` op. This is matches the behavior of tiling to `scf.for` +/// upstream. +struct GMLSTTilingResult { + SmallVector tiledOps; + scf::ForallOp loop = nullptr; +}; +FailureOr tileUsingSCFForallOp( + PatternRewriter &rewriter, TilingInterface op, + const scf::SCFTilingOptions &options); + +/// Extracts all yielded values from scf.in_parallel terminator. It should be +/// upstreamed. +SmallVector getYieldedValues(scf::InParallelOp inParallelOp); + +} // namespace mlir::gml_st + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_TILING_TILING_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/vectorization/vectorization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/vectorization/vectorization.h new file mode 100644 index 0000000000000000000000000000000000000000..ede8e9320ff11d7d4c9dd5d3c31ff63a195da9dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/transforms/vectorization/vectorization.h @@ -0,0 +1,53 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_VECTORIZATION_VECTORIZATION_H +#define MLIR_HLO_GML_ST_TRANSFORMS_VECTORIZATION_VECTORIZATION_H + +#include "mlir/Dialect/Linalg/Transforms/Transforms.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Support/LogicalResult.h" + +namespace mlir { +namespace gml_st { + +// TODO(manany): This should be parameterized later on depending on hardware. +static constexpr int64_t kNumElementsVectorization = 8; + +template +struct VectorizationPattern : public mlir::OpRewritePattern { + VectorizationPattern(MLIRContext *context, + llvm::function_ref matchFn, + mlir::PatternBenefit benefit = 1) + : mlir::OpRewritePattern(context, benefit), filterFn(matchFn) {} + + LogicalResult matchAndRewrite(OpTy op, + PatternRewriter &rewriter) const override { + if (!filterFn(op)) + return rewriter.notifyMatchFailure(op, "did not match filter"); + return mlir::linalg::vectorize(rewriter, op); + } + + private: + llvm::function_ref filterFn; +}; + +RewritePatternSet getDefaultVectorizationPatterns(MLIRContext *ctx); + +} // namespace gml_st +} // namespace mlir + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_VECTORIZATION_VECTORIZATION_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/linalg_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/linalg_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..aef0a7603ad3f73b393b7403a1add6c9e03f3115 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/linalg_utils.h @@ -0,0 +1,77 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_UTILS_LINALG_UTILS_H +#define MLIR_HLO_GML_ST_UTILS_LINALG_UTILS_H + +#include "mlir/Dialect/Linalg/IR/Linalg.h" + +namespace mlir::gml_st { + +// Helper functions to match Linalg ops that implement simple reductions, +// bcasts, and cwise ops. + +struct SimpleBcastReduction { + Operation *bcast; + Operation *reduction; + Value operand; +}; + +bool isSimpleBcastReduction(Operation *op, int64_t *dimension = nullptr, + SimpleBcastReduction *chain = nullptr); + +// The Conv2D is transformable into a matmul, if it has the following shape +// +// linalg.conv_2d_nhwc_hwcf +// {dilations = dense<1> : tensor<2xi64>, strides = dense<1> : tensor<2xi64>} +// ins(%input, %kernel : tensor<1x(N+L-1)xKx1xf32>, tensor) +// outs(%fill : tensor<1xNx1xM>) -> tensor<1xNx1xMxf32> +// +// in that case we can tile w.r.t. L to bring it to the following form +// +// linalg.conv_2d_nhwc_hwcf +// {dilations = dense<1> : tensor<2xi64>, strides = dense<1> : tensor<2xi64>} +// ins(%input, %kernel : tensor<1xNxKx1xf32>, tensor<1xKx1xMxf32>) +// outs(%fill : tensor<1xNx1xM>) -> tensor<1xNx1xMxf32> +bool isTransformableIntoMatmul(linalg::Conv2DNhwcHwcfOp convOp); + +// linalg.conv_2d_nhwc_hwcf +// {dilations = dense<1> : tensor<2xi64>, strides = dense<1> : tensor<2xi64>} +// ins(%input, %kernel : tensor<1xNxKx1xf32>, tensor<1xKx1xMxf32>) +// outs(%fill : tensor<1xNx1xM>) -> tensor<1xNx1xMxf32> +// +// into +// +// linalg.matmul +// ins(%lhs, %rhs : tensor, tensor) +// outs(%fill : tensor) -> tensor<1xNx1xMxf32> +FailureOr convertConvToMatmul(linalg::Conv2DNhwcHwcfOp convOp, + PatternRewriter &rewriter); + +// Converts linalg.batch_matmul into linalg.matmul. +FailureOr convertBatchMatmulToMatmul( + linalg::BatchMatmulOp batchMatmulOp, PatternRewriter &rewriter); + +// Converts linalg.matvec into linalg.dot. +FailureOr convertMatvecToDotOp(PatternRewriter &rewriter, + linalg::MatvecOp matvecOp); + +// Converts linalg.dot into linalg.reduce(linalg.map). +FailureOr convertDotOpToReduce(linalg::DotOp dotOp, + PatternRewriter &rewriter); + +} // namespace mlir::gml_st + +#endif // MLIR_HLO_GML_ST_UTILS_LINALG_UTILS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/tensor_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/tensor_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0d0de996984ef0eff2f60f2315b1b1385321b771 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes/gml_st/utils/tensor_utils.h @@ -0,0 +1,57 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_UTILS_TENSOR_UTILS_H +#define MLIR_HLO_GML_ST_UTILS_TENSOR_UTILS_H + +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/Dialect/Utils/ReshapeOpsUtils.h" + +namespace mlir { +namespace gml_st { + +// TODO(vuson): maybe overload this function instead of templating it. +// Check if the reshape operation is only expanding into/collapsing of +// unit-dimension. +template +bool isDegenerateReshapeOp(TensorReshapeOp reshapeOp) { + constexpr bool isExpanding = + std::is_same::value; + llvm::ArrayRef expandedShape = + (isExpanding ? reshapeOp.getResultType().getShape() + : reshapeOp.getSrcType().getShape()); + for (auto& indices : reshapeOp.getReassociationIndices()) { + // For each reassociation indices, a degenerate reshape op only has at most + // 1 non-unit-dimension, i.e. number of unit-dimensions is greater or equal + // to the indices size - 1. + if (static_cast( + llvm::count_if(indices, [&expandedShape](int64_t idx) { + return expandedShape[idx] == 1; + })) < indices.size() - 1) + return false; + } + return true; +} + +// Returns ids of size-1 dims that were expanded or collapsed by +// tensor.expand_shape/tensor.collapse_shape. +SmallVector getPreservedDimensions( + ArrayRef shape, + ArrayRef reassociationIndices); + +} // namespace gml_st +} // namespace mlir + +#endif // MLIR_HLO_GML_ST_UTILS_TENSOR_UTILS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes_inc_gen/gml_st/transforms/passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes_inc_gen/gml_st/transforms/passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..9639d899e3c49e3f19c1354eef2c655312775233 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_passes_inc_gen/gml_st/transforms/passes.h.inc @@ -0,0 +1,3250 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ADDDEBUGINFOPASS +#define GEN_PASS_DECL_COLLAPSESHAPEPASS +#define GEN_PASS_DECL_COLLECTSTATSPASS +#define GEN_PASS_DECL_COMPOSEEXTRACTINSERTSLICEPASS +#define GEN_PASS_DECL_FUSIONOUTLININGPASS +#define GEN_PASS_DECL_FUSIONPLANNINGFORCPUPASS +#define GEN_PASS_DECL_INLINEFUSIONCLUSTERSPASS +#define GEN_PASS_DECL_LOWERVECTORSPASS +#define GEN_PASS_DECL_NAIVECOPYREMOVALPASS +#define GEN_PASS_DECL_OPTIMIZELINALGOPSPASS +#define GEN_PASS_DECL_PACKMATMULPASS +#define GEN_PASS_DECL_REMOVELABELPASS +#define GEN_PASS_DECL_REWRITEFORALLOPPASS +#define GEN_PASS_DECL_REWRITEFROMELEMENTSOPPASS +#define GEN_PASS_DECL_SCALARIZATIONPASS +#define GEN_PASS_DECL_TILEBYONEPASS +#define GEN_PASS_DECL_TILINGSOFTMAXPASS +#define GEN_PASS_DECL_TRANSFORMDOTFORCPUPASS +#define GEN_PASS_DECL_TRANSFORMELEMENTWISEFORCPUPASS +#define GEN_PASS_DECL_TRANSFORMMMT4DFORCPUPASS +#define GEN_PASS_DECL_TRANSFORMPACKFORCPUPASS +#define GEN_PASS_DECL_TRANSFORMREDUCEFORCPUPASS +#define GEN_PASS_DECL_TRANSFORMSCATTERFORCPUPASS +#define GEN_PASS_DECL_VECTORIZECOPYPASS +#define GEN_PASS_DECL_VECTORIZEFORCPUPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// AddDebugInfoPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ADDDEBUGINFOPASS +#undef GEN_PASS_DECL_ADDDEBUGINFOPASS +#endif // GEN_PASS_DECL_ADDDEBUGINFOPASS +#ifdef GEN_PASS_DEF_ADDDEBUGINFOPASS +namespace impl { + +template +class AddDebugInfoPassBase : public ::mlir::OperationPass { +public: + using Base = AddDebugInfoPassBase; + + AddDebugInfoPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddDebugInfoPassBase(const AddDebugInfoPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("add-debug-info"); + } + ::llvm::StringRef getArgument() const override { return "add-debug-info"; } + + ::llvm::StringRef getDescription() const override { return "Add debug info for the whole module"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddDebugInfoPass"); + } + ::llvm::StringRef getName() const override { return "AddDebugInfoPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddDebugInfoPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_ADDDEBUGINFOPASS +#endif // GEN_PASS_DEF_ADDDEBUGINFOPASS + +//===----------------------------------------------------------------------===// +// CollapseShapePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_COLLAPSESHAPEPASS +struct CollapseShapePassOptions { + int64_t retainTrailingDims = 0; +}; +#undef GEN_PASS_DECL_COLLAPSESHAPEPASS +#endif // GEN_PASS_DECL_COLLAPSESHAPEPASS +#ifdef GEN_PASS_DEF_COLLAPSESHAPEPASS +namespace impl { + +template +class CollapseShapePassBase : public ::mlir::OperationPass { +public: + using Base = CollapseShapePassBase; + + CollapseShapePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + CollapseShapePassBase(const CollapseShapePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-collapse-shape"); + } + ::llvm::StringRef getArgument() const override { return "gml-collapse-shape"; } + + ::llvm::StringRef getDescription() const override { return "Collapse dimensions of bcasts, reductions, and cwise ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("CollapseShapePass"); + } + ::llvm::StringRef getName() const override { return "CollapseShapePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CollapseShapePassBase) + + CollapseShapePassBase(const CollapseShapePassOptions &options) : CollapseShapePassBase() { + retainTrailingDims = options.retainTrailingDims; + } +protected: + ::mlir::Pass::Option retainTrailingDims{*this, "retain-trailing-dims", ::llvm::cl::desc("Number of trailing dimensions that will not be collapsed."), ::llvm::cl::init(0)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_COLLAPSESHAPEPASS +#endif // GEN_PASS_DEF_COLLAPSESHAPEPASS + +//===----------------------------------------------------------------------===// +// CollectStatsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_COLLECTSTATSPASS +#undef GEN_PASS_DECL_COLLECTSTATSPASS +#endif // GEN_PASS_DECL_COLLECTSTATSPASS +#ifdef GEN_PASS_DEF_COLLECTSTATSPASS +namespace impl { + +template +class CollectStatsPassBase : public ::mlir::OperationPass { +public: + using Base = CollectStatsPassBase; + + CollectStatsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + CollectStatsPassBase(const CollectStatsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("collect-stats"); + } + ::llvm::StringRef getArgument() const override { return "collect-stats"; } + + ::llvm::StringRef getDescription() const override { return "Print stats about tileable ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("CollectStatsPass"); + } + ::llvm::StringRef getName() const override { return "CollectStatsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CollectStatsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_COLLECTSTATSPASS +#endif // GEN_PASS_DEF_COLLECTSTATSPASS + +//===----------------------------------------------------------------------===// +// ComposeExtractInsertSlicePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_COMPOSEEXTRACTINSERTSLICEPASS +#undef GEN_PASS_DECL_COMPOSEEXTRACTINSERTSLICEPASS +#endif // GEN_PASS_DECL_COMPOSEEXTRACTINSERTSLICEPASS +#ifdef GEN_PASS_DEF_COMPOSEEXTRACTINSERTSLICEPASS +namespace impl { + +template +class ComposeExtractInsertSlicePassBase : public ::mlir::OperationPass { +public: + using Base = ComposeExtractInsertSlicePassBase; + + ComposeExtractInsertSlicePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ComposeExtractInsertSlicePassBase(const ComposeExtractInsertSlicePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-compose-extract-insert-slice"); + } + ::llvm::StringRef getArgument() const override { return "gml-compose-extract-insert-slice"; } + + ::llvm::StringRef getDescription() const override { return "Compose tensor.extract_slice/insert_slice ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ComposeExtractInsertSlicePass"); + } + ::llvm::StringRef getName() const override { return "ComposeExtractInsertSlicePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ComposeExtractInsertSlicePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_COMPOSEEXTRACTINSERTSLICEPASS +#endif // GEN_PASS_DEF_COMPOSEEXTRACTINSERTSLICEPASS + +//===----------------------------------------------------------------------===// +// FusionOutliningPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_FUSIONOUTLININGPASS +#undef GEN_PASS_DECL_FUSIONOUTLININGPASS +#endif // GEN_PASS_DECL_FUSIONOUTLININGPASS +#ifdef GEN_PASS_DEF_FUSIONOUTLININGPASS +namespace impl { + +template +class FusionOutliningPassBase : public ::mlir::OperationPass { +public: + using Base = FusionOutliningPassBase; + + FusionOutliningPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FusionOutliningPassBase(const FusionOutliningPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-fusion-outlining"); + } + ::llvm::StringRef getArgument() const override { return "gml-fusion-outlining"; } + + ::llvm::StringRef getDescription() const override { return "Pass to outline fusion regions into functions."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FusionOutliningPass"); + } + ::llvm::StringRef getName() const override { return "FusionOutliningPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FusionOutliningPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_FUSIONOUTLININGPASS +#endif // GEN_PASS_DEF_FUSIONOUTLININGPASS + +//===----------------------------------------------------------------------===// +// FusionPlanningForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_FUSIONPLANNINGFORCPUPASS +struct FusionPlanningForCpuPassOptions { + int64_t vectorSize = 8; +}; +#undef GEN_PASS_DECL_FUSIONPLANNINGFORCPUPASS +#endif // GEN_PASS_DECL_FUSIONPLANNINGFORCPUPASS +#ifdef GEN_PASS_DEF_FUSIONPLANNINGFORCPUPASS +namespace impl { + +template +class FusionPlanningForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = FusionPlanningForCpuPassBase; + + FusionPlanningForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FusionPlanningForCpuPassBase(const FusionPlanningForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-cpu-fusion-planning"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-cpu-fusion-planning"; } + + ::llvm::StringRef getDescription() const override { return "Create fusion clusters."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FusionPlanningForCpuPass"); + } + ::llvm::StringRef getName() const override { return "FusionPlanningForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::gml_st::GmlStDialect>(); + + registry.insert<::mlir::linalg::LinalgDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FusionPlanningForCpuPassBase) + + FusionPlanningForCpuPassBase(const FusionPlanningForCpuPassOptions &options) : FusionPlanningForCpuPassBase() { + vectorSize = options.vectorSize; + } +protected: + ::mlir::Pass::Option vectorSize{*this, "vector-size", ::llvm::cl::desc("Tile size for the innermost dimension of `linalg.map`"), ::llvm::cl::init(8)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_FUSIONPLANNINGFORCPUPASS +#endif // GEN_PASS_DEF_FUSIONPLANNINGFORCPUPASS + +//===----------------------------------------------------------------------===// +// InlineFusionClustersPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_INLINEFUSIONCLUSTERSPASS +#undef GEN_PASS_DECL_INLINEFUSIONCLUSTERSPASS +#endif // GEN_PASS_DECL_INLINEFUSIONCLUSTERSPASS +#ifdef GEN_PASS_DEF_INLINEFUSIONCLUSTERSPASS +namespace impl { + +template +class InlineFusionClustersPassBase : public ::mlir::OperationPass { +public: + using Base = InlineFusionClustersPassBase; + + InlineFusionClustersPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + InlineFusionClustersPassBase(const InlineFusionClustersPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-inline-fusion-clusters"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-inline-fusion-clusters"; } + + ::llvm::StringRef getDescription() const override { return "Replaces all gml_st.fusion op with ops from the region."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("InlineFusionClustersPass"); + } + ::llvm::StringRef getName() const override { return "InlineFusionClustersPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::gml_st::GmlStDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(InlineFusionClustersPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_INLINEFUSIONCLUSTERSPASS +#endif // GEN_PASS_DEF_INLINEFUSIONCLUSTERSPASS + +//===----------------------------------------------------------------------===// +// LowerVectorsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LOWERVECTORSPASS +struct LowerVectorsPassOptions { + bool enableAVX2 = true; + bool flatten = false; +}; +#undef GEN_PASS_DECL_LOWERVECTORSPASS +#endif // GEN_PASS_DECL_LOWERVECTORSPASS +#ifdef GEN_PASS_DEF_LOWERVECTORSPASS +namespace impl { + +template +class LowerVectorsPassBase : public ::mlir::OperationPass { +public: + using Base = LowerVectorsPassBase; + + LowerVectorsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LowerVectorsPassBase(const LowerVectorsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-vectors"); + } + ::llvm::StringRef getArgument() const override { return "lower-vectors"; } + + ::llvm::StringRef getDescription() const override { return "Pass to lower vector operations progressively."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerVectorsPass"); + } + ::llvm::StringRef getName() const override { return "LowerVectorsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + registry.insert<::mlir::vector::VectorDialect>(); + + registry.insert<::mlir::affine::AffineDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerVectorsPassBase) + + LowerVectorsPassBase(const LowerVectorsPassOptions &options) : LowerVectorsPassBase() { + enableAVX2 = options.enableAVX2; + flatten = options.flatten; + } +protected: + ::mlir::Pass::Option enableAVX2{*this, "enable-avx2", ::llvm::cl::desc("Enable specialized lowerings for AVX2."), ::llvm::cl::init(true)}; + ::mlir::Pass::Option flatten{*this, "flatten", ::llvm::cl::desc("Flatten multiple small n-D vector transfers into a large 1-D transfer."), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LOWERVECTORSPASS +#endif // GEN_PASS_DEF_LOWERVECTORSPASS + +//===----------------------------------------------------------------------===// +// NaiveCopyRemovalPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_NAIVECOPYREMOVALPASS +#undef GEN_PASS_DECL_NAIVECOPYREMOVALPASS +#endif // GEN_PASS_DECL_NAIVECOPYREMOVALPASS +#ifdef GEN_PASS_DEF_NAIVECOPYREMOVALPASS +namespace impl { + +template +class NaiveCopyRemovalPassBase : public ::mlir::OperationPass { +public: + using Base = NaiveCopyRemovalPassBase; + + NaiveCopyRemovalPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + NaiveCopyRemovalPassBase(const NaiveCopyRemovalPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("naive-copy-removal"); + } + ::llvm::StringRef getArgument() const override { return "naive-copy-removal"; } + + ::llvm::StringRef getDescription() const override { return "Pass to remove redundant `memref.copy` ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("NaiveCopyRemovalPass"); + } + ::llvm::StringRef getName() const override { return "NaiveCopyRemovalPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(NaiveCopyRemovalPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_NAIVECOPYREMOVALPASS +#endif // GEN_PASS_DEF_NAIVECOPYREMOVALPASS + +//===----------------------------------------------------------------------===// +// OptimizeLinalgOpsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_OPTIMIZELINALGOPSPASS +#undef GEN_PASS_DECL_OPTIMIZELINALGOPSPASS +#endif // GEN_PASS_DECL_OPTIMIZELINALGOPSPASS +#ifdef GEN_PASS_DEF_OPTIMIZELINALGOPSPASS +namespace impl { + +template +class OptimizeLinalgOpsPassBase : public ::mlir::OperationPass { +public: + using Base = OptimizeLinalgOpsPassBase; + + OptimizeLinalgOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OptimizeLinalgOpsPassBase(const OptimizeLinalgOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-optimize-linalg-ops-pass"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-optimize-linalg-ops-pass"; } + + ::llvm::StringRef getDescription() const override { return "Canonicalization patterns for linalg ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OptimizeLinalgOpsPass"); + } + ::llvm::StringRef getName() const override { return "OptimizeLinalgOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::linalg::LinalgDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OptimizeLinalgOpsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_OPTIMIZELINALGOPSPASS +#endif // GEN_PASS_DEF_OPTIMIZELINALGOPSPASS + +//===----------------------------------------------------------------------===// +// PackMatmulPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_PACKMATMULPASS +#undef GEN_PASS_DECL_PACKMATMULPASS +#endif // GEN_PASS_DECL_PACKMATMULPASS +#ifdef GEN_PASS_DEF_PACKMATMULPASS +namespace impl { + +template +class PackMatmulPassBase : public ::mlir::OperationPass { +public: + using Base = PackMatmulPassBase; + + PackMatmulPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + PackMatmulPassBase(const PackMatmulPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-pack-matmul"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-pack-matmul"; } + + ::llvm::StringRef getDescription() const override { return "Pack linalg.matmul as linalg.mmt4d"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("PackMatmulPass"); + } + ::llvm::StringRef getName() const override { return "PackMatmulPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PackMatmulPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_PACKMATMULPASS +#endif // GEN_PASS_DEF_PACKMATMULPASS + +//===----------------------------------------------------------------------===// +// RemoveLabelPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_REMOVELABELPASS +#undef GEN_PASS_DECL_REMOVELABELPASS +#endif // GEN_PASS_DECL_REMOVELABELPASS +#ifdef GEN_PASS_DEF_REMOVELABELPASS +namespace impl { + +template +class RemoveLabelPassBase : public ::mlir::OperationPass { +public: + using Base = RemoveLabelPassBase; + + RemoveLabelPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RemoveLabelPassBase(const RemoveLabelPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("remove-label"); + } + ::llvm::StringRef getArgument() const override { return "remove-label"; } + + ::llvm::StringRef getDescription() const override { return "Remove transformed labels from tiled ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RemoveLabelPass"); + } + ::llvm::StringRef getName() const override { return "RemoveLabelPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RemoveLabelPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_REMOVELABELPASS +#endif // GEN_PASS_DEF_REMOVELABELPASS + +//===----------------------------------------------------------------------===// +// RewriteForallOpPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_REWRITEFORALLOPPASS +#undef GEN_PASS_DECL_REWRITEFORALLOPPASS +#endif // GEN_PASS_DECL_REWRITEFORALLOPPASS +#ifdef GEN_PASS_DEF_REWRITEFORALLOPPASS +namespace impl { + +template +class RewriteForallOpPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteForallOpPassBase; + + RewriteForallOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteForallOpPassBase(const RewriteForallOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-rewrite-forall-ops"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-rewrite-forall-ops"; } + + ::llvm::StringRef getDescription() const override { return "Pass to rewrite scf.forall to scf.for."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteForallOpPass"); + } + ::llvm::StringRef getName() const override { return "RewriteForallOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteForallOpPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_REWRITEFORALLOPPASS +#endif // GEN_PASS_DEF_REWRITEFORALLOPPASS + +//===----------------------------------------------------------------------===// +// RewriteFromElementsOpPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_REWRITEFROMELEMENTSOPPASS +#undef GEN_PASS_DECL_REWRITEFROMELEMENTSOPPASS +#endif // GEN_PASS_DECL_REWRITEFROMELEMENTSOPPASS +#ifdef GEN_PASS_DEF_REWRITEFROMELEMENTSOPPASS +namespace impl { + +template +class RewriteFromElementsOpPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteFromElementsOpPassBase; + + RewriteFromElementsOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteFromElementsOpPassBase(const RewriteFromElementsOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-rewrite-from-elements-ops"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-rewrite-from-elements-ops"; } + + ::llvm::StringRef getDescription() const override { return "Pass to rewrite tensor.from_elements into tensor.insert."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteFromElementsOpPass"); + } + ::llvm::StringRef getName() const override { return "RewriteFromElementsOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteFromElementsOpPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_REWRITEFROMELEMENTSOPPASS +#endif // GEN_PASS_DEF_REWRITEFROMELEMENTSOPPASS + +//===----------------------------------------------------------------------===// +// ScalarizationPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SCALARIZATIONPASS +struct ScalarizationPassOptions { + bool scalarizeAllThlo = true; +}; +#undef GEN_PASS_DECL_SCALARIZATIONPASS +#endif // GEN_PASS_DECL_SCALARIZATIONPASS +#ifdef GEN_PASS_DEF_SCALARIZATIONPASS +namespace impl { + +template +class ScalarizationPassBase : public ::mlir::OperationPass { +public: + using Base = ScalarizationPassBase; + + ScalarizationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ScalarizationPassBase(const ScalarizationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("scalarize"); + } + ::llvm::StringRef getArgument() const override { return "scalarize"; } + + ::llvm::StringRef getDescription() const override { return "Converts ops on tensors with 1 element to scalar ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ScalarizationPass"); + } + ::llvm::StringRef getName() const override { return "ScalarizationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ScalarizationPassBase) + + ScalarizationPassBase(const ScalarizationPassOptions &options) : ScalarizationPassBase() { + scalarizeAllThlo = options.scalarizeAllThlo; + } +protected: + ::mlir::Pass::Option scalarizeAllThlo{*this, "scalarize-all-thlo", ::llvm::cl::desc("Enable scalarization of thlo.concatenate/gather/scatter."), ::llvm::cl::init(true)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_SCALARIZATIONPASS +#endif // GEN_PASS_DEF_SCALARIZATIONPASS + +//===----------------------------------------------------------------------===// +// TileByOnePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TILEBYONEPASS +#undef GEN_PASS_DECL_TILEBYONEPASS +#endif // GEN_PASS_DECL_TILEBYONEPASS +#ifdef GEN_PASS_DEF_TILEBYONEPASS +namespace impl { + +template +class TileByOnePassBase : public ::mlir::OperationPass { +public: + using Base = TileByOnePassBase; + + TileByOnePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TileByOnePassBase(const TileByOnePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-tile-by-one"); + } + ::llvm::StringRef getArgument() const override { return "gml-tile-by-one"; } + + ::llvm::StringRef getDescription() const override { return "Tile all tileable ops by size 1"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TileByOnePass"); + } + ::llvm::StringRef getName() const override { return "TileByOnePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TileByOnePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TILEBYONEPASS +#endif // GEN_PASS_DEF_TILEBYONEPASS + +//===----------------------------------------------------------------------===// +// TilingSoftmaxPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TILINGSOFTMAXPASS +struct TilingSoftmaxPassOptions { + ::llvm::ArrayRef tileSizes; +}; +#undef GEN_PASS_DECL_TILINGSOFTMAXPASS +#endif // GEN_PASS_DECL_TILINGSOFTMAXPASS +#ifdef GEN_PASS_DEF_TILINGSOFTMAXPASS +namespace impl { + +template +class TilingSoftmaxPassBase : public ::mlir::OperationPass { +public: + using Base = TilingSoftmaxPassBase; + + TilingSoftmaxPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TilingSoftmaxPassBase(const TilingSoftmaxPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-tiling-softmax"); + } + ::llvm::StringRef getArgument() const override { return "gml-tiling-softmax"; } + + ::llvm::StringRef getDescription() const override { return "Match, tile, and fuse softmax implementations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TilingSoftmaxPass"); + } + ::llvm::StringRef getName() const override { return "TilingSoftmaxPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TilingSoftmaxPassBase) + + TilingSoftmaxPassBase(const TilingSoftmaxPassOptions &options) : TilingSoftmaxPassBase() { + tileSizes = options.tileSizes; + } +protected: + ::mlir::Pass::ListOption tileSizes{*this, "tile-sizes", ::llvm::cl::desc("Right-aligned tile sizes. Do not tile possible remaining dimensions"), llvm::cl::ZeroOrMore}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TILINGSOFTMAXPASS +#endif // GEN_PASS_DEF_TILINGSOFTMAXPASS + +//===----------------------------------------------------------------------===// +// TransformDotForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMDOTFORCPUPASS +#undef GEN_PASS_DECL_TRANSFORMDOTFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMDOTFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMDOTFORCPUPASS +namespace impl { + +template +class TransformDotForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformDotForCpuPassBase; + + TransformDotForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformDotForCpuPassBase(const TransformDotForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-dot"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-dot"; } + + ::llvm::StringRef getDescription() const override { return "Transform dot ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformDotForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformDotForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformDotForCpuPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMDOTFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMDOTFORCPUPASS + +//===----------------------------------------------------------------------===// +// TransformElementwiseForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMELEMENTWISEFORCPUPASS +struct TransformElementwiseForCpuPassOptions { + int64_t vectorSize = 8; + bool fuseDegenerateReshapes = false; +}; +#undef GEN_PASS_DECL_TRANSFORMELEMENTWISEFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMELEMENTWISEFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMELEMENTWISEFORCPUPASS +namespace impl { + +template +class TransformElementwiseForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformElementwiseForCpuPassBase; + + TransformElementwiseForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformElementwiseForCpuPassBase(const TransformElementwiseForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-elementwise"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-elementwise"; } + + ::llvm::StringRef getDescription() const override { return "Transform elementwise ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformElementwiseForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformElementwiseForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformElementwiseForCpuPassBase) + + TransformElementwiseForCpuPassBase(const TransformElementwiseForCpuPassOptions &options) : TransformElementwiseForCpuPassBase() { + vectorSize = options.vectorSize; + fuseDegenerateReshapes = options.fuseDegenerateReshapes; + } +protected: + ::mlir::Pass::Option vectorSize{*this, "vector-size", ::llvm::cl::desc("Vector size."), ::llvm::cl::init(8)}; + ::mlir::Pass::Option fuseDegenerateReshapes{*this, "fuse-degenerate-reshapes", ::llvm::cl::desc("Fuse through degenerate tensor.expand/collapse_shape"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMELEMENTWISEFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMELEMENTWISEFORCPUPASS + +//===----------------------------------------------------------------------===// +// TransformMmt4DForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMMMT4DFORCPUPASS +#undef GEN_PASS_DECL_TRANSFORMMMT4DFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMMMT4DFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMMMT4DFORCPUPASS +namespace impl { + +template +class TransformMmt4DForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformMmt4DForCpuPassBase; + + TransformMmt4DForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformMmt4DForCpuPassBase(const TransformMmt4DForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-mmt4d"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-mmt4d"; } + + ::llvm::StringRef getDescription() const override { return "Transform linalg.mmt4d ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformMmt4DForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformMmt4DForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformMmt4DForCpuPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMMMT4DFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMMMT4DFORCPUPASS + +//===----------------------------------------------------------------------===// +// TransformPackForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMPACKFORCPUPASS +#undef GEN_PASS_DECL_TRANSFORMPACKFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMPACKFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMPACKFORCPUPASS +namespace impl { + +template +class TransformPackForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformPackForCpuPassBase; + + TransformPackForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformPackForCpuPassBase(const TransformPackForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-pack"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-pack"; } + + ::llvm::StringRef getDescription() const override { return "Transform tensor.pack/unpack ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformPackForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformPackForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformPackForCpuPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMPACKFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMPACKFORCPUPASS + +//===----------------------------------------------------------------------===// +// TransformReduceForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMREDUCEFORCPUPASS +struct TransformReduceForCpuPassOptions { + bool enableHeuristic = false; + int64_t tileSize1D = 32; + int64_t splitRatio1D = 8; + int64_t parallelDimTileSize2D = 4; + int64_t reductionDimTileSize2D = 4; +}; +#undef GEN_PASS_DECL_TRANSFORMREDUCEFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMREDUCEFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMREDUCEFORCPUPASS +namespace impl { + +template +class TransformReduceForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformReduceForCpuPassBase; + + TransformReduceForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformReduceForCpuPassBase(const TransformReduceForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-reduce"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-reduce"; } + + ::llvm::StringRef getDescription() const override { return "Transform reduce ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformReduceForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformReduceForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformReduceForCpuPassBase) + + TransformReduceForCpuPassBase(const TransformReduceForCpuPassOptions &options) : TransformReduceForCpuPassBase() { + enableHeuristic = options.enableHeuristic; + tileSize1D = options.tileSize1D; + splitRatio1D = options.splitRatio1D; + parallelDimTileSize2D = options.parallelDimTileSize2D; + reductionDimTileSize2D = options.reductionDimTileSize2D; + } +protected: + ::mlir::Pass::Option enableHeuristic{*this, "enable_heuristic", ::llvm::cl::desc("Enable heuristic for tiling sizes. Currently only for 1D."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option tileSize1D{*this, "reduction-1d-tile-size", ::llvm::cl::desc("Tile size for a 1D reduction."), ::llvm::cl::init(32)}; + ::mlir::Pass::Option splitRatio1D{*this, "reduction-1d-split-ratio", ::llvm::cl::desc("Ratio used to split the reduction dimension, i.e. tiled reduce op `reduce(tensor)` will be split into a composition of a column reduction `reduce(tensor)` and a row 1D reductionreduce(tensor)`."), ::llvm::cl::init(8)}; + ::mlir::Pass::Option parallelDimTileSize2D{*this, "reduction-2d-parallel-dim-tile-size", ::llvm::cl::desc("Tile size for the parallel dimension of a 2D reduction."), ::llvm::cl::init(4)}; + ::mlir::Pass::Option reductionDimTileSize2D{*this, "reduction-2d-reduction-dim-tile-size", ::llvm::cl::desc("Tile size for the reduction dimension of a 2D reduction."), ::llvm::cl::init(4)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMREDUCEFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMREDUCEFORCPUPASS + +//===----------------------------------------------------------------------===// +// TransformScatterForCpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TRANSFORMSCATTERFORCPUPASS +#undef GEN_PASS_DECL_TRANSFORMSCATTERFORCPUPASS +#endif // GEN_PASS_DECL_TRANSFORMSCATTERFORCPUPASS +#ifdef GEN_PASS_DEF_TRANSFORMSCATTERFORCPUPASS +namespace impl { + +template +class TransformScatterForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformScatterForCpuPassBase; + + TransformScatterForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformScatterForCpuPassBase(const TransformScatterForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-scatter"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-scatter"; } + + ::llvm::StringRef getDescription() const override { return "Transform scatter ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformScatterForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformScatterForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformScatterForCpuPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TRANSFORMSCATTERFORCPUPASS +#endif // GEN_PASS_DEF_TRANSFORMSCATTERFORCPUPASS + +//===----------------------------------------------------------------------===// +// VectorizeCopyPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_VECTORIZECOPYPASS +struct VectorizeCopyPassOptions { + int64_t numElementsThreshold = 8; +}; +#undef GEN_PASS_DECL_VECTORIZECOPYPASS +#endif // GEN_PASS_DECL_VECTORIZECOPYPASS +#ifdef GEN_PASS_DEF_VECTORIZECOPYPASS +namespace impl { + +template +class VectorizeCopyPassBase : public ::mlir::OperationPass { +public: + using Base = VectorizeCopyPassBase; + + VectorizeCopyPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + VectorizeCopyPassBase(const VectorizeCopyPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("vectorize-copy"); + } + ::llvm::StringRef getArgument() const override { return "vectorize-copy"; } + + ::llvm::StringRef getDescription() const override { return "Pass to vectorize `memref.copy`."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("VectorizeCopyPass"); + } + ::llvm::StringRef getName() const override { return "VectorizeCopyPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(VectorizeCopyPassBase) + + VectorizeCopyPassBase(const VectorizeCopyPassOptions &options) : VectorizeCopyPassBase() { + numElementsThreshold = options.numElementsThreshold; + } +protected: + ::mlir::Pass::Option numElementsThreshold{*this, "num-elements-threshold", ::llvm::cl::desc("Max number of elements in src and dst memref for a copy to be vectorized."), ::llvm::cl::init(8)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_VECTORIZECOPYPASS +#endif // GEN_PASS_DEF_VECTORIZECOPYPASS + +//===----------------------------------------------------------------------===// +// VectorizeForCPUPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_VECTORIZEFORCPUPASS +struct VectorizeForCPUPassOptions { + int64_t numElementsThreshold = 128; +}; +#undef GEN_PASS_DECL_VECTORIZEFORCPUPASS +#endif // GEN_PASS_DECL_VECTORIZEFORCPUPASS +#ifdef GEN_PASS_DEF_VECTORIZEFORCPUPASS +namespace impl { + +template +class VectorizeForCPUPassBase : public ::mlir::OperationPass { +public: + using Base = VectorizeForCPUPassBase; + + VectorizeForCPUPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + VectorizeForCPUPassBase(const VectorizeForCPUPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("vectorize-for-cpu"); + } + ::llvm::StringRef getArgument() const override { return "vectorize-for-cpu"; } + + ::llvm::StringRef getDescription() const override { return "Pass to vectorize gml_st.for loops that are tiled perfectly."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("VectorizeForCPUPass"); + } + ::llvm::StringRef getName() const override { return "VectorizeForCPUPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::vector::VectorDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(VectorizeForCPUPassBase) + + VectorizeForCPUPassBase(const VectorizeForCPUPassOptions &options) : VectorizeForCPUPassBase() { + numElementsThreshold = options.numElementsThreshold; + } +protected: + ::mlir::Pass::Option numElementsThreshold{*this, "num-elements-threshold", ::llvm::cl::desc("Number of elements max of the tensor operands in order for the op to be vectorized."), ::llvm::cl::init(128)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_VECTORIZEFORCPUPASS +#endif // GEN_PASS_DEF_VECTORIZEFORCPUPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// AddDebugInfoPass Registration +//===----------------------------------------------------------------------===// + +inline void registerAddDebugInfoPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createAddDebugInfoPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerAddDebugInfoPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createAddDebugInfoPass(); + }); +} + +//===----------------------------------------------------------------------===// +// CollapseShapePass Registration +//===----------------------------------------------------------------------===// + +inline void registerCollapseShapePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createCollapseShapePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerCollapseShapePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createCollapseShapePass(); + }); +} + +//===----------------------------------------------------------------------===// +// CollectStatsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerCollectStatsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createCollectStatsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerCollectStatsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createCollectStatsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ComposeExtractInsertSlicePass Registration +//===----------------------------------------------------------------------===// + +inline void registerComposeExtractInsertSlicePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createComposeExtractInsertSlicePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerComposeExtractInsertSlicePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createComposeExtractInsertSlicePass(); + }); +} + +//===----------------------------------------------------------------------===// +// FusionOutliningPass Registration +//===----------------------------------------------------------------------===// + +inline void registerFusionOutliningPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFusionOutliningPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerFusionOutliningPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFusionOutliningPass(); + }); +} + +//===----------------------------------------------------------------------===// +// FusionPlanningForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerFusionPlanningForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFusionPlanningForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerFusionPlanningForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFusionPlanningForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// InlineFusionClustersPass Registration +//===----------------------------------------------------------------------===// + +inline void registerInlineFusionClustersPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createInlineFusionClustersPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerInlineFusionClustersPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createInlineFusionClustersPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LowerVectorsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLowerVectorsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createLowerVectorsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLowerVectorsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createLowerVectorsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// NaiveCopyRemovalPass Registration +//===----------------------------------------------------------------------===// + +inline void registerNaiveCopyRemovalPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createNaiveCopyRemovalPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerNaiveCopyRemovalPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createNaiveCopyRemovalPass(); + }); +} + +//===----------------------------------------------------------------------===// +// OptimizeLinalgOpsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerOptimizeLinalgOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createOptimizeLinalgOpsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerOptimizeLinalgOpsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createOptimizeLinalgOpsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// PackMatmulPass Registration +//===----------------------------------------------------------------------===// + +inline void registerPackMatmulPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createPackMatmulPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerPackMatmulPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createPackMatmulPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RemoveLabelPass Registration +//===----------------------------------------------------------------------===// + +inline void registerRemoveLabelPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createRemoveLabelPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerRemoveLabelPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createRemoveLabelPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RewriteForallOpPass Registration +//===----------------------------------------------------------------------===// + +inline void registerRewriteForallOpPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteForallOpPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerRewriteForallOpPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteForallOpPass(); + }); +} + +//===----------------------------------------------------------------------===// +// RewriteFromElementsOpPass Registration +//===----------------------------------------------------------------------===// + +inline void registerRewriteFromElementsOpPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteFromElementsOpPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerRewriteFromElementsOpPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createRewriteFromElementsOpPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ScalarizationPass Registration +//===----------------------------------------------------------------------===// + +inline void registerScalarizationPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createScalarizationPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerScalarizationPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createScalarizationPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TileByOnePass Registration +//===----------------------------------------------------------------------===// + +inline void registerTileByOnePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTileByOnePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTileByOnePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTileByOnePass(); + }); +} + +//===----------------------------------------------------------------------===// +// TilingSoftmaxPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTilingSoftmaxPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTilingSoftmaxPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTilingSoftmaxPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTilingSoftmaxPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformDotForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformDotForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformDotForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformDotForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformDotForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformElementwiseForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformElementwiseForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTransformElementwiseForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformElementwiseForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTransformElementwiseForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformMmt4DForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformMmt4DForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformMmt4DForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformMmt4DForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformMmt4DForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformPackForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformPackForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformPackForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformPackForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformPackForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformReduceForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformReduceForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTransformReduceForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformReduceForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createTransformReduceForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TransformScatterForCpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTransformScatterForCpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformScatterForCpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTransformScatterForCpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTransformScatterForCpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// VectorizeCopyPass Registration +//===----------------------------------------------------------------------===// + +inline void registerVectorizeCopyPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createVectorizeCopyPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerVectorizeCopyPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createVectorizeCopyPass(); + }); +} + +//===----------------------------------------------------------------------===// +// VectorizeForCPUPass Registration +//===----------------------------------------------------------------------===// + +inline void registerVectorizeForCPUPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createVectorizeForCPUPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerVectorizeForCPUPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return ::mlir::gml_st::createVectorizeForCPUPass(); + }); +} + +//===----------------------------------------------------------------------===// +// GmlSt Registration +//===----------------------------------------------------------------------===// + +inline void registerGmlStPasses() { + registerAddDebugInfoPass(); + registerCollapseShapePass(); + registerCollectStatsPass(); + registerComposeExtractInsertSlicePass(); + registerFusionOutliningPass(); + registerFusionPlanningForCpuPass(); + registerInlineFusionClustersPass(); + registerLowerVectorsPass(); + registerNaiveCopyRemovalPass(); + registerOptimizeLinalgOpsPass(); + registerPackMatmulPass(); + registerRemoveLabelPass(); + registerRewriteForallOpPass(); + registerRewriteFromElementsOpPass(); + registerScalarizationPass(); + registerTileByOnePass(); + registerTilingSoftmaxPass(); + registerTransformDotForCpuPass(); + registerTransformElementwiseForCpuPass(); + registerTransformMmt4DForCpuPass(); + registerTransformPackForCpuPass(); + registerTransformReduceForCpuPass(); + registerTransformScatterForCpuPass(); + registerVectorizeCopyPass(); + registerVectorizeForCPUPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class AddDebugInfoPassBase : public ::mlir::OperationPass { +public: + using Base = AddDebugInfoPassBase; + + AddDebugInfoPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + AddDebugInfoPassBase(const AddDebugInfoPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("add-debug-info"); + } + ::llvm::StringRef getArgument() const override { return "add-debug-info"; } + + ::llvm::StringRef getDescription() const override { return "Add debug info for the whole module"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("AddDebugInfoPass"); + } + ::llvm::StringRef getName() const override { return "AddDebugInfoPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(AddDebugInfoPassBase) + +protected: +}; + +template +class CollapseShapePassBase : public ::mlir::OperationPass { +public: + using Base = CollapseShapePassBase; + + CollapseShapePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + CollapseShapePassBase(const CollapseShapePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-collapse-shape"); + } + ::llvm::StringRef getArgument() const override { return "gml-collapse-shape"; } + + ::llvm::StringRef getDescription() const override { return "Collapse dimensions of bcasts, reductions, and cwise ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("CollapseShapePass"); + } + ::llvm::StringRef getName() const override { return "CollapseShapePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CollapseShapePassBase) + +protected: + ::mlir::Pass::Option retainTrailingDims{*this, "retain-trailing-dims", ::llvm::cl::desc("Number of trailing dimensions that will not be collapsed."), ::llvm::cl::init(0)}; +}; + +template +class CollectStatsPassBase : public ::mlir::OperationPass { +public: + using Base = CollectStatsPassBase; + + CollectStatsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + CollectStatsPassBase(const CollectStatsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("collect-stats"); + } + ::llvm::StringRef getArgument() const override { return "collect-stats"; } + + ::llvm::StringRef getDescription() const override { return "Print stats about tileable ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("CollectStatsPass"); + } + ::llvm::StringRef getName() const override { return "CollectStatsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CollectStatsPassBase) + +protected: +}; + +template +class ComposeExtractInsertSlicePassBase : public ::mlir::OperationPass { +public: + using Base = ComposeExtractInsertSlicePassBase; + + ComposeExtractInsertSlicePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ComposeExtractInsertSlicePassBase(const ComposeExtractInsertSlicePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-compose-extract-insert-slice"); + } + ::llvm::StringRef getArgument() const override { return "gml-compose-extract-insert-slice"; } + + ::llvm::StringRef getDescription() const override { return "Compose tensor.extract_slice/insert_slice ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ComposeExtractInsertSlicePass"); + } + ::llvm::StringRef getName() const override { return "ComposeExtractInsertSlicePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ComposeExtractInsertSlicePassBase) + +protected: +}; + +template +class FusionOutliningPassBase : public ::mlir::OperationPass { +public: + using Base = FusionOutliningPassBase; + + FusionOutliningPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FusionOutliningPassBase(const FusionOutliningPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-fusion-outlining"); + } + ::llvm::StringRef getArgument() const override { return "gml-fusion-outlining"; } + + ::llvm::StringRef getDescription() const override { return "Pass to outline fusion regions into functions."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FusionOutliningPass"); + } + ::llvm::StringRef getName() const override { return "FusionOutliningPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FusionOutliningPassBase) + +protected: +}; + +template +class FusionPlanningForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = FusionPlanningForCpuPassBase; + + FusionPlanningForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FusionPlanningForCpuPassBase(const FusionPlanningForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-cpu-fusion-planning"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-cpu-fusion-planning"; } + + ::llvm::StringRef getDescription() const override { return "Create fusion clusters."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FusionPlanningForCpuPass"); + } + ::llvm::StringRef getName() const override { return "FusionPlanningForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::gml_st::GmlStDialect>(); + + registry.insert<::mlir::linalg::LinalgDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FusionPlanningForCpuPassBase) + +protected: + ::mlir::Pass::Option vectorSize{*this, "vector-size", ::llvm::cl::desc("Tile size for the innermost dimension of `linalg.map`"), ::llvm::cl::init(8)}; +}; + +template +class InlineFusionClustersPassBase : public ::mlir::OperationPass { +public: + using Base = InlineFusionClustersPassBase; + + InlineFusionClustersPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + InlineFusionClustersPassBase(const InlineFusionClustersPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-inline-fusion-clusters"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-inline-fusion-clusters"; } + + ::llvm::StringRef getDescription() const override { return "Replaces all gml_st.fusion op with ops from the region."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("InlineFusionClustersPass"); + } + ::llvm::StringRef getName() const override { return "InlineFusionClustersPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::gml_st::GmlStDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(InlineFusionClustersPassBase) + +protected: +}; + +template +class LowerVectorsPassBase : public ::mlir::OperationPass { +public: + using Base = LowerVectorsPassBase; + + LowerVectorsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LowerVectorsPassBase(const LowerVectorsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-vectors"); + } + ::llvm::StringRef getArgument() const override { return "lower-vectors"; } + + ::llvm::StringRef getDescription() const override { return "Pass to lower vector operations progressively."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerVectorsPass"); + } + ::llvm::StringRef getName() const override { return "LowerVectorsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::LLVM::LLVMDialect>(); + + registry.insert<::mlir::vector::VectorDialect>(); + + registry.insert<::mlir::affine::AffineDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerVectorsPassBase) + +protected: + ::mlir::Pass::Option enableAVX2{*this, "enable-avx2", ::llvm::cl::desc("Enable specialized lowerings for AVX2."), ::llvm::cl::init(true)}; + ::mlir::Pass::Option flatten{*this, "flatten", ::llvm::cl::desc("Flatten multiple small n-D vector transfers into a large 1-D transfer."), ::llvm::cl::init(false)}; +}; + +template +class NaiveCopyRemovalPassBase : public ::mlir::OperationPass { +public: + using Base = NaiveCopyRemovalPassBase; + + NaiveCopyRemovalPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + NaiveCopyRemovalPassBase(const NaiveCopyRemovalPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("naive-copy-removal"); + } + ::llvm::StringRef getArgument() const override { return "naive-copy-removal"; } + + ::llvm::StringRef getDescription() const override { return "Pass to remove redundant `memref.copy` ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("NaiveCopyRemovalPass"); + } + ::llvm::StringRef getName() const override { return "NaiveCopyRemovalPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::memref::MemRefDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(NaiveCopyRemovalPassBase) + +protected: +}; + +template +class OptimizeLinalgOpsPassBase : public ::mlir::OperationPass { +public: + using Base = OptimizeLinalgOpsPassBase; + + OptimizeLinalgOpsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + OptimizeLinalgOpsPassBase(const OptimizeLinalgOpsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-optimize-linalg-ops-pass"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-optimize-linalg-ops-pass"; } + + ::llvm::StringRef getDescription() const override { return "Canonicalization patterns for linalg ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("OptimizeLinalgOpsPass"); + } + ::llvm::StringRef getName() const override { return "OptimizeLinalgOpsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::arith::ArithDialect>(); + + registry.insert<::mlir::linalg::LinalgDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OptimizeLinalgOpsPassBase) + +protected: +}; + +template +class PackMatmulPassBase : public ::mlir::OperationPass { +public: + using Base = PackMatmulPassBase; + + PackMatmulPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + PackMatmulPassBase(const PackMatmulPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-pack-matmul"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-pack-matmul"; } + + ::llvm::StringRef getDescription() const override { return "Pack linalg.matmul as linalg.mmt4d"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("PackMatmulPass"); + } + ::llvm::StringRef getName() const override { return "PackMatmulPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PackMatmulPassBase) + +protected: +}; + +template +class RemoveLabelPassBase : public ::mlir::OperationPass { +public: + using Base = RemoveLabelPassBase; + + RemoveLabelPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RemoveLabelPassBase(const RemoveLabelPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("remove-label"); + } + ::llvm::StringRef getArgument() const override { return "remove-label"; } + + ::llvm::StringRef getDescription() const override { return "Remove transformed labels from tiled ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RemoveLabelPass"); + } + ::llvm::StringRef getName() const override { return "RemoveLabelPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RemoveLabelPassBase) + +protected: +}; + +template +class RewriteForallOpPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteForallOpPassBase; + + RewriteForallOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteForallOpPassBase(const RewriteForallOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-rewrite-forall-ops"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-rewrite-forall-ops"; } + + ::llvm::StringRef getDescription() const override { return "Pass to rewrite scf.forall to scf.for."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteForallOpPass"); + } + ::llvm::StringRef getName() const override { return "RewriteForallOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteForallOpPassBase) + +protected: +}; + +template +class RewriteFromElementsOpPassBase : public ::mlir::OperationPass { +public: + using Base = RewriteFromElementsOpPassBase; + + RewriteFromElementsOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + RewriteFromElementsOpPassBase(const RewriteFromElementsOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-st-rewrite-from-elements-ops"); + } + ::llvm::StringRef getArgument() const override { return "gml-st-rewrite-from-elements-ops"; } + + ::llvm::StringRef getDescription() const override { return "Pass to rewrite tensor.from_elements into tensor.insert."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("RewriteFromElementsOpPass"); + } + ::llvm::StringRef getName() const override { return "RewriteFromElementsOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RewriteFromElementsOpPassBase) + +protected: +}; + +template +class ScalarizationPassBase : public ::mlir::OperationPass { +public: + using Base = ScalarizationPassBase; + + ScalarizationPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ScalarizationPassBase(const ScalarizationPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("scalarize"); + } + ::llvm::StringRef getArgument() const override { return "scalarize"; } + + ::llvm::StringRef getDescription() const override { return "Converts ops on tensors with 1 element to scalar ops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ScalarizationPass"); + } + ::llvm::StringRef getName() const override { return "ScalarizationPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ScalarizationPassBase) + +protected: + ::mlir::Pass::Option scalarizeAllThlo{*this, "scalarize-all-thlo", ::llvm::cl::desc("Enable scalarization of thlo.concatenate/gather/scatter."), ::llvm::cl::init(true)}; +}; + +template +class TileByOnePassBase : public ::mlir::OperationPass { +public: + using Base = TileByOnePassBase; + + TileByOnePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TileByOnePassBase(const TileByOnePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-tile-by-one"); + } + ::llvm::StringRef getArgument() const override { return "gml-tile-by-one"; } + + ::llvm::StringRef getDescription() const override { return "Tile all tileable ops by size 1"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TileByOnePass"); + } + ::llvm::StringRef getName() const override { return "TileByOnePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TileByOnePassBase) + +protected: +}; + +template +class TilingSoftmaxPassBase : public ::mlir::OperationPass { +public: + using Base = TilingSoftmaxPassBase; + + TilingSoftmaxPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TilingSoftmaxPassBase(const TilingSoftmaxPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gml-tiling-softmax"); + } + ::llvm::StringRef getArgument() const override { return "gml-tiling-softmax"; } + + ::llvm::StringRef getDescription() const override { return "Match, tile, and fuse softmax implementations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TilingSoftmaxPass"); + } + ::llvm::StringRef getName() const override { return "TilingSoftmaxPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TilingSoftmaxPassBase) + +protected: + ::mlir::Pass::ListOption tileSizes{*this, "tile-sizes", ::llvm::cl::desc("Right-aligned tile sizes. Do not tile possible remaining dimensions"), llvm::cl::ZeroOrMore}; +}; + +template +class TransformDotForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformDotForCpuPassBase; + + TransformDotForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformDotForCpuPassBase(const TransformDotForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-dot"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-dot"; } + + ::llvm::StringRef getDescription() const override { return "Transform dot ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformDotForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformDotForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformDotForCpuPassBase) + +protected: +}; + +template +class TransformElementwiseForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformElementwiseForCpuPassBase; + + TransformElementwiseForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformElementwiseForCpuPassBase(const TransformElementwiseForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-elementwise"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-elementwise"; } + + ::llvm::StringRef getDescription() const override { return "Transform elementwise ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformElementwiseForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformElementwiseForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformElementwiseForCpuPassBase) + +protected: + ::mlir::Pass::Option vectorSize{*this, "vector-size", ::llvm::cl::desc("Vector size."), ::llvm::cl::init(8)}; + ::mlir::Pass::Option fuseDegenerateReshapes{*this, "fuse-degenerate-reshapes", ::llvm::cl::desc("Fuse through degenerate tensor.expand/collapse_shape"), ::llvm::cl::init(false)}; +}; + +template +class TransformMmt4DForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformMmt4DForCpuPassBase; + + TransformMmt4DForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformMmt4DForCpuPassBase(const TransformMmt4DForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-mmt4d"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-mmt4d"; } + + ::llvm::StringRef getDescription() const override { return "Transform linalg.mmt4d ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformMmt4DForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformMmt4DForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformMmt4DForCpuPassBase) + +protected: +}; + +template +class TransformPackForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformPackForCpuPassBase; + + TransformPackForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformPackForCpuPassBase(const TransformPackForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-pack"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-pack"; } + + ::llvm::StringRef getDescription() const override { return "Transform tensor.pack/unpack ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformPackForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformPackForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformPackForCpuPassBase) + +protected: +}; + +template +class TransformReduceForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformReduceForCpuPassBase; + + TransformReduceForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformReduceForCpuPassBase(const TransformReduceForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-reduce"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-reduce"; } + + ::llvm::StringRef getDescription() const override { return "Transform reduce ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformReduceForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformReduceForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformReduceForCpuPassBase) + +protected: + ::mlir::Pass::Option enableHeuristic{*this, "enable_heuristic", ::llvm::cl::desc("Enable heuristic for tiling sizes. Currently only for 1D."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option tileSize1D{*this, "reduction-1d-tile-size", ::llvm::cl::desc("Tile size for a 1D reduction."), ::llvm::cl::init(32)}; + ::mlir::Pass::Option splitRatio1D{*this, "reduction-1d-split-ratio", ::llvm::cl::desc("Ratio used to split the reduction dimension, i.e. tiled reduce op `reduce(tensor)` will be split into a composition of a column reduction `reduce(tensor)` and a row 1D reductionreduce(tensor)`."), ::llvm::cl::init(8)}; + ::mlir::Pass::Option parallelDimTileSize2D{*this, "reduction-2d-parallel-dim-tile-size", ::llvm::cl::desc("Tile size for the parallel dimension of a 2D reduction."), ::llvm::cl::init(4)}; + ::mlir::Pass::Option reductionDimTileSize2D{*this, "reduction-2d-reduction-dim-tile-size", ::llvm::cl::desc("Tile size for the reduction dimension of a 2D reduction."), ::llvm::cl::init(4)}; +}; + +template +class TransformScatterForCpuPassBase : public ::mlir::OperationPass { +public: + using Base = TransformScatterForCpuPassBase; + + TransformScatterForCpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TransformScatterForCpuPassBase(const TransformScatterForCpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("xla-cpu-transform-scatter"); + } + ::llvm::StringRef getArgument() const override { return "xla-cpu-transform-scatter"; } + + ::llvm::StringRef getDescription() const override { return "Transform scatter ops for running on CPU"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TransformScatterForCpuPass"); + } + ::llvm::StringRef getName() const override { return "TransformScatterForCpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TransformScatterForCpuPassBase) + +protected: +}; + +template +class VectorizeCopyPassBase : public ::mlir::OperationPass { +public: + using Base = VectorizeCopyPassBase; + + VectorizeCopyPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + VectorizeCopyPassBase(const VectorizeCopyPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("vectorize-copy"); + } + ::llvm::StringRef getArgument() const override { return "vectorize-copy"; } + + ::llvm::StringRef getDescription() const override { return "Pass to vectorize `memref.copy`."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("VectorizeCopyPass"); + } + ::llvm::StringRef getName() const override { return "VectorizeCopyPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(VectorizeCopyPassBase) + +protected: + ::mlir::Pass::Option numElementsThreshold{*this, "num-elements-threshold", ::llvm::cl::desc("Max number of elements in src and dst memref for a copy to be vectorized."), ::llvm::cl::init(8)}; +}; + +template +class VectorizeForCPUPassBase : public ::mlir::OperationPass { +public: + using Base = VectorizeForCPUPassBase; + + VectorizeForCPUPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + VectorizeForCPUPassBase(const VectorizeForCPUPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("vectorize-for-cpu"); + } + ::llvm::StringRef getArgument() const override { return "vectorize-for-cpu"; } + + ::llvm::StringRef getDescription() const override { return "Pass to vectorize gml_st.for loops that are tiled perfectly."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("VectorizeForCPUPass"); + } + ::llvm::StringRef getName() const override { return "VectorizeForCPUPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert<::mlir::vector::VectorDialect>(); + + registry.insert<::mlir::tensor::TensorDialect>(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(VectorizeForCPUPassBase) + +protected: + ::mlir::Pass::Option numElementsThreshold{*this, "num-elements-threshold", ::llvm::cl::desc("Number of elements max of the tensor operands in order for the op to be vectorized."), ::llvm::cl::init(128)}; +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_transforms/gml_st/transforms/transforms.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_transforms/gml_st/transforms/transforms.h new file mode 100644 index 0000000000000000000000000000000000000000..97d0ef0cf750a3ded9c56a571198dc1f4a23614f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gml_st_transforms/gml_st/transforms/transforms.h @@ -0,0 +1,47 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_GML_ST_TRANSFORMS_TRANSFORMS_H +#define MLIR_HLO_GML_ST_TRANSFORMS_TRANSFORMS_H + +#include "mlir/IR/Operation.h" + +namespace mlir { +namespace gml_st { + +constexpr llvm::StringRef kPerfectlyTiledLoopLabel = + "__perfectly_tiled_loop_label__"; + +static constexpr llvm::StringRef kTransformedLabel = "__transformed_label__"; + +template +bool hasSingleElement(ShapedTy type) { + return type.hasStaticShape() && type.getNumElements() == 1; +} +bool hasSingleElementOperandsAndResults(Operation *op); + +// Sets the attribute to the `op` that indicates that the op was transformed. +void setLabel(Operation *op, StringRef name); + +// Removes the attribute that indicates that it was transformed. +void removeLabel(Operation *op, StringRef name); + +// Checks if `op` has the attribute that indicates that it was transformed. +bool hasLabel(Operation *op, StringRef name); + +} // namespace gml_st +} // namespace mlir + +#endif // MLIR_HLO_GML_ST_TRANSFORMS_TRANSFORMS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gpu_transforms_passes_inc_gen/transforms/gpu_passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gpu_transforms_passes_inc_gen/transforms/gpu_passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..c82815463038ca519a4a3ffba5644b31df9d92bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/gpu_transforms_passes_inc_gen/transforms/gpu_passes.h.inc @@ -0,0 +1,280 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_GPUKERNELTONVVMPASS +#define GEN_PASS_DECL_GPUKERNELTOROCDLPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// GpuKernelToNVVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_GPUKERNELTONVVMPASS +#undef GEN_PASS_DECL_GPUKERNELTONVVMPASS +#endif // GEN_PASS_DECL_GPUKERNELTONVVMPASS +#ifdef GEN_PASS_DEF_GPUKERNELTONVVMPASS +namespace impl { + +template +class GpuKernelToNVVMPassBase : public ::mlir::OperationPass { +public: + using Base = GpuKernelToNVVMPassBase; + + GpuKernelToNVVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuKernelToNVVMPassBase(const GpuKernelToNVVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-kernel-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "gpu-kernel-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Pass to transform a gpu module to nvvm."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuKernelToNVVMPass"); + } + ::llvm::StringRef getName() const override { return "GpuKernelToNVVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuKernelToNVVMPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_GPUKERNELTONVVMPASS +#endif // GEN_PASS_DEF_GPUKERNELTONVVMPASS + +//===----------------------------------------------------------------------===// +// GpuKernelToROCDLPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_GPUKERNELTOROCDLPASS +#undef GEN_PASS_DECL_GPUKERNELTOROCDLPASS +#endif // GEN_PASS_DECL_GPUKERNELTOROCDLPASS +#ifdef GEN_PASS_DEF_GPUKERNELTOROCDLPASS +namespace impl { + +template +class GpuKernelToROCDLPassBase : public ::mlir::OperationPass { +public: + using Base = GpuKernelToROCDLPassBase; + + GpuKernelToROCDLPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuKernelToROCDLPassBase(const GpuKernelToROCDLPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-kernel-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "gpu-kernel-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Pass to transform a gpu module to rocdl."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuKernelToROCDLPass"); + } + ::llvm::StringRef getName() const override { return "GpuKernelToROCDLPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuKernelToROCDLPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_GPUKERNELTOROCDLPASS +#endif // GEN_PASS_DEF_GPUKERNELTOROCDLPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// GpuKernelToNVVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerGpuKernelToNVVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuKernelToNvvmPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerGpuKernelToNVVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuKernelToNvvmPass(); + }); +} + +//===----------------------------------------------------------------------===// +// GpuKernelToROCDLPass Registration +//===----------------------------------------------------------------------===// + +inline void registerGpuKernelToROCDLPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuKernelToRocdlPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerGpuKernelToROCDLPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuKernelToRocdlPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LMHLOGPUTransforms Registration +//===----------------------------------------------------------------------===// + +inline void registerLMHLOGPUTransformsPasses() { + registerGpuKernelToNVVMPass(); + registerGpuKernelToROCDLPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class GpuKernelToNVVMPassBase : public ::mlir::OperationPass { +public: + using Base = GpuKernelToNVVMPassBase; + + GpuKernelToNVVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuKernelToNVVMPassBase(const GpuKernelToNVVMPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-kernel-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "gpu-kernel-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Pass to transform a gpu module to nvvm."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuKernelToNVVMPass"); + } + ::llvm::StringRef getName() const override { return "GpuKernelToNVVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuKernelToNVVMPassBase) + +protected: +}; + +template +class GpuKernelToROCDLPassBase : public ::mlir::OperationPass { +public: + using Base = GpuKernelToROCDLPassBase; + + GpuKernelToROCDLPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuKernelToROCDLPassBase(const GpuKernelToROCDLPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-kernel-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "gpu-kernel-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Pass to transform a gpu module to rocdl."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuKernelToROCDLPass"); + } + ::llvm::StringRef getName() const override { return "GpuKernelToROCDLPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + registry.insert(); + + registry.insert(); + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuKernelToROCDLPassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_dialect_registration/mhlo/IR/register.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_dialect_registration/mhlo/IR/register.h new file mode 100644 index 0000000000000000000000000000000000000000..47a89a707115a15f161977c4ad089f37e2d0a6a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_dialect_registration/mhlo/IR/register.h @@ -0,0 +1,28 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_DIALECT_MHLO_IR_REGISTER_H_ +#define MLIR_HLO_DIALECT_MHLO_IR_REGISTER_H_ + +namespace mlir { +class DialectRegistry; +namespace mhlo { + +// Add chlo and mhlo dialects to the provided registry. +void registerAllMhloDialects(DialectRegistry ®istry); +} // namespace mhlo +} // namespace mlir + +#endif // MLIR_HLO_DIALECT_MHLO_IR_REGISTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_legalize_to_stablehlo/mhlo/transforms/rewriters.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_legalize_to_stablehlo/mhlo/transforms/rewriters.h new file mode 100644 index 0000000000000000000000000000000000000000..2d5bbfa8887653582238e8e4985f31aa16393ee9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_legalize_to_stablehlo/mhlo/transforms/rewriters.h @@ -0,0 +1,231 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H +#define MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H + +#include +#include + +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +namespace bufferization { +class BufferizeTypeConverter; +} // namespace bufferization +namespace mhlo { + +// Rewrite patterns for broadcast to equivalent broadcast_in_dim legalization. +void populateBroadcastToBroadcastInDimPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering a general dot product. +void populateGeneralDotOpLoweringPatterns(RewritePatternSet *patterns, + MLIRContext *ctx); + +// Collection of rewrite patterns for lowering complex operations to equivalent +// float operations. +void populateComplexLoweringPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +void populateOptimizeMhloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for create_token to equivalent after_all legalization. +void populateCreateTokenToAfterAllPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for cross-replica-sum to equivalent all_reduce legalization. +void populateCrossReplicaSumToAllReducePatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for dot to equivalent dot_general legalization. +void populateDotToDotGeneralPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for einsum to equivalent dot_general legalization. +void populateEinsumToDotGeneralPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for gather to equivalent torch index select legalization. +void populateGatherToTorchIndexSelectPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +// Rewrite patterns for torch index select to equivalent gather legalization. +void populateTorchIndexSelectToGatherPatterns(mlir::MLIRContext *context, + RewritePatternSet *patterns); + +void populateMhloToStdPatterns(RewritePatternSet *patterns, MLIRContext *ctx); + +// Collection of rewrite patterns for lowering all mhlo ops to their +// lmhlo counterparts. +void populateDynamicHloToLhloConversionPattern( + MLIRContext *context, bufferization::BufferizeTypeConverter *converter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to LHLO dialect. +void populateHloToLhloConversionPattern( + MLIRContext *context, bufferization::BufferizeTypeConverter *converter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to arithmetic dialect. +void populateHloToArithmeticConversionPatterns(RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering pointwise HLO ops with scalar +// arguments to arithmetic dialect. +void populateScalarHloToArithmeticConversionPatterns( + MLIRContext *context, TypeConverter &typeConverter, + RewritePatternSet *patterns, + llvm::function_ref filterFn = nullptr); + +// Collection of rewrite patterns for lowering of shape operations from the HLO +// dialect to the standard dialect. +void populateHloShapeOpsToStandardConversionPattern( + MLIRContext *context, TypeConverter &typeConverter, + RewritePatternSet *patterns); + +// Collection of rewrite patterns for lowering of HLO to Linalg dialect. +void populateHloToLinalgConversionPattern(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns, + bool enablePrimitiveOps = false); + +// Collection of rewrite patterns for lowering of HLO dim operations. +void populateShapeComputationPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Converter to signless intergers to be used with linalg conversion patterns. +std::unique_ptr createHloToLinalgTypeConverter(); + +// Sets up legality definitions for materializing broadcasts. +void setupMaterializeBroadcastsLegality(MLIRContext *context, + ConversionTarget *conversionTarget); + +// Populates a collection of rewrite patterns for materializing broadcast +// attributes to equivalent sequences of ops. +void populateMaterializeBroadcastsPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populates a collection of rewrite patterns to realize element-wise operations +// on ranked tensors where possible. +void populateTransformUnrankedHloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +void populateDynamicShapeFusionPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// batch_norm_inference into constituent HLO ops. +void populateUnfuseBatchNormInferencePattern(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// batch_norm_training into constituent HLO ops. +void populateUnfuseBatchNormTrainingPattern(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate a collection of conversion patterns for un-fusing +// // batch_norm_inference and batch_norm_training into constituent HLO ops. +inline void populateUnfuseBatchNormPatterns(MLIRContext *context, + RewritePatternSet *patterns) { + populateUnfuseBatchNormInferencePattern(context, patterns); + populateUnfuseBatchNormTrainingPattern(context, patterns); +} + +// Populates patterns that translate the trigonometric operations from the +// standard dialect to approximations that do not use intrinsics. +void populateTrigonometricToApproximationPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate patterns to prepare moving dynamic broadcasts up over element-wise +// operations and broadcast the operands rather than the result. This will +// eventually allow for larger fusions. +void populateMergeAssumingOpsPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populate patterns for iterative shape reification. +void populateShapeReificationPatterns(MLIRContext *, RewritePatternSet *); + +// Populate patterns to group reduction and parallel dimensions of reduction +// operations and realize them through equivalent 1D or 2D reductions. +void populateGroupReductionDimensionsPatterns(MLIRContext *context, + RewritePatternSet *patterns, + bool preferColumnsReductions); + +/// Populate rank specialization clustering and lowering patterns. +void populateRankSpecializationClusterPatterns(MLIRContext *context, + RewritePatternSet *patterns); +void populateRankSpecializationToSCFPatterns(MLIRContext *context, + RewritePatternSet *patterns, + int64_t maxTargetRank); + +/// Populate sparse tensor specific rewriting patterns. +void populateSparseRewritingPatterns(RewritePatternSet *patterns, + MLIRContext *ctx); + +/// Populates sparse ops in CHLO to linalg rewriting patterns. +void populateLegalizeSparseCHLOPatterns(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns); + +/// Populate sparse ops to mhlo.CustomCall patterns. +void populateLegalizeSparseOpsToCustomCallPatterns(MLIRContext *context, + TypeConverter &typeConverter, + RewritePatternSet *patterns); + +} // namespace mhlo + +namespace chlo { + +// Populates a collection of conversion patterns for legalizing broadcasting +// client-HLO to their non-broadcasting counterparts. +void populateChloBroadcastingPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +// Populates a collection of conversion patterns for legalizing client-HLO to +// HLO by decomposing client-operations to corresponding sequences of more +// primitive operations. This does not include the +// PopulateChloBroadcastingPatterns above. +void populateDecomposeChloPatterns(MLIRContext *context, + RewritePatternSet *patterns); + +} // namespace chlo + +namespace stablehlo { + +// Populates MHLO ops to StableHLO ops rewriting patterns. +// Also see `stablehlo::registerFuncOpsForTypeConversion` for helper patterns +// which make sure `func.func`, `func.call` and `func.return` which involve +// illegal types also get converted. +void populateHloToStablehloPatterns(RewritePatternSet *patterns, + TypeConverter *converter, + MLIRContext *context, + bool allowExperimentalFeatures); + +// Populates StableHLO ops to MHLO ops rewriting patterns. +// Also see `stablehlo::registerFuncOpsForTypeConversion` for helper patterns +// which make sure `func.func`, `func.call` and `func.return` which involve +// illegal types also get converted. +void populateStablehloToHloPatterns(RewritePatternSet *patterns, + TypeConverter *converter, + MLIRContext *context); + +} // namespace stablehlo + +} // namespace mlir + +#endif // MLIR_HLO_MHLO_TRANSFORMS_REWRITERS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_attrs_inc_gen/mhlo/IR/hlo_ops_attrs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_attrs_inc_gen/mhlo/IR/hlo_ops_attrs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..588fbcdb58bb30fc34a3c2c6221e0128ad1ee325 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_attrs_inc_gen/mhlo/IR/hlo_ops_attrs.h.inc @@ -0,0 +1,389 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace mhlo { +class ArgResultAliasAttr; +class ChannelHandleAttr; +class ComparisonDirectionAttr; +class ComparisonTypeAttr; +class ConvDimensionNumbersAttr; +class CrossProgramPrefetchAttr; +class CustomCallScheduleAttr; +class DequantizeModeAttr; +class DomainKindAttr; +class DotDimensionNumbersAttr; +class FftTypeAttr; +class FusionKindAttr; +class GatherDimensionNumbersAttr; +class OutputOperandAliasAttr; +class PrecisionAttr; +class RngAlgorithmAttr; +class RngDistributionAttr; +class ScatterDimensionNumbersAttr; +class TransposeAttr; +class TypeExtensionsAttr; +namespace detail { +struct ArgResultAliasAttrStorage; +} // namespace detail +class ArgResultAliasAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ArgResultAliasAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef argTupleIndices, int64_t resultIndex, ::llvm::ArrayRef resultTupleIndices, bool isMustAlias); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"result_alias"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getArgTupleIndices() const; + int64_t getResultIndex() const; + ::llvm::ArrayRef getResultTupleIndices() const; + bool getIsMustAlias() const; +}; +namespace detail { +struct ChannelHandleAttrStorage; +} // namespace detail +class ChannelHandleAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ChannelHandleAttr get(::mlir::MLIRContext *context, int64_t handle, int64_t type); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"channel_handle"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getHandle() const; + int64_t getType() const; +}; +namespace detail { +struct ComparisonDirectionAttrStorage; +} // namespace detail +class ComparisonDirectionAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ComparisonDirectionAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::ComparisonDirection value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"comparison_direction"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::ComparisonDirection getValue() const; +}; +namespace detail { +struct ComparisonTypeAttrStorage; +} // namespace detail +class ComparisonTypeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ComparisonTypeAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::ComparisonType value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"comparison_type"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::ComparisonType getValue() const; +}; +namespace detail { +struct ConvDimensionNumbersAttrStorage; +} // namespace detail +class ConvDimensionNumbersAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ConvDimensionNumbersAttr get(::mlir::MLIRContext *context, int64_t inputBatchDimension, int64_t inputFeatureDimension, ::llvm::ArrayRef inputSpatialDimensions, int64_t kernelInputFeatureDimension, int64_t kernelOutputFeatureDimension, ::llvm::ArrayRef kernelSpatialDimensions, int64_t outputBatchDimension, int64_t outputFeatureDimension, ::llvm::ArrayRef outputSpatialDimensions); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"conv"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getInputBatchDimension() const; + int64_t getInputFeatureDimension() const; + ::llvm::ArrayRef getInputSpatialDimensions() const; + int64_t getKernelInputFeatureDimension() const; + int64_t getKernelOutputFeatureDimension() const; + ::llvm::ArrayRef getKernelSpatialDimensions() const; + int64_t getOutputBatchDimension() const; + int64_t getOutputFeatureDimension() const; + ::llvm::ArrayRef getOutputSpatialDimensions() const; +}; +namespace detail { +struct CrossProgramPrefetchAttrStorage; +} // namespace detail +class CrossProgramPrefetchAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static CrossProgramPrefetchAttr get(::mlir::MLIRContext *context, int64_t parameter, ::llvm::ArrayRef indices, std::optional offset); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"cross_program_prefetch"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getParameter() const; + ::llvm::ArrayRef getIndices() const; + std::optional getOffset() const; +}; +namespace detail { +struct CustomCallScheduleAttrStorage; +} // namespace detail +class CustomCallScheduleAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static CustomCallScheduleAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::CustomCallSchedule value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"custom_call_schedule"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::CustomCallSchedule getValue() const; +}; +namespace detail { +struct DequantizeModeAttrStorage; +} // namespace detail +class DequantizeModeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static DequantizeModeAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::DequantizeMode value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"dequantize_mode"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::DequantizeMode getValue() const; +}; +namespace detail { +struct DomainKindAttrStorage; +} // namespace detail +class DomainKindAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static DomainKindAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::DomainKind value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"kind"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::DomainKind getValue() const; +}; +namespace detail { +struct DotDimensionNumbersAttrStorage; +} // namespace detail +class DotDimensionNumbersAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static DotDimensionNumbersAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef lhsBatchingDimensions, ::llvm::ArrayRef rhsBatchingDimensions, ::llvm::ArrayRef lhsContractingDimensions, ::llvm::ArrayRef rhsContractingDimensions); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"dot"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getLhsBatchingDimensions() const; + ::llvm::ArrayRef getRhsBatchingDimensions() const; + ::llvm::ArrayRef getLhsContractingDimensions() const; + ::llvm::ArrayRef getRhsContractingDimensions() const; +}; +namespace detail { +struct FftTypeAttrStorage; +} // namespace detail +class FftTypeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static FftTypeAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::FftType value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"fft_type"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::FftType getValue() const; +}; +namespace detail { +struct FusionKindAttrStorage; +} // namespace detail +class FusionKindAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static FusionKindAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::FusionKind value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"fusion_kind"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::FusionKind getValue() const; +}; +namespace detail { +struct GatherDimensionNumbersAttrStorage; +} // namespace detail +class GatherDimensionNumbersAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static GatherDimensionNumbersAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef offsetDims, ::llvm::ArrayRef collapsedSliceDims, ::llvm::ArrayRef startIndexMap, int64_t indexVectorDim); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"gather"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getOffsetDims() const; + ::llvm::ArrayRef getCollapsedSliceDims() const; + ::llvm::ArrayRef getStartIndexMap() const; + int64_t getIndexVectorDim() const; +}; +namespace detail { +struct OutputOperandAliasAttrStorage; +} // namespace detail +class OutputOperandAliasAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static OutputOperandAliasAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef outputTupleIndices, int64_t operandIndex, ::llvm::ArrayRef operandTupleIndices); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"output_operand_alias"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getOutputTupleIndices() const; + int64_t getOperandIndex() const; + ::llvm::ArrayRef getOperandTupleIndices() const; +}; +namespace detail { +struct PrecisionAttrStorage; +} // namespace detail +class PrecisionAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static PrecisionAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::Precision value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"precision"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::Precision getValue() const; +}; +namespace detail { +struct RngAlgorithmAttrStorage; +} // namespace detail +class RngAlgorithmAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static RngAlgorithmAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::RngAlgorithm value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"rng_algorithm"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::RngAlgorithm getValue() const; +}; +namespace detail { +struct RngDistributionAttrStorage; +} // namespace detail +class RngDistributionAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static RngDistributionAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::RngDistribution value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"rng_distribution"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::RngDistribution getValue() const; +}; +namespace detail { +struct ScatterDimensionNumbersAttrStorage; +} // namespace detail +class ScatterDimensionNumbersAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ScatterDimensionNumbersAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef updateWindowDims, ::llvm::ArrayRef insertedWindowDims, ::llvm::ArrayRef scatterDimsToOperandDims, int64_t indexVectorDim); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"scatter"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getUpdateWindowDims() const; + ::llvm::ArrayRef getInsertedWindowDims() const; + ::llvm::ArrayRef getScatterDimsToOperandDims() const; + int64_t getIndexVectorDim() const; +}; +namespace detail { +struct TransposeAttrStorage; +} // namespace detail +class TransposeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static TransposeAttr get(::mlir::MLIRContext *context, ::mlir::mhlo::Transpose value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"transpose"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::mhlo::Transpose getValue() const; +}; +namespace detail { +struct TypeExtensionsAttrStorage; +} // namespace detail +class TypeExtensionsAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static TypeExtensionsAttr get(::mlir::MLIRContext *context, ::llvm::ArrayRef bounds); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"type_extensions"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getBounds() const; + ::mlir::LogicalResult verifyEncoding(ArrayRef shape, Type elementType, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) const; +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ArgResultAliasAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ChannelHandleAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ComparisonDirectionAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ComparisonTypeAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ConvDimensionNumbersAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CrossProgramPrefetchAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CustomCallScheduleAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DequantizeModeAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DomainKindAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DotDimensionNumbersAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::FftTypeAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::FusionKindAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::GatherDimensionNumbersAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::OutputOperandAliasAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::PrecisionAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RngAlgorithmAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RngDistributionAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ScatterDimensionNumbersAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TransposeAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TypeExtensionsAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_common/mhlo/IR/hlo_ops_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_common/mhlo/IR/hlo_ops_common.h new file mode 100644 index 0000000000000000000000000000000000000000..db6898ae9850f54c03bc16f9d39dc57afc7168f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_common/mhlo/IR/hlo_ops_common.h @@ -0,0 +1,58 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_MHLO_IR_HLO_OPS_COMMON_H +#define MLIR_HLO_MHLO_IR_HLO_OPS_COMMON_H + +// This file defines functionality shared between chlo/mhlo/lhlo dialects. + +#include +#include + +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/IR/OpImplementation.h" +#include "mlir/IR/Operation.h" + +namespace mlir { +namespace hlo { + +// Verifies the source target pairs attached to collective permute. +LogicalResult verifyCollectivePermuteSourceTargetPairs( + Operation* op, DenseIntElementsAttr attr); + +LogicalResult verifyReduceScatter(Operation* op, TypeRange operandTypes, + TypeRange resultTypes, + uint64_t scatterDimension); + +// Custom formatting for convolution window attributes. +void printWindowAttributes(OpAsmPrinter& p, Operation* op, + std::optional windowStrides, + std::optional padding, + std::optional lhsDilation, + std::optional rhsDilation, + std::optional windowReversal); + +ParseResult parseWindowAttributes(OpAsmParser& parser, + DenseIntElementsAttr& windowStrides, + DenseIntElementsAttr& padding, + DenseIntElementsAttr& lhsDilation, + DenseIntElementsAttr& rhsDilation, + DenseElementsAttr& windowReversal); + +} // namespace hlo +} // namespace mlir + +#endif // MLIR_HLO_MHLO_IR_HLO_OPS_COMMON_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_enums_inc_gen/mhlo/IR/hlo_ops_enums.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_enums_inc_gen/mhlo/IR/hlo_ops_enums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..38b5eb38d069ad1be361a7cc58d86328798e4266 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_enums_inc_gen/mhlo/IR/hlo_ops_enums.h.inc @@ -0,0 +1,1008 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: hlo_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace mhlo { +// Which comparison operation to perform. +enum class ComparisonDirection : uint32_t { + EQ = 0, + NE = 1, + GE = 2, + GT = 3, + LE = 4, + LT = 5, +}; + +::std::optional symbolizeComparisonDirection(uint32_t); +::llvm::StringRef stringifyComparisonDirection(ComparisonDirection); +::std::optional symbolizeComparisonDirection(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForComparisonDirection() { + return 5; +} + + +inline ::llvm::StringRef stringifyEnum(ComparisonDirection enumValue) { + return stringifyComparisonDirection(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeComparisonDirection(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::ComparisonDirection, ::mlir::mhlo::ComparisonDirection> { + template + static FailureOr<::mlir::mhlo::ComparisonDirection> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Which comparison operation to perform."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::ComparisonDirection> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::ComparisonDirection>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Which comparison operation to perform. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::ComparisonDirection value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::ComparisonDirection> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::ComparisonDirection getEmptyKey() { + return static_cast<::mlir::mhlo::ComparisonDirection>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::ComparisonDirection getTombstoneKey() { + return static_cast<::mlir::mhlo::ComparisonDirection>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::ComparisonDirection &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::ComparisonDirection &lhs, const ::mlir::mhlo::ComparisonDirection &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Which comparison type to use. +enum class ComparisonType : uint32_t { + NOTYPE = 0, + FLOAT = 1, + TOTALORDER = 2, + SIGNED = 3, + UNSIGNED = 4, +}; + +::std::optional symbolizeComparisonType(uint32_t); +::llvm::StringRef stringifyComparisonType(ComparisonType); +::std::optional symbolizeComparisonType(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForComparisonType() { + return 4; +} + + +inline ::llvm::StringRef stringifyEnum(ComparisonType enumValue) { + return stringifyComparisonType(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeComparisonType(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::ComparisonType, ::mlir::mhlo::ComparisonType> { + template + static FailureOr<::mlir::mhlo::ComparisonType> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Which comparison type to use."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::ComparisonType> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::ComparisonType>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Which comparison type to use. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::ComparisonType value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::ComparisonType> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::ComparisonType getEmptyKey() { + return static_cast<::mlir::mhlo::ComparisonType>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::ComparisonType getTombstoneKey() { + return static_cast<::mlir::mhlo::ComparisonType>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::ComparisonType &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::ComparisonType &lhs, const ::mlir::mhlo::ComparisonType &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Custom call API version +enum class CustomCallApiVersion : uint32_t { + API_VERSION_UNSPECIFIED = 0, + API_VERSION_ORIGINAL = 1, + API_VERSION_STATUS_RETURNING = 2, + API_VERSION_STATUS_RETURNING_UNIFIED = 3, + API_VERSION_TYPED_FFI = 4, +}; + +::std::optional symbolizeCustomCallApiVersion(uint32_t); +::llvm::StringRef stringifyCustomCallApiVersion(CustomCallApiVersion); +::std::optional symbolizeCustomCallApiVersion(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForCustomCallApiVersion() { + return 4; +} + + +inline ::llvm::StringRef stringifyEnum(CustomCallApiVersion enumValue) { + return stringifyCustomCallApiVersion(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeCustomCallApiVersion(str); +} + +class CustomCallApiVersionAttr : public ::mlir::IntegerAttr { +public: + using ValueType = CustomCallApiVersion; + using ::mlir::IntegerAttr::IntegerAttr; + static bool classof(::mlir::Attribute attr); + static CustomCallApiVersionAttr get(::mlir::MLIRContext *context, CustomCallApiVersion val); + CustomCallApiVersion getValue() const; +}; +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::CustomCallApiVersion, ::mlir::mhlo::CustomCallApiVersion> { + template + static FailureOr<::mlir::mhlo::CustomCallApiVersion> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Custom call API version"); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::CustomCallApiVersion> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::CustomCallApiVersion>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Custom call API version specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::CustomCallApiVersion value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::CustomCallApiVersion> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::CustomCallApiVersion getEmptyKey() { + return static_cast<::mlir::mhlo::CustomCallApiVersion>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::CustomCallApiVersion getTombstoneKey() { + return static_cast<::mlir::mhlo::CustomCallApiVersion>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::CustomCallApiVersion &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::CustomCallApiVersion &lhs, const ::mlir::mhlo::CustomCallApiVersion &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Specifies the desired schedule for the custom-call. +enum class CustomCallSchedule : uint32_t { + NONE = 0, + LATEST = 1, + EARLIEST = 2, +}; + +::std::optional symbolizeCustomCallSchedule(uint32_t); +::llvm::StringRef stringifyCustomCallSchedule(CustomCallSchedule); +::std::optional symbolizeCustomCallSchedule(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForCustomCallSchedule() { + return 2; +} + + +inline ::llvm::StringRef stringifyEnum(CustomCallSchedule enumValue) { + return stringifyCustomCallSchedule(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeCustomCallSchedule(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::CustomCallSchedule, ::mlir::mhlo::CustomCallSchedule> { + template + static FailureOr<::mlir::mhlo::CustomCallSchedule> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Specifies the desired schedule for the custom-call."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::CustomCallSchedule> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::CustomCallSchedule>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Specifies the desired schedule for the custom-call. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::CustomCallSchedule value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::CustomCallSchedule> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::CustomCallSchedule getEmptyKey() { + return static_cast<::mlir::mhlo::CustomCallSchedule>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::CustomCallSchedule getTombstoneKey() { + return static_cast<::mlir::mhlo::CustomCallSchedule>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::CustomCallSchedule &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::CustomCallSchedule &lhs, const ::mlir::mhlo::CustomCallSchedule &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Dequantization mode. Only MIN_COMBINED is supported. +enum class DequantizeMode : uint32_t { + MIN_COMBINED = 0, +}; + +::std::optional symbolizeDequantizeMode(uint32_t); +::llvm::StringRef stringifyDequantizeMode(DequantizeMode); +::std::optional symbolizeDequantizeMode(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForDequantizeMode() { + return 0; +} + + +inline ::llvm::StringRef stringifyEnum(DequantizeMode enumValue) { + return stringifyDequantizeMode(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeDequantizeMode(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::DequantizeMode, ::mlir::mhlo::DequantizeMode> { + template + static FailureOr<::mlir::mhlo::DequantizeMode> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Dequantization mode. Only MIN_COMBINED is supported."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::DequantizeMode> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::DequantizeMode>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Dequantization mode. Only MIN_COMBINED is supported. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::DequantizeMode value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::DequantizeMode> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::DequantizeMode getEmptyKey() { + return static_cast<::mlir::mhlo::DequantizeMode>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::DequantizeMode getTombstoneKey() { + return static_cast<::mlir::mhlo::DequantizeMode>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::DequantizeMode &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::DequantizeMode &lhs, const ::mlir::mhlo::DequantizeMode &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Kind of domain metatdata attached to an HLO domain. +enum class DomainKind : uint32_t { + sharding = 0, +}; + +::std::optional symbolizeDomainKind(uint32_t); +::llvm::StringRef stringifyDomainKind(DomainKind); +::std::optional symbolizeDomainKind(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForDomainKind() { + return 0; +} + + +inline ::llvm::StringRef stringifyEnum(DomainKind enumValue) { + return stringifyDomainKind(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeDomainKind(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::DomainKind, ::mlir::mhlo::DomainKind> { + template + static FailureOr<::mlir::mhlo::DomainKind> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Kind of domain metatdata attached to an HLO domain."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::DomainKind> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::DomainKind>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Kind of domain metatdata attached to an HLO domain. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::DomainKind value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::DomainKind> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::DomainKind getEmptyKey() { + return static_cast<::mlir::mhlo::DomainKind>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::DomainKind getTombstoneKey() { + return static_cast<::mlir::mhlo::DomainKind>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::DomainKind &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::DomainKind &lhs, const ::mlir::mhlo::DomainKind &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// XLA fast fourier transform type. +enum class FftType : uint32_t { + FFT = 0, + IFFT = 1, + RFFT = 2, + IRFFT = 3, +}; + +::std::optional symbolizeFftType(uint32_t); +::llvm::StringRef stringifyFftType(FftType); +::std::optional symbolizeFftType(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForFftType() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(FftType enumValue) { + return stringifyFftType(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeFftType(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::FftType, ::mlir::mhlo::FftType> { + template + static FailureOr<::mlir::mhlo::FftType> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for XLA fast fourier transform type."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::FftType> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::FftType>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid XLA fast fourier transform type. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::FftType value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::FftType> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::FftType getEmptyKey() { + return static_cast<::mlir::mhlo::FftType>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::FftType getTombstoneKey() { + return static_cast<::mlir::mhlo::FftType>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::FftType &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::FftType &lhs, const ::mlir::mhlo::FftType &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// fusion kind +enum class FusionKind : uint32_t { + kLoop = 0, + kInput = 1, + kOutput = 2, + kCustom = 3, +}; + +::std::optional symbolizeFusionKind(uint32_t); +::llvm::StringRef stringifyFusionKind(FusionKind); +::std::optional symbolizeFusionKind(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForFusionKind() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(FusionKind enumValue) { + return stringifyFusionKind(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeFusionKind(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::FusionKind, ::mlir::mhlo::FusionKind> { + template + static FailureOr<::mlir::mhlo::FusionKind> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for fusion kind"); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::FusionKind> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::FusionKind>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid fusion kind specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::FusionKind value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::FusionKind> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::FusionKind getEmptyKey() { + return static_cast<::mlir::mhlo::FusionKind>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::FusionKind getTombstoneKey() { + return static_cast<::mlir::mhlo::FusionKind>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::FusionKind &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::FusionKind &lhs, const ::mlir::mhlo::FusionKind &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// XLA precision for an operand. Has backend specific meaning. +enum class Precision : uint32_t { + DEFAULT = 0, + HIGH = 1, + HIGHEST = 2, + PACKED_NIBBLE = 3, +}; + +::std::optional symbolizePrecision(uint32_t); +::llvm::StringRef stringifyPrecision(Precision); +::std::optional symbolizePrecision(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForPrecision() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(Precision enumValue) { + return stringifyPrecision(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizePrecision(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::Precision, ::mlir::mhlo::Precision> { + template + static FailureOr<::mlir::mhlo::Precision> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for XLA precision for an operand. Has backend specific meaning."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::Precision> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::Precision>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid XLA precision for an operand. Has backend specific meaning. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::Precision value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::Precision> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::Precision getEmptyKey() { + return static_cast<::mlir::mhlo::Precision>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::Precision getTombstoneKey() { + return static_cast<::mlir::mhlo::Precision>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::Precision &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::Precision &lhs, const ::mlir::mhlo::Precision &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// XLA PRNG algorithm to be used. +enum class RngAlgorithm : uint32_t { + DEFAULT = 0, + THREE_FRY = 1, + PHILOX = 2, +}; + +::std::optional symbolizeRngAlgorithm(uint32_t); +::llvm::StringRef stringifyRngAlgorithm(RngAlgorithm); +::std::optional symbolizeRngAlgorithm(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForRngAlgorithm() { + return 2; +} + + +inline ::llvm::StringRef stringifyEnum(RngAlgorithm enumValue) { + return stringifyRngAlgorithm(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeRngAlgorithm(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::RngAlgorithm, ::mlir::mhlo::RngAlgorithm> { + template + static FailureOr<::mlir::mhlo::RngAlgorithm> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for XLA PRNG algorithm to be used."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::RngAlgorithm> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::RngAlgorithm>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid XLA PRNG algorithm to be used. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::RngAlgorithm value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::RngAlgorithm> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::RngAlgorithm getEmptyKey() { + return static_cast<::mlir::mhlo::RngAlgorithm>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::RngAlgorithm getTombstoneKey() { + return static_cast<::mlir::mhlo::RngAlgorithm>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::RngAlgorithm &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::RngAlgorithm &lhs, const ::mlir::mhlo::RngAlgorithm &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// XLA PRNG distribution to be used. +enum class RngDistribution : uint32_t { + UNIFORM = 1, + NORMAL = 2, +}; + +::std::optional symbolizeRngDistribution(uint32_t); +::llvm::StringRef stringifyRngDistribution(RngDistribution); +::std::optional symbolizeRngDistribution(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForRngDistribution() { + return 2; +} + + +inline ::llvm::StringRef stringifyEnum(RngDistribution enumValue) { + return stringifyRngDistribution(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeRngDistribution(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::RngDistribution, ::mlir::mhlo::RngDistribution> { + template + static FailureOr<::mlir::mhlo::RngDistribution> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for XLA PRNG distribution to be used."); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::RngDistribution> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::RngDistribution>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid XLA PRNG distribution to be used. specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::RngDistribution value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::RngDistribution> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::RngDistribution getEmptyKey() { + return static_cast<::mlir::mhlo::RngDistribution>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::RngDistribution getTombstoneKey() { + return static_cast<::mlir::mhlo::RngDistribution>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::RngDistribution &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::RngDistribution &lhs, const ::mlir::mhlo::RngDistribution &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace mhlo { +// Transpose options +enum class Transpose : uint32_t { + TRANSPOSE_INVALID = 0, + NO_TRANSPOSE = 1, + TRANSPOSE = 2, + ADJOINT = 3, +}; + +::std::optional symbolizeTranspose(uint32_t); +::llvm::StringRef stringifyTranspose(Transpose); +::std::optional symbolizeTranspose(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForTranspose() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(Transpose enumValue) { + return stringifyTranspose(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeTranspose(str); +} +} // namespace mhlo +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::mhlo::Transpose, ::mlir::mhlo::Transpose> { + template + static FailureOr<::mlir::mhlo::Transpose> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Transpose options"); + + // Symbolize the keyword. + if (::std::optional<::mlir::mhlo::Transpose> attr = ::mlir::mhlo::symbolizeEnum<::mlir::mhlo::Transpose>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Transpose options specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::mhlo::Transpose value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::mhlo::Transpose> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::mhlo::Transpose getEmptyKey() { + return static_cast<::mlir::mhlo::Transpose>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::mhlo::Transpose getTombstoneKey() { + return static_cast<::mlir::mhlo::Transpose>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::mhlo::Transpose &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::mhlo::Transpose &lhs, const ::mlir::mhlo::Transpose &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_inc_gen/mhlo/IR/hlo_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_inc_gen/mhlo/IR/hlo_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..8ac9e1da525402b2bd2d08a43fba8873349425f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_inc_gen/mhlo/IR/hlo_ops.h.inc @@ -0,0 +1,17622 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: hlo_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace mhlo { +class AbsOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AddDependencyOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AddOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AfterAllOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AllGatherOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AllReduceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AllToAllOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AndOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AsyncDoneOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AsyncStartOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class AsyncUpdateOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class Atan2Op; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BatchNormGradOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BatchNormInferenceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BatchNormTrainingOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BitcastConvertOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BitcastOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BroadcastInDimOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class BroadcastOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CaseOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CbrtOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CeilOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CholeskyOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ClampOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ClzOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CollectivePermuteOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CompareOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ComplexOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ComputeReshapeShapeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ConcatenateOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ConstantOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ConvertOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ConvolutionOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CopyOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CosineOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CreateTokenOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CrossReplicaSumOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CstrReshapableOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class CustomCallOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DivOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DomainOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DotGeneralOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DotOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicBroadcastInDimOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicConvOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicGatherOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicIotaOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicPadOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicReshapeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicSliceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class DynamicUpdateSliceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class EinsumOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ExpOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class Expm1Op; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class FftOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class FloorOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class FusionOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class GatherOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class GetDimensionSizeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class GetTupleElementOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class IfOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ImagOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class InfeedOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class IotaOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class IsFiniteOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class Log1pOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class LogOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class LogisticOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class MapOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class MaxOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class MinOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class MulOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class NegOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class NotOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class OptimizationBarrierOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class OrOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class OutfeedOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class PadOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class PartitionIdOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class PopulationCountOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class PowOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RealDynamicSliceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RealOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RecvOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReduceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReducePrecisionOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReduceScatterOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReduceWindowOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RemOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReplicaIdOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReshapeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReturnOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ReverseOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RngBitGeneratorOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RngOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RoundNearestEvenOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RoundOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class RsqrtOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ScatterOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SelectAndScatterOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SelectOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SendOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SetDimensionSizeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ShiftLeftOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ShiftRightArithmeticOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class ShiftRightLogicalOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SignOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SineOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SliceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SortOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SqrtOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class StochasticConvertOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class SubtractOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TanOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TanhOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TopKOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TorchIndexSelectOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TraceOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TransposeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TriangularSolveOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class TupleOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class UnaryEinsumOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class UniformDequantizeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class UniformQuantizeOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class WhileOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class XlaRngGetAndUpdateStateOp; +} // namespace mhlo +} // namespace mlir +namespace mlir { +namespace mhlo { +class XorOp; +} // namespace mhlo +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AbsOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AbsOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AbsOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AbsOpGenericAdaptorBase(AbsOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AbsOpGenericAdaptor : public detail::AbsOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AbsOpGenericAdaptorBase; +public: + AbsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AbsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AbsOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AbsOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AbsOpAdaptor : public AbsOpGenericAdaptor<::mlir::ValueRange> { +public: + using AbsOpGenericAdaptor::AbsOpGenericAdaptor; + AbsOpAdaptor(AbsOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AbsOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = AbsOpAdaptor; + template + using GenericAdaptor = AbsOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.abs"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AbsOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AddDependencyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AddDependencyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AddDependencyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AddDependencyOpGenericAdaptorBase(AddDependencyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AddDependencyOpGenericAdaptor : public detail::AddDependencyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AddDependencyOpGenericAdaptorBase; +public: + AddDependencyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AddDependencyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AddDependencyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AddDependencyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getToken() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AddDependencyOpAdaptor : public AddDependencyOpGenericAdaptor<::mlir::ValueRange> { +public: + using AddDependencyOpGenericAdaptor::AddDependencyOpGenericAdaptor; + AddDependencyOpAdaptor(AddDependencyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AddDependencyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AddDependencyOpAdaptor; + template + using GenericAdaptor = AddDependencyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.add_dependency"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getOperand(); + ::mlir::Value getToken(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getOutput(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::Value operand, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AddDependencyOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AddOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AddOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AddOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AddOpGenericAdaptorBase(AddOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AddOpGenericAdaptor : public detail::AddOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AddOpGenericAdaptorBase; +public: + AddOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AddOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AddOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AddOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AddOpAdaptor : public AddOpGenericAdaptor<::mlir::ValueRange> { +public: + using AddOpGenericAdaptor::AddOpGenericAdaptor; + AddOpAdaptor(AddOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AddOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = AddOpAdaptor; + template + using GenericAdaptor = AddOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.add"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AddOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AfterAllOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AfterAllOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AfterAllOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AfterAllOpGenericAdaptorBase(AfterAllOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AfterAllOpGenericAdaptor : public detail::AfterAllOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AfterAllOpGenericAdaptorBase; +public: + AfterAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AfterAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AfterAllOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AfterAllOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AfterAllOpAdaptor : public AfterAllOpGenericAdaptor<::mlir::ValueRange> { +public: + using AfterAllOpGenericAdaptor::AfterAllOpGenericAdaptor; + AfterAllOpAdaptor(AfterAllOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AfterAllOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AfterAllOpAdaptor; + template + using GenericAdaptor = AfterAllOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.after_all"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::ValueRange inputs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AfterAllOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AllGatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllGatherOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllGatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllGatherOpGenericAdaptorBase(AllGatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getAllGatherDimAttr(); + uint64_t getAllGatherDim(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); +}; +} // namespace detail +template +class AllGatherOpGenericAdaptor : public detail::AllGatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllGatherOpGenericAdaptorBase; +public: + AllGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllGatherOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllGatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllGatherOpAdaptor : public AllGatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllGatherOpGenericAdaptor::AllGatherOpGenericAdaptor; + AllGatherOpAdaptor(AllGatherOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllGatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::SameOperandsAndResultElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllGatherOpAdaptor; + template + using GenericAdaptor = AllGatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("all_gather_dim"), ::llvm::StringRef("channel_handle"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAllGatherDimAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAllGatherDimAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.all_gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getAllGatherDimAttr(); + uint64_t getAllGatherDim(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + void setAllGatherDimAttr(::mlir::IntegerAttr attr); + void setAllGatherDim(uint64_t attrValue); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::UnitAttr attr); + void setUseGlobalDeviceIds(bool attrValue); + ::mlir::Attribute removeChannelHandleAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result_type, ::mlir::Value operand, ::mlir::IntegerAttr all_gather_dim, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::IntegerAttr all_gather_dim, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr all_gather_dim, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, uint64_t all_gather_dim, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint64_t all_gather_dim, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 4 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AllGatherOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AllReduceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceOpGenericAdaptorBase(AllReduceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class AllReduceOpGenericAdaptor : public detail::AllReduceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceOpGenericAdaptorBase; +public: + AllReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return getODSOperands(0); + } + +private: + RangeT odsOperands; +}; +class AllReduceOpAdaptor : public AllReduceOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceOpGenericAdaptor::AllReduceOpGenericAdaptor; + AllReduceOpAdaptor(AllReduceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceOpAdaptor; + template + using GenericAdaptor = AllReduceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.all_reduce"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperands(); + ::mlir::MutableOperandRange getOperandsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::UnitAttr attr); + void setUseGlobalDeviceIds(bool attrValue); + ::mlir::Attribute removeChannelHandleAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result_type, ::mlir::Value operand, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::mhlo::ChannelHandleAttr channel_handle, bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::mhlo::ChannelHandleAttr channel_handle, bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operands, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operands, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AllReduceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AllToAllOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllOpGenericAdaptorBase(AllToAllOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + ::mlir::IntegerAttr getConcatDimensionAttr(); + ::std::optional getConcatDimension(); + ::mlir::IntegerAttr getSplitCountAttr(); + ::std::optional getSplitCount(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); +}; +} // namespace detail +template +class AllToAllOpGenericAdaptor : public detail::AllToAllOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllOpGenericAdaptorBase; +public: + AllToAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllOpAdaptor : public AllToAllOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllOpGenericAdaptor::AllToAllOpGenericAdaptor; + AllToAllOpAdaptor(AllToAllOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllOpAdaptor; + template + using GenericAdaptor = AllToAllOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("concat_dimension"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("split_count"), ::llvm::StringRef("split_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConcatDimensionAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConcatDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getSplitCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getSplitCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getSplitDimensionAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getSplitDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.all_to_all"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::MutableOperandRange getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + ::mlir::IntegerAttr getConcatDimensionAttr(); + ::std::optional getConcatDimension(); + ::mlir::IntegerAttr getSplitCountAttr(); + ::std::optional getSplitCount(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + void setSplitDimensionAttr(::mlir::IntegerAttr attr); + void setSplitDimension(::std::optional attrValue); + void setConcatDimensionAttr(::mlir::IntegerAttr attr); + void setConcatDimension(::std::optional attrValue); + void setSplitCountAttr(::mlir::IntegerAttr attr); + void setSplitCount(::std::optional attrValue); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + ::mlir::Attribute removeSplitDimensionAttr(); + ::mlir::Attribute removeConcatDimensionAttr(); + ::mlir::Attribute removeSplitCountAttr(); + ::mlir::Attribute removeChannelHandleAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result_type, ::mlir::Value operand, ::mlir::IntegerAttr split_dimension, ::mlir::IntegerAttr concat_dimension, ::mlir::IntegerAttr split_count, ::mlir::DenseIntElementsAttr replica_groups); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange result_type, ::mlir::ValueRange operand, ::mlir::IntegerAttr split_dimension, ::mlir::IntegerAttr concat_dimension, ::mlir::IntegerAttr split_count, ::mlir::DenseIntElementsAttr replica_groups); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange operand, /*optional*/::mlir::IntegerAttr split_dimension, /*optional*/::mlir::IntegerAttr concat_dimension, /*optional*/::mlir::IntegerAttr split_count, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operand, /*optional*/::mlir::IntegerAttr split_dimension, /*optional*/::mlir::IntegerAttr concat_dimension, /*optional*/::mlir::IntegerAttr split_count, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 5 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AllToAllOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AndOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AndOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AndOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AndOpGenericAdaptorBase(AndOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AndOpGenericAdaptor : public detail::AndOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AndOpGenericAdaptorBase; +public: + AndOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AndOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AndOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AndOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AndOpAdaptor : public AndOpGenericAdaptor<::mlir::ValueRange> { +public: + using AndOpGenericAdaptor::AndOpGenericAdaptor; + AndOpAdaptor(AndOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AndOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = AndOpAdaptor; + template + using GenericAdaptor = AndOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.and"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AndOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AsyncDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AsyncDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AsyncDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AsyncDoneOpGenericAdaptorBase(AsyncDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); +}; +} // namespace detail +template +class AsyncDoneOpGenericAdaptor : public detail::AsyncDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AsyncDoneOpGenericAdaptorBase; +public: + AsyncDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AsyncDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AsyncDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AsyncDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBundle() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AsyncDoneOpAdaptor : public AsyncDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AsyncDoneOpGenericAdaptor::AsyncDoneOpGenericAdaptor; + AsyncDoneOpAdaptor(AsyncDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AsyncDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AsyncDoneOpAdaptor; + template + using GenericAdaptor = AsyncDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("called_computation"), ::llvm::StringRef("execution_thread"), ::llvm::StringRef("group_id")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCalledComputationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCalledComputationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getExecutionThreadAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getExecutionThreadAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getGroupIdAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getGroupIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.async_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getBundle(); + ::mlir::OpOperand &getBundleMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); + void setCalledComputationAttr(::mlir::FlatSymbolRefAttr attr); + void setCalledComputation(::llvm::StringRef attrValue); + void setExecutionThreadAttr(::mlir::StringAttr attr); + void setExecutionThread(::llvm::StringRef attrValue); + void setGroupIdAttr(::mlir::IntegerAttr attr); + void setGroupId(::std::optional attrValue); + ::mlir::Attribute removeGroupIdAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value bundle, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bundle, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value bundle, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bundle, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AsyncDoneOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AsyncStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AsyncStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AsyncStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AsyncStartOpGenericAdaptorBase(AsyncStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); +}; +} // namespace detail +template +class AsyncStartOpGenericAdaptor : public detail::AsyncStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AsyncStartOpGenericAdaptorBase; +public: + AsyncStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AsyncStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AsyncStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AsyncStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AsyncStartOpAdaptor : public AsyncStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AsyncStartOpGenericAdaptor::AsyncStartOpGenericAdaptor; + AsyncStartOpAdaptor(AsyncStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AsyncStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants> { +public: + using Op::Op; + using Op::print; + using Adaptor = AsyncStartOpAdaptor; + template + using GenericAdaptor = AsyncStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("called_computation"), ::llvm::StringRef("execution_thread"), ::llvm::StringRef("group_id")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCalledComputationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCalledComputationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getExecutionThreadAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getExecutionThreadAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getGroupIdAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getGroupIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.async_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); + void setCalledComputationAttr(::mlir::FlatSymbolRefAttr attr); + void setCalledComputation(::llvm::StringRef attrValue); + void setExecutionThreadAttr(::mlir::StringAttr attr); + void setExecutionThread(::llvm::StringRef attrValue); + void setGroupIdAttr(::mlir::IntegerAttr attr); + void setGroupId(::std::optional attrValue); + ::mlir::Attribute removeGroupIdAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AsyncStartOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::AsyncUpdateOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AsyncUpdateOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AsyncUpdateOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AsyncUpdateOpGenericAdaptorBase(AsyncUpdateOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); +}; +} // namespace detail +template +class AsyncUpdateOpGenericAdaptor : public detail::AsyncUpdateOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AsyncUpdateOpGenericAdaptorBase; +public: + AsyncUpdateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AsyncUpdateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AsyncUpdateOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AsyncUpdateOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBundle() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AsyncUpdateOpAdaptor : public AsyncUpdateOpGenericAdaptor<::mlir::ValueRange> { +public: + using AsyncUpdateOpGenericAdaptor::AsyncUpdateOpGenericAdaptor; + AsyncUpdateOpAdaptor(AsyncUpdateOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AsyncUpdateOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AsyncUpdateOpAdaptor; + template + using GenericAdaptor = AsyncUpdateOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("called_computation"), ::llvm::StringRef("execution_thread"), ::llvm::StringRef("group_id")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCalledComputationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCalledComputationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getExecutionThreadAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getExecutionThreadAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getGroupIdAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getGroupIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.async_update"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getBundle(); + ::mlir::OpOperand &getBundleMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FlatSymbolRefAttr getCalledComputationAttr(); + ::llvm::StringRef getCalledComputation(); + ::mlir::StringAttr getExecutionThreadAttr(); + ::llvm::StringRef getExecutionThread(); + ::mlir::IntegerAttr getGroupIdAttr(); + ::std::optional getGroupId(); + void setCalledComputationAttr(::mlir::FlatSymbolRefAttr attr); + void setCalledComputation(::llvm::StringRef attrValue); + void setExecutionThreadAttr(::mlir::StringAttr attr); + void setExecutionThread(::llvm::StringRef attrValue); + void setGroupIdAttr(::mlir::IntegerAttr attr); + void setGroupId(::std::optional attrValue); + ::mlir::Attribute removeGroupIdAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value bundle, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bundle, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bundle, ::mlir::FlatSymbolRefAttr called_computation, ::mlir::StringAttr execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value bundle, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bundle, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bundle, ::llvm::StringRef called_computation, ::llvm::StringRef execution_thread, /*optional*/::mlir::IntegerAttr group_id); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AsyncUpdateOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::Atan2Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Atan2OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Atan2OpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Atan2OpGenericAdaptorBase(Atan2Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class Atan2OpGenericAdaptor : public detail::Atan2OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Atan2OpGenericAdaptorBase; +public: + Atan2OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Atan2OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Atan2OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Atan2OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Atan2OpAdaptor : public Atan2OpGenericAdaptor<::mlir::ValueRange> { +public: + using Atan2OpGenericAdaptor::Atan2OpGenericAdaptor; + Atan2OpAdaptor(Atan2Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Atan2Op : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = Atan2OpAdaptor; + template + using GenericAdaptor = Atan2OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.atan2"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::Atan2Op) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BatchNormGradOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormGradOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormGradOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormGradOpGenericAdaptorBase(BatchNormGradOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormGradOpGenericAdaptor : public detail::BatchNormGradOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormGradOpGenericAdaptorBase; +public: + BatchNormGradOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormGradOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormGradOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormGradOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getMean() { + return (*getODSOperands(2).begin()); + } + + ValueT getVariance() { + return (*getODSOperands(3).begin()); + } + + ValueT getGradOutput() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormGradOpAdaptor : public BatchNormGradOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormGradOpGenericAdaptor::BatchNormGradOpGenericAdaptor; + BatchNormGradOpAdaptor(BatchNormGradOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormGradOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<5>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormGradOpAdaptor; + template + using GenericAdaptor = BatchNormGradOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.batch_norm_grad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getScale(); + ::mlir::TypedValue<::mlir::RankedTensorType> getMean(); + ::mlir::TypedValue<::mlir::RankedTensorType> getVariance(); + ::mlir::TypedValue<::mlir::RankedTensorType> getGradOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getMeanMutable(); + ::mlir::OpOperand &getVarianceMutable(); + ::mlir::OpOperand &getGradOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getGradOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getGradScale(); + ::mlir::TypedValue<::mlir::RankedTensorType> getGradOffset(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type grad_operand, ::mlir::Type grad_scale, ::mlir::Type grad_offset, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type grad_operand, ::mlir::Type grad_scale, ::mlir::Type grad_offset, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BatchNormGradOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BatchNormInferenceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormInferenceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormInferenceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormInferenceOpGenericAdaptorBase(BatchNormInferenceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormInferenceOpGenericAdaptor : public detail::BatchNormInferenceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormInferenceOpGenericAdaptorBase; +public: + BatchNormInferenceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormInferenceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormInferenceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormInferenceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getOffset() { + return (*getODSOperands(2).begin()); + } + + ValueT getMean() { + return (*getODSOperands(3).begin()); + } + + ValueT getVariance() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormInferenceOpAdaptor : public BatchNormInferenceOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormInferenceOpGenericAdaptor::BatchNormInferenceOpGenericAdaptor; + BatchNormInferenceOpAdaptor(BatchNormInferenceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormInferenceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<5>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormInferenceOpAdaptor; + template + using GenericAdaptor = BatchNormInferenceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.batch_norm_inference"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getScale(); + ::mlir::TypedValue<::mlir::RankedTensorType> getOffset(); + ::mlir::TypedValue<::mlir::RankedTensorType> getMean(); + ::mlir::TypedValue<::mlir::RankedTensorType> getVariance(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getOffsetMutable(); + ::mlir::OpOperand &getMeanMutable(); + ::mlir::OpOperand &getVarianceMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getResult(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BatchNormInferenceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BatchNormTrainingOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormTrainingOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormTrainingOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormTrainingOpGenericAdaptorBase(BatchNormTrainingOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormTrainingOpGenericAdaptor : public detail::BatchNormTrainingOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormTrainingOpGenericAdaptorBase; +public: + BatchNormTrainingOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormTrainingOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormTrainingOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormTrainingOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getOffset() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormTrainingOpAdaptor : public BatchNormTrainingOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormTrainingOpGenericAdaptor::BatchNormTrainingOpGenericAdaptor; + BatchNormTrainingOpAdaptor(BatchNormTrainingOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormTrainingOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormTrainingOpAdaptor; + template + using GenericAdaptor = BatchNormTrainingOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.batch_norm_training"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getScale(); + ::mlir::TypedValue<::mlir::RankedTensorType> getOffset(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getOffsetMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutput(); + ::mlir::TypedValue<::mlir::RankedTensorType> getBatchMean(); + ::mlir::TypedValue<::mlir::RankedTensorType> getBatchVar(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::Type batch_mean, ::mlir::Type batch_var, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::Type batch_mean, ::mlir::Type batch_var, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BatchNormTrainingOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BitcastConvertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BitcastConvertOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BitcastConvertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BitcastConvertOpGenericAdaptorBase(BitcastConvertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class BitcastConvertOpGenericAdaptor : public detail::BitcastConvertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BitcastConvertOpGenericAdaptorBase; +public: + BitcastConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BitcastConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BitcastConvertOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BitcastConvertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BitcastConvertOpAdaptor : public BitcastConvertOpGenericAdaptor<::mlir::ValueRange> { +public: + using BitcastConvertOpGenericAdaptor::BitcastConvertOpGenericAdaptor; + BitcastConvertOpAdaptor(BitcastConvertOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BitcastConvertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BitcastConvertOpAdaptor; + template + using GenericAdaptor = BitcastConvertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.bitcast_convert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BitcastConvertOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BitcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BitcastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BitcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BitcastOpGenericAdaptorBase(BitcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class BitcastOpGenericAdaptor : public detail::BitcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BitcastOpGenericAdaptorBase; +public: + BitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BitcastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BitcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BitcastOpAdaptor : public BitcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BitcastOpGenericAdaptor::BitcastOpGenericAdaptor; + BitcastOpAdaptor(BitcastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BitcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BitcastOpAdaptor; + template + using GenericAdaptor = BitcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.bitcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BitcastOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BroadcastInDimOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BroadcastInDimOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BroadcastInDimOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BroadcastInDimOpGenericAdaptorBase(BroadcastInDimOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); +}; +} // namespace detail +template +class BroadcastInDimOpGenericAdaptor : public detail::BroadcastInDimOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BroadcastInDimOpGenericAdaptorBase; +public: + BroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BroadcastInDimOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BroadcastInDimOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BroadcastInDimOpAdaptor : public BroadcastInDimOpGenericAdaptor<::mlir::ValueRange> { +public: + using BroadcastInDimOpGenericAdaptor::BroadcastInDimOpGenericAdaptor; + BroadcastInDimOpAdaptor(BroadcastInDimOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BroadcastInDimOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = BroadcastInDimOpAdaptor; + template + using GenericAdaptor = BroadcastInDimOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.broadcast_in_dim"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BroadcastInDimOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::BroadcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BroadcastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BroadcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BroadcastOpGenericAdaptorBase(BroadcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastSizesAttr(); + ::mlir::DenseIntElementsAttr getBroadcastSizes(); +}; +} // namespace detail +template +class BroadcastOpGenericAdaptor : public detail::BroadcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BroadcastOpGenericAdaptorBase; +public: + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BroadcastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BroadcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BroadcastOpAdaptor : public BroadcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BroadcastOpGenericAdaptor::BroadcastOpGenericAdaptor; + BroadcastOpAdaptor(BroadcastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BroadcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = BroadcastOpAdaptor; + template + using GenericAdaptor = BroadcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.broadcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastSizesAttr(); + ::mlir::DenseIntElementsAttr getBroadcastSizes(); + void setBroadcastSizesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr broadcast_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr broadcast_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr broadcast_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::BroadcastOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CaseOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CaseOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CaseOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CaseOpGenericAdaptorBase(CaseOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::RegionRange getBranches(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class CaseOpGenericAdaptor : public detail::CaseOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CaseOpGenericAdaptorBase; +public: + CaseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CaseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CaseOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CaseOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getIndex() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CaseOpAdaptor : public CaseOpGenericAdaptor<::mlir::ValueRange> { +public: + using CaseOpGenericAdaptor::CaseOpGenericAdaptor; + CaseOpAdaptor(CaseOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CaseOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CaseOpAdaptor; + template + using GenericAdaptor = CaseOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.case"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getIndex(); + ::mlir::OpOperand &getIndexMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::MutableArrayRef<::mlir::Region> getBranches(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value index, unsigned branchesCount); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value index, unsigned branchesCount); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes, unsigned numRegions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes, unsigned numRegions); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CaseOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CbrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CbrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CbrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CbrtOpGenericAdaptorBase(CbrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CbrtOpGenericAdaptor : public detail::CbrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CbrtOpGenericAdaptorBase; +public: + CbrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CbrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CbrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CbrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CbrtOpAdaptor : public CbrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using CbrtOpGenericAdaptor::CbrtOpGenericAdaptor; + CbrtOpAdaptor(CbrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CbrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = CbrtOpAdaptor; + template + using GenericAdaptor = CbrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.cbrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CbrtOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CeilOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CeilOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CeilOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CeilOpGenericAdaptorBase(CeilOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CeilOpGenericAdaptor : public detail::CeilOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CeilOpGenericAdaptorBase; +public: + CeilOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CeilOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CeilOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CeilOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CeilOpAdaptor : public CeilOpGenericAdaptor<::mlir::ValueRange> { +public: + using CeilOpGenericAdaptor::CeilOpGenericAdaptor; + CeilOpAdaptor(CeilOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CeilOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = CeilOpAdaptor; + template + using GenericAdaptor = CeilOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.ceil"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CeilOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CholeskyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CholeskyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CholeskyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CholeskyOpGenericAdaptorBase(CholeskyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); +}; +} // namespace detail +template +class CholeskyOpGenericAdaptor : public detail::CholeskyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CholeskyOpGenericAdaptorBase; +public: + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CholeskyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CholeskyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CholeskyOpAdaptor : public CholeskyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CholeskyOpGenericAdaptor::CholeskyOpGenericAdaptor; + CholeskyOpAdaptor(CholeskyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CholeskyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CholeskyOpAdaptor; + template + using GenericAdaptor = CholeskyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("lower")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLowerAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.cholesky"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getA(); + ::mlir::OpOperand &getAMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + void setLowerAttr(::mlir::BoolAttr attr); + void setLower(::std::optional attrValue); + ::mlir::Attribute removeLowerAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value a, /*optional*/::mlir::BoolAttr lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, /*optional*/::mlir::BoolAttr lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, /*optional*/::mlir::BoolAttr lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value a, /*optional*/bool lower = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, /*optional*/bool lower = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, /*optional*/bool lower = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CholeskyOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ClampOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ClampOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ClampOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ClampOpGenericAdaptorBase(ClampOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ClampOpGenericAdaptor : public detail::ClampOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ClampOpGenericAdaptorBase; +public: + ClampOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ClampOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ClampOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ClampOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMin() { + return (*getODSOperands(0).begin()); + } + + ValueT getOperand() { + return (*getODSOperands(1).begin()); + } + + ValueT getMax() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ClampOpAdaptor : public ClampOpGenericAdaptor<::mlir::ValueRange> { +public: + using ClampOpGenericAdaptor::ClampOpGenericAdaptor; + ClampOpAdaptor(ClampOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ClampOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::hlo::OpTrait::BroadcastingElementwise, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ClampOpAdaptor; + template + using GenericAdaptor = ClampOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.clamp"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getMin(); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getMax(); + ::mlir::OpOperand &getMinMutable(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getMaxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value min, ::mlir::Value operand, ::mlir::Value max); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value min, ::mlir::Value operand, ::mlir::Value max); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value min, ::mlir::Value operand, ::mlir::Value max); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ClampOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ClzOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ClzOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ClzOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ClzOpGenericAdaptorBase(ClzOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ClzOpGenericAdaptor : public detail::ClzOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ClzOpGenericAdaptorBase; +public: + ClzOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ClzOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ClzOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ClzOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ClzOpAdaptor : public ClzOpGenericAdaptor<::mlir::ValueRange> { +public: + using ClzOpGenericAdaptor::ClzOpGenericAdaptor; + ClzOpAdaptor(ClzOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ClzOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ClzOpAdaptor; + template + using GenericAdaptor = ClzOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.count_leading_zeros"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ClzOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CollectivePermuteOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteOpGenericAdaptorBase(CollectivePermuteOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); +}; +} // namespace detail +template +class CollectivePermuteOpGenericAdaptor : public detail::CollectivePermuteOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteOpGenericAdaptorBase; +public: + CollectivePermuteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteOpAdaptor : public CollectivePermuteOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteOpGenericAdaptor::CollectivePermuteOpGenericAdaptor; + CollectivePermuteOpAdaptor(CollectivePermuteOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteOpAdaptor; + template + using GenericAdaptor = CollectivePermuteOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("source_target_pairs")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getSourceTargetPairsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getSourceTargetPairsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.collective_permute"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + void setSourceTargetPairsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + ::mlir::Attribute removeChannelHandleAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result_type, ::mlir::Value operand, ::mlir::DenseIntElementsAttr source_target_pairs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CollectivePermuteOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CompareOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CompareOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CompareOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CompareOpGenericAdaptorBase(CompareOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ComparisonDirectionAttr getComparisonDirectionAttr(); + ::mlir::mhlo::ComparisonDirection getComparisonDirection(); + ::mlir::mhlo::ComparisonTypeAttr getCompareTypeAttr(); + ::std::optional<::mlir::mhlo::ComparisonType> getCompareType(); +}; +} // namespace detail +template +class CompareOpGenericAdaptor : public detail::CompareOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CompareOpGenericAdaptorBase; +public: + CompareOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CompareOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CompareOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CompareOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CompareOpAdaptor : public CompareOpGenericAdaptor<::mlir::ValueRange> { +public: + using CompareOpGenericAdaptor::CompareOpGenericAdaptor; + CompareOpAdaptor(CompareOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CompareOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CompareOpAdaptor; + template + using GenericAdaptor = CompareOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("compare_type"), ::llvm::StringRef("comparison_direction")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCompareTypeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCompareTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getComparisonDirectionAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getComparisonDirectionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.compare"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::ComparisonDirectionAttr getComparisonDirectionAttr(); + ::mlir::mhlo::ComparisonDirection getComparisonDirection(); + ::mlir::mhlo::ComparisonTypeAttr getCompareTypeAttr(); + ::std::optional<::mlir::mhlo::ComparisonType> getCompareType(); + void setComparisonDirectionAttr(::mlir::mhlo::ComparisonDirectionAttr attr); + void setComparisonDirection(::mlir::mhlo::ComparisonDirection attrValue); + void setCompareTypeAttr(::mlir::mhlo::ComparisonTypeAttr attr); + void setCompareType(::std::optional<::mlir::mhlo::ComparisonType> attrValue); + ::mlir::Attribute removeCompareTypeAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, ::mlir::mhlo::ComparisonDirection comparison_direction, ::mlir::mhlo::ComparisonType compare_type = ::mlir::mhlo::ComparisonType::NOTYPE); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirectionAttr comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirectionAttr comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirectionAttr comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirection comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirection comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::ComparisonDirection comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CompareOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ComplexOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ComplexOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ComplexOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ComplexOpGenericAdaptorBase(ComplexOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ComplexOpGenericAdaptor : public detail::ComplexOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ComplexOpGenericAdaptorBase; +public: + ComplexOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ComplexOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ComplexOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ComplexOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ComplexOpAdaptor : public ComplexOpGenericAdaptor<::mlir::ValueRange> { +public: + using ComplexOpGenericAdaptor::ComplexOpGenericAdaptor; + ComplexOpAdaptor(ComplexOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ComplexOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ComplexOpAdaptor; + template + using GenericAdaptor = ComplexOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.complex"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ComplexOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ComputeReshapeShapeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ComputeReshapeShapeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ComputeReshapeShapeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ComputeReshapeShapeOpGenericAdaptorBase(ComputeReshapeShapeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ComputeReshapeShapeOpGenericAdaptor : public detail::ComputeReshapeShapeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ComputeReshapeShapeOpGenericAdaptorBase; +public: + ComputeReshapeShapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ComputeReshapeShapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ComputeReshapeShapeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ComputeReshapeShapeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getNumElements() { + return (*getODSOperands(0).begin()); + } + + ValueT getDynamicShape() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ComputeReshapeShapeOpAdaptor : public ComputeReshapeShapeOpGenericAdaptor<::mlir::ValueRange> { +public: + using ComputeReshapeShapeOpGenericAdaptor::ComputeReshapeShapeOpGenericAdaptor; + ComputeReshapeShapeOpAdaptor(ComputeReshapeShapeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ComputeReshapeShapeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ComputeReshapeShapeOpAdaptor; + template + using GenericAdaptor = ComputeReshapeShapeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.compute_reshape_shape"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::IndexType> getNumElements(); + ::mlir::TypedValue<::mlir::RankedTensorType> getDynamicShape(); + ::mlir::OpOperand &getNumElementsMutable(); + ::mlir::OpOperand &getDynamicShapeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value num_elements, ::mlir::Value dynamic_shape); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value num_elements, ::mlir::Value dynamic_shape); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ComputeReshapeShapeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ConcatenateOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConcatenateOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConcatenateOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConcatenateOpGenericAdaptorBase(ConcatenateOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); +}; +} // namespace detail +template +class ConcatenateOpGenericAdaptor : public detail::ConcatenateOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConcatenateOpGenericAdaptorBase; +public: + ConcatenateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConcatenateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConcatenateOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConcatenateOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getVal() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConcatenateOpAdaptor : public ConcatenateOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConcatenateOpGenericAdaptor::ConcatenateOpGenericAdaptor; + ConcatenateOpAdaptor(ConcatenateOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConcatenateOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConcatenateOpAdaptor; + template + using GenericAdaptor = ConcatenateOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.concatenate"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getVal(); + ::mlir::MutableOperandRange getValMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange val, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange val, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange val, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange val, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange val, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange val, uint64_t dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ConcatenateOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ConstantOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConstantOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConstantOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConstantOpGenericAdaptorBase(ConstantOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::ElementsAttr getValueAttr(); + ::mlir::ElementsAttr getValue(); +}; +} // namespace detail +template +class ConstantOpGenericAdaptor : public detail::ConstantOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConstantOpGenericAdaptorBase; +public: + ConstantOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConstantOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConstantOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConstantOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConstantOpAdaptor : public ConstantOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConstantOpGenericAdaptor::ConstantOpGenericAdaptor; + ConstantOpAdaptor(ConstantOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConstantOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::ConstantLike, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConstantOpAdaptor; + template + using GenericAdaptor = ConstantOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("value")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getValueAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getValueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.constant"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutput(); + ::mlir::ElementsAttr getValueAttr(); + ::mlir::ElementsAttr getValue(); + void setValueAttr(::mlir::ElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Attribute value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::ElementsAttr value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ElementsAttr value); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ElementsAttr value); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r); +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ConstantOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ConvertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvertOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvertOpGenericAdaptorBase(ConvertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ConvertOpGenericAdaptor : public detail::ConvertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvertOpGenericAdaptorBase; +public: + ConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvertOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvertOpAdaptor : public ConvertOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvertOpGenericAdaptor::ConvertOpGenericAdaptor; + ConvertOpAdaptor(ConvertOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvertOpAdaptor; + template + using GenericAdaptor = ConvertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.convert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value operand, Type result_element_ty); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ConvertOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ConvolutionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvolutionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvolutionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvolutionOpGenericAdaptorBase(ConvolutionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class ConvolutionOpGenericAdaptor : public detail::ConvolutionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvolutionOpGenericAdaptorBase; +public: + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvolutionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvolutionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvolutionOpAdaptor : public ConvolutionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvolutionOpGenericAdaptor::ConvolutionOpGenericAdaptor; + ConvolutionOpAdaptor(ConvolutionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvolutionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvolutionOpAdaptor; + template + using GenericAdaptor = ConvolutionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.convolution"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 9 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + bool hasWindowReversal() { + auto reversal = getWindowReversalAttr(); + return reversal && llvm::any_of(reversal.getValues(), + [](bool v) { return v; }); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ConvolutionOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CopyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CopyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CopyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CopyOpGenericAdaptorBase(CopyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getCrossProgramPrefetchIndexAttr(); + ::std::optional getCrossProgramPrefetchIndex(); +}; +} // namespace detail +template +class CopyOpGenericAdaptor : public detail::CopyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CopyOpGenericAdaptorBase; +public: + CopyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CopyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CopyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CopyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CopyOpAdaptor : public CopyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CopyOpGenericAdaptor::CopyOpGenericAdaptor; + CopyOpAdaptor(CopyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CopyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CopyOpAdaptor; + template + using GenericAdaptor = CopyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("cross_program_prefetch_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getCrossProgramPrefetchIndexAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getCrossProgramPrefetchIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.copy"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getResult(); + ::mlir::IntegerAttr getCrossProgramPrefetchIndexAttr(); + ::std::optional getCrossProgramPrefetchIndex(); + void setCrossProgramPrefetchIndexAttr(::mlir::IntegerAttr attr); + void setCrossProgramPrefetchIndex(::std::optional attrValue); + ::mlir::Attribute removeCrossProgramPrefetchIndexAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, /*optional*/::mlir::IntegerAttr cross_program_prefetch_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, /*optional*/::mlir::IntegerAttr cross_program_prefetch_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, /*optional*/::mlir::IntegerAttr cross_program_prefetch_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CopyOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CosineOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CosineOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CosineOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CosineOpGenericAdaptorBase(CosineOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CosineOpGenericAdaptor : public detail::CosineOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CosineOpGenericAdaptorBase; +public: + CosineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CosineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CosineOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CosineOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CosineOpAdaptor : public CosineOpGenericAdaptor<::mlir::ValueRange> { +public: + using CosineOpGenericAdaptor::CosineOpGenericAdaptor; + CosineOpAdaptor(CosineOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CosineOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = CosineOpAdaptor; + template + using GenericAdaptor = CosineOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.cosine"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CosineOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CreateTokenOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CreateTokenOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CreateTokenOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CreateTokenOpGenericAdaptorBase(CreateTokenOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CreateTokenOpGenericAdaptor : public detail::CreateTokenOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CreateTokenOpGenericAdaptorBase; +public: + CreateTokenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CreateTokenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CreateTokenOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CreateTokenOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CreateTokenOpAdaptor : public CreateTokenOpGenericAdaptor<::mlir::ValueRange> { +public: + using CreateTokenOpGenericAdaptor::CreateTokenOpGenericAdaptor; + CreateTokenOpAdaptor(CreateTokenOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CreateTokenOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CreateTokenOpAdaptor; + template + using GenericAdaptor = CreateTokenOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.create_token"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getOutput(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CreateTokenOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CrossReplicaSumOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CrossReplicaSumOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CrossReplicaSumOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CrossReplicaSumOpGenericAdaptorBase(CrossReplicaSumOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); +}; +} // namespace detail +template +class CrossReplicaSumOpGenericAdaptor : public detail::CrossReplicaSumOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CrossReplicaSumOpGenericAdaptorBase; +public: + CrossReplicaSumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CrossReplicaSumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CrossReplicaSumOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CrossReplicaSumOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CrossReplicaSumOpAdaptor : public CrossReplicaSumOpGenericAdaptor<::mlir::ValueRange> { +public: + using CrossReplicaSumOpGenericAdaptor::CrossReplicaSumOpGenericAdaptor; + CrossReplicaSumOpAdaptor(CrossReplicaSumOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CrossReplicaSumOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CrossReplicaSumOpAdaptor; + template + using GenericAdaptor = CrossReplicaSumOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("replica_groups")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.cross-replica-sum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr replica_groups); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr replica_groups); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr replica_groups); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CrossReplicaSumOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CstrReshapableOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CstrReshapableOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CstrReshapableOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CstrReshapableOpGenericAdaptorBase(CstrReshapableOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CstrReshapableOpGenericAdaptor : public detail::CstrReshapableOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CstrReshapableOpGenericAdaptorBase; +public: + CstrReshapableOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CstrReshapableOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CstrReshapableOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CstrReshapableOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getNumElements() { + return (*getODSOperands(0).begin()); + } + + ValueT getDynamicShape() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CstrReshapableOpAdaptor : public CstrReshapableOpGenericAdaptor<::mlir::ValueRange> { +public: + using CstrReshapableOpGenericAdaptor::CstrReshapableOpGenericAdaptor; + CstrReshapableOpAdaptor(CstrReshapableOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CstrReshapableOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CstrReshapableOpAdaptor; + template + using GenericAdaptor = CstrReshapableOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.cstr_reshapable"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::IndexType> getNumElements(); + ::mlir::TypedValue<::mlir::RankedTensorType> getDynamicShape(); + ::mlir::OpOperand &getNumElementsMutable(); + ::mlir::OpOperand &getDynamicShapeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::shape::WitnessType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value num_elements, ::mlir::Value dynamic_shape); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value num_elements, ::mlir::Value dynamic_shape); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value num_elements, ::mlir::Value dynamic_shape); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CstrReshapableOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::CustomCallOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CustomCallOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CustomCallOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CustomCallOpGenericAdaptorBase(CustomCallOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getCallTargetNameAttr(); + ::llvm::StringRef getCallTargetName(); + ::mlir::BoolAttr getHasSideEffectAttr(); + bool getHasSideEffect(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + ::mlir::mhlo::CustomCallApiVersionAttr getApiVersionAttr(); + ::mlir::mhlo::CustomCallApiVersion getApiVersion(); + ::mlir::ArrayAttr getCalledComputationsAttr(); + ::mlir::ArrayAttr getCalledComputations(); + ::mlir::mhlo::CustomCallScheduleAttr getCustomCallScheduleAttr(); + ::mlir::mhlo::CustomCallSchedule getCustomCallSchedule(); + ::mlir::ArrayAttr getOperandLayoutsAttr(); + ::std::optional< ::mlir::ArrayAttr > getOperandLayouts(); + ::mlir::ArrayAttr getResultLayoutsAttr(); + ::std::optional< ::mlir::ArrayAttr > getResultLayouts(); + ::mlir::ArrayAttr getOutputOperandAliasesAttr(); + ::mlir::ArrayAttr getOutputOperandAliases(); +}; +} // namespace detail +template +class CustomCallOpGenericAdaptor : public detail::CustomCallOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CustomCallOpGenericAdaptorBase; +public: + CustomCallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CustomCallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CustomCallOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CustomCallOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CustomCallOpAdaptor : public CustomCallOpGenericAdaptor<::mlir::ValueRange> { +public: + using CustomCallOpGenericAdaptor::CustomCallOpGenericAdaptor; + CustomCallOpAdaptor(CustomCallOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CustomCallOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = CustomCallOpAdaptor; + template + using GenericAdaptor = CustomCallOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("api_version"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("call_target_name"), ::llvm::StringRef("called_computations"), ::llvm::StringRef("custom_call_schedule"), ::llvm::StringRef("has_side_effect"), ::llvm::StringRef("operand_layouts"), ::llvm::StringRef("output_operand_aliases"), ::llvm::StringRef("result_layouts")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getApiVersionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getApiVersionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getCallTargetNameAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getCallTargetNameAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getCalledComputationsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getCalledComputationsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getCustomCallScheduleAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getCustomCallScheduleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getHasSideEffectAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getHasSideEffectAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandLayoutsAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandLayoutsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getOutputOperandAliasesAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getOutputOperandAliasesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getResultLayoutsAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getResultLayoutsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.custom_call"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getCallTargetNameAttr(); + ::llvm::StringRef getCallTargetName(); + ::mlir::BoolAttr getHasSideEffectAttr(); + bool getHasSideEffect(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + ::mlir::mhlo::CustomCallApiVersionAttr getApiVersionAttr(); + ::mlir::mhlo::CustomCallApiVersion getApiVersion(); + ::mlir::ArrayAttr getCalledComputationsAttr(); + ::mlir::ArrayAttr getCalledComputations(); + ::mlir::mhlo::CustomCallScheduleAttr getCustomCallScheduleAttr(); + ::mlir::mhlo::CustomCallSchedule getCustomCallSchedule(); + ::mlir::ArrayAttr getOperandLayoutsAttr(); + ::std::optional< ::mlir::ArrayAttr > getOperandLayouts(); + ::mlir::ArrayAttr getResultLayoutsAttr(); + ::std::optional< ::mlir::ArrayAttr > getResultLayouts(); + ::mlir::ArrayAttr getOutputOperandAliasesAttr(); + ::mlir::ArrayAttr getOutputOperandAliases(); + void setCallTargetNameAttr(::mlir::StringAttr attr); + void setCallTargetName(::llvm::StringRef attrValue); + void setHasSideEffectAttr(::mlir::BoolAttr attr); + void setHasSideEffect(::std::optional attrValue); + void setBackendConfigAttr(::mlir::Attribute attr); + void setApiVersionAttr(::mlir::mhlo::CustomCallApiVersionAttr attr); + void setApiVersion(::std::optional<::mlir::mhlo::CustomCallApiVersion> attrValue); + void setCalledComputationsAttr(::mlir::ArrayAttr attr); + void setCustomCallScheduleAttr(::mlir::mhlo::CustomCallScheduleAttr attr); + void setCustomCallSchedule(::std::optional<::mlir::mhlo::CustomCallSchedule> attrValue); + void setOperandLayoutsAttr(::mlir::ArrayAttr attr); + void setResultLayoutsAttr(::mlir::ArrayAttr attr); + void setOutputOperandAliasesAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeHasSideEffectAttr(); + ::mlir::Attribute removeBackendConfigAttr(); + ::mlir::Attribute removeApiVersionAttr(); + ::mlir::Attribute removeCalledComputationsAttr(); + ::mlir::Attribute removeCustomCallScheduleAttr(); + ::mlir::Attribute removeOperandLayoutsAttr(); + ::mlir::Attribute removeResultLayoutsAttr(); + ::mlir::Attribute removeOutputOperandAliasesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange result_type, ::mlir::ValueRange inputs, ::mlir::StringAttr call_target_name, ::mlir::BoolAttr has_side_effect, ::mlir::StringAttr backend_config, ::mlir::mhlo::CustomCallApiVersionAttr api_version, ::mlir::ArrayAttr called_computations, ::mlir::ArrayAttr operand_layouts, ::mlir::ArrayAttr result_layouts); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::mlir::StringAttr call_target_name, /*optional*/::mlir::BoolAttr has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersionAttr api_version, /*optional*/::mlir::ArrayAttr called_computations, /*optional*/::mlir::mhlo::CustomCallScheduleAttr custom_call_schedule, /*optional*/::mlir::ArrayAttr operand_layouts, /*optional*/::mlir::ArrayAttr result_layouts, /*optional*/::mlir::ArrayAttr output_operand_aliases); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::llvm::StringRef call_target_name, /*optional*/bool has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersion api_version, /*optional*/::mlir::ArrayAttr called_computations, /*optional*/::mlir::mhlo::CustomCallSchedule custom_call_schedule, /*optional*/::mlir::ArrayAttr operand_layouts, /*optional*/::mlir::ArrayAttr result_layouts, /*optional*/::mlir::ArrayAttr output_operand_aliases); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 9 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::CustomCallOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DivOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DivOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DivOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DivOpGenericAdaptorBase(DivOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DivOpGenericAdaptor : public detail::DivOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DivOpGenericAdaptorBase; +public: + DivOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DivOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DivOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DivOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DivOpAdaptor : public DivOpGenericAdaptor<::mlir::ValueRange> { +public: + using DivOpGenericAdaptor::DivOpGenericAdaptor; + DivOpAdaptor(DivOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DivOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = DivOpAdaptor; + template + using GenericAdaptor = DivOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.divide"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DivOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DomainOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DomainOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DomainOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DomainOpGenericAdaptorBase(DomainOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DomainKindAttr getKindAttr(); + ::mlir::mhlo::DomainKind getKind(); + ::mlir::StringAttr getEntryMetadataAttr(); + ::llvm::StringRef getEntryMetadata(); + ::mlir::StringAttr getExitMetadataAttr(); + ::llvm::StringRef getExitMetadata(); +}; +} // namespace detail +template +class DomainOpGenericAdaptor : public detail::DomainOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DomainOpGenericAdaptorBase; +public: + DomainOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DomainOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DomainOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DomainOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DomainOpAdaptor : public DomainOpGenericAdaptor<::mlir::ValueRange> { +public: + using DomainOpGenericAdaptor::DomainOpGenericAdaptor; + DomainOpAdaptor(DomainOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DomainOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DomainOpAdaptor; + template + using GenericAdaptor = DomainOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("entry_metadata"), ::llvm::StringRef("exit_metadata"), ::llvm::StringRef("kind")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEntryMetadataAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEntryMetadataAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getExitMetadataAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getExitMetadataAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.domain"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getResult(); + ::mlir::mhlo::DomainKindAttr getKindAttr(); + ::mlir::mhlo::DomainKind getKind(); + ::mlir::StringAttr getEntryMetadataAttr(); + ::llvm::StringRef getEntryMetadata(); + ::mlir::StringAttr getExitMetadataAttr(); + ::llvm::StringRef getExitMetadata(); + void setKindAttr(::mlir::mhlo::DomainKindAttr attr); + void setKind(::mlir::mhlo::DomainKind attrValue); + void setEntryMetadataAttr(::mlir::StringAttr attr); + void setEntryMetadata(::llvm::StringRef attrValue); + void setExitMetadataAttr(::mlir::StringAttr attr); + void setExitMetadata(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::mhlo::DomainKindAttr kind, ::mlir::StringAttr entry_metadata, ::mlir::StringAttr exit_metadata); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::mhlo::DomainKindAttr kind, ::mlir::StringAttr entry_metadata, ::mlir::StringAttr exit_metadata); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::mhlo::DomainKindAttr kind, ::mlir::StringAttr entry_metadata, ::mlir::StringAttr exit_metadata); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::mhlo::DomainKind kind, ::llvm::StringRef entry_metadata, ::llvm::StringRef exit_metadata); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::mhlo::DomainKind kind, ::llvm::StringRef entry_metadata, ::llvm::StringRef exit_metadata); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::mhlo::DomainKind kind, ::llvm::StringRef entry_metadata, ::llvm::StringRef exit_metadata); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DomainOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DotGeneralOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DotGeneralOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DotGeneralOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DotGeneralOpGenericAdaptorBase(DotGeneralOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DotGeneralOpGenericAdaptor : public detail::DotGeneralOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DotGeneralOpGenericAdaptorBase; +public: + DotGeneralOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DotGeneralOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DotGeneralOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DotGeneralOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DotGeneralOpAdaptor : public DotGeneralOpGenericAdaptor<::mlir::ValueRange> { +public: + using DotGeneralOpGenericAdaptor::DotGeneralOpGenericAdaptor; + DotGeneralOpAdaptor(DotGeneralOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DotGeneralOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DotGeneralOpAdaptor; + template + using GenericAdaptor = DotGeneralOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dot_general"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DotGeneralOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DotOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DotOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DotOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DotOpGenericAdaptorBase(DotOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DotOpGenericAdaptor : public detail::DotOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DotOpGenericAdaptorBase; +public: + DotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DotOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DotOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DotOpAdaptor : public DotOpGenericAdaptor<::mlir::ValueRange> { +public: + using DotOpGenericAdaptor::DotOpGenericAdaptor; + DotOpAdaptor(DotOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DotOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DotOpAdaptor; + template + using GenericAdaptor = DotOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dot"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DotOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicBroadcastInDimOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicBroadcastInDimOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicBroadcastInDimOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicBroadcastInDimOpGenericAdaptorBase(DynamicBroadcastInDimOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); + ::mlir::DenseIntElementsAttr getKnownExpandingDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getKnownExpandingDimensions(); + ::mlir::DenseIntElementsAttr getKnownNonexpandingDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getKnownNonexpandingDimensions(); +}; +} // namespace detail +template +class DynamicBroadcastInDimOpGenericAdaptor : public detail::DynamicBroadcastInDimOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicBroadcastInDimOpGenericAdaptorBase; +public: + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicBroadcastInDimOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutputDimensions() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicBroadcastInDimOpAdaptor : public DynamicBroadcastInDimOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicBroadcastInDimOpGenericAdaptor::DynamicBroadcastInDimOpGenericAdaptor; + DynamicBroadcastInDimOpAdaptor(DynamicBroadcastInDimOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicBroadcastInDimOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicBroadcastInDimOpAdaptor; + template + using GenericAdaptor = DynamicBroadcastInDimOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions"), ::llvm::StringRef("known_expanding_dimensions"), ::llvm::StringRef("known_nonexpanding_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getKnownExpandingDimensionsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getKnownExpandingDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getKnownNonexpandingDimensionsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getKnownNonexpandingDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_broadcast_in_dim"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutputDimensions(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputDimensionsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); + ::mlir::DenseIntElementsAttr getKnownExpandingDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getKnownExpandingDimensions(); + ::mlir::DenseIntElementsAttr getKnownNonexpandingDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getKnownNonexpandingDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setKnownExpandingDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setKnownNonexpandingDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeKnownExpandingDimensionsAttr(); + ::mlir::Attribute removeKnownNonexpandingDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Type result_type, Value operand, Value output_dimensions, DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value output_dimensions, ::mlir::DenseIntElementsAttr broadcast_dimensions, /*optional*/::mlir::DenseIntElementsAttr known_expanding_dimensions, /*optional*/::mlir::DenseIntElementsAttr known_nonexpanding_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output_dimensions, ::mlir::DenseIntElementsAttr broadcast_dimensions, /*optional*/::mlir::DenseIntElementsAttr known_expanding_dimensions, /*optional*/::mlir::DenseIntElementsAttr known_nonexpanding_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicBroadcastInDimOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicConvOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicConvOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicConvOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicConvOpGenericAdaptorBase(DynamicConvOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DynamicConvOpGenericAdaptor : public detail::DynamicConvOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicConvOpGenericAdaptorBase; +public: + DynamicConvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicConvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicConvOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicConvOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getDPadding() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicConvOpAdaptor : public DynamicConvOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicConvOpGenericAdaptor::DynamicConvOpGenericAdaptor; + DynamicConvOpAdaptor(DynamicConvOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicConvOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicConvOpAdaptor; + template + using GenericAdaptor = DynamicConvOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_conv"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::TypedValue<::mlir::TensorType> getDPadding(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getDPaddingMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 9 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicConvOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicGatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicGatherOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicGatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicGatherOpGenericAdaptorBase(DynamicGatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); +}; +} // namespace detail +template +class DynamicGatherOpGenericAdaptor : public detail::DynamicGatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicGatherOpGenericAdaptorBase; +public: + DynamicGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicGatherOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicGatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getSliceSizes() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicGatherOpAdaptor : public DynamicGatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicGatherOpGenericAdaptor::DynamicGatherOpGenericAdaptor; + DynamicGatherOpAdaptor(DynamicGatherOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicGatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicGatherOpAdaptor; + template + using GenericAdaptor = DynamicGatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("indices_are_sorted")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIndicesAreSortedAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIndicesAreSortedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getStartIndices(); + ::mlir::TypedValue<::mlir::TensorType> getSliceSizes(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + ::mlir::OpOperand &getSliceSizesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + void setDimensionNumbersAttr(::mlir::mhlo::GatherDimensionNumbersAttr attr); + void setIndicesAreSortedAttr(::mlir::BoolAttr attr); + void setIndicesAreSorted(::std::optional attrValue); + ::mlir::Attribute removeIndicesAreSortedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicGatherOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicIotaOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicIotaOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicIotaOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicIotaOpGenericAdaptorBase(DynamicIotaOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); +}; +} // namespace detail +template +class DynamicIotaOpGenericAdaptor : public detail::DynamicIotaOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicIotaOpGenericAdaptorBase; +public: + DynamicIotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicIotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicIotaOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicIotaOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOutputShape() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicIotaOpAdaptor : public DynamicIotaOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicIotaOpGenericAdaptor::DynamicIotaOpGenericAdaptor; + DynamicIotaOpAdaptor(DynamicIotaOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicIotaOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicIotaOpAdaptor; + template + using GenericAdaptor = DynamicIotaOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("iota_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIotaDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIotaDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_iota"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutputShape(); + ::mlir::OpOperand &getOutputShapeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); + void setIotaDimensionAttr(::mlir::IntegerAttr attr); + void setIotaDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value output_shape, ::mlir::IntegerAttr iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value output_shape, ::mlir::IntegerAttr iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value output_shape, uint64_t iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value output_shape, uint64_t iota_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicIotaOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicPadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicPadOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicPadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicPadOpGenericAdaptorBase(DynamicPadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicPadOpGenericAdaptor : public detail::DynamicPadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicPadOpGenericAdaptorBase; +public: + DynamicPadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicPadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicPadOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicPadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getPaddingValue() { + return (*getODSOperands(1).begin()); + } + + ValueT getEdgePaddingLow() { + return (*getODSOperands(2).begin()); + } + + ValueT getEdgePaddingHigh() { + return (*getODSOperands(3).begin()); + } + + ValueT getInteriorPadding() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicPadOpAdaptor : public DynamicPadOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicPadOpGenericAdaptor::DynamicPadOpGenericAdaptor; + DynamicPadOpAdaptor(DynamicPadOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicPadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<5>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicPadOpAdaptor; + template + using GenericAdaptor = DynamicPadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_pad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getPaddingValue(); + ::mlir::TypedValue<::mlir::RankedTensorType> getEdgePaddingLow(); + ::mlir::TypedValue<::mlir::RankedTensorType> getEdgePaddingHigh(); + ::mlir::TypedValue<::mlir::RankedTensorType> getInteriorPadding(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getPaddingValueMutable(); + ::mlir::OpOperand &getEdgePaddingLowMutable(); + ::mlir::OpOperand &getEdgePaddingHighMutable(); + ::mlir::OpOperand &getInteriorPaddingMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::Value edge_padding_low, ::mlir::Value edge_padding_high, ::mlir::Value interior_padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::Value edge_padding_low, ::mlir::Value edge_padding_high, ::mlir::Value interior_padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicPadOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicReshapeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicReshapeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicReshapeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicReshapeOpGenericAdaptorBase(DynamicReshapeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicReshapeOpGenericAdaptor : public detail::DynamicReshapeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicReshapeOpGenericAdaptorBase; +public: + DynamicReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicReshapeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicReshapeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutputShape() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicReshapeOpAdaptor : public DynamicReshapeOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicReshapeOpGenericAdaptor::DynamicReshapeOpGenericAdaptor; + DynamicReshapeOpAdaptor(DynamicReshapeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicReshapeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicReshapeOpAdaptor; + template + using GenericAdaptor = DynamicReshapeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_reshape"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutputShape(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputShapeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value output_shape); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output_shape); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicReshapeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicSliceOpGenericAdaptorBase(DynamicSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); +}; +} // namespace detail +template +class DynamicSliceOpGenericAdaptor : public detail::DynamicSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicSliceOpGenericAdaptorBase; +public: + DynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getStartIndices() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicSliceOpAdaptor : public DynamicSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicSliceOpGenericAdaptor::DynamicSliceOpGenericAdaptor; + DynamicSliceOpAdaptor(DynamicSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicSliceOpAdaptor; + template + using GenericAdaptor = DynamicSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("slice_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getSliceSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getSliceSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::Operation::operand_range getStartIndices(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::MutableOperandRange getStartIndicesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); + void setSliceSizesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::ValueRange start_indices, ::mlir::DenseIntElementsAttr slice_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::ValueRange start_indices, ::mlir::DenseIntElementsAttr slice_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::ValueRange start_indices, ::mlir::DenseIntElementsAttr slice_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicSliceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::DynamicUpdateSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicUpdateSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicUpdateSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicUpdateSliceOpGenericAdaptorBase(DynamicUpdateSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicUpdateSliceOpGenericAdaptor : public detail::DynamicUpdateSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicUpdateSliceOpGenericAdaptorBase; +public: + DynamicUpdateSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicUpdateSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicUpdateSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicUpdateSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getUpdate() { + return (*getODSOperands(1).begin()); + } + + RangeT getStartIndices() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicUpdateSliceOpAdaptor : public DynamicUpdateSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicUpdateSliceOpGenericAdaptor::DynamicUpdateSliceOpGenericAdaptor; + DynamicUpdateSliceOpAdaptor(DynamicUpdateSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicUpdateSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicUpdateSliceOpAdaptor; + template + using GenericAdaptor = DynamicUpdateSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.dynamic_update_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getUpdate(); + ::mlir::Operation::operand_range getStartIndices(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getUpdateMutable(); + ::mlir::MutableOperandRange getStartIndicesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value update, ::mlir::ValueRange start_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value update, ::mlir::ValueRange start_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value update, ::mlir::ValueRange start_indices); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::DynamicUpdateSliceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::EinsumOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class EinsumOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + EinsumOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + EinsumOpGenericAdaptorBase(EinsumOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getEinsumConfigAttr(); + ::llvm::StringRef getEinsumConfig(); +}; +} // namespace detail +template +class EinsumOpGenericAdaptor : public detail::EinsumOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::EinsumOpGenericAdaptorBase; +public: + EinsumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + EinsumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : EinsumOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + EinsumOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class EinsumOpAdaptor : public EinsumOpGenericAdaptor<::mlir::ValueRange> { +public: + using EinsumOpGenericAdaptor::EinsumOpGenericAdaptor; + EinsumOpAdaptor(EinsumOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class EinsumOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = EinsumOpAdaptor; + template + using GenericAdaptor = EinsumOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("einsum_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEinsumConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEinsumConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.einsum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getEinsumConfigAttr(); + ::llvm::StringRef getEinsumConfig(); + void setEinsumConfigAttr(::mlir::StringAttr attr); + void setEinsumConfig(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::StringAttr einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::StringAttr einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::llvm::StringRef einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::llvm::StringRef einsum_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::EinsumOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ExpOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExpOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ExpOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ExpOpGenericAdaptorBase(ExpOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ExpOpGenericAdaptor : public detail::ExpOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExpOpGenericAdaptorBase; +public: + ExpOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExpOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExpOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ExpOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExpOpAdaptor : public ExpOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExpOpGenericAdaptor::ExpOpGenericAdaptor; + ExpOpAdaptor(ExpOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ExpOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExpOpAdaptor; + template + using GenericAdaptor = ExpOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.exponential"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ExpOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::Expm1Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Expm1OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Expm1OpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Expm1OpGenericAdaptorBase(Expm1Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class Expm1OpGenericAdaptor : public detail::Expm1OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Expm1OpGenericAdaptorBase; +public: + Expm1OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Expm1OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Expm1OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Expm1OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Expm1OpAdaptor : public Expm1OpGenericAdaptor<::mlir::ValueRange> { +public: + using Expm1OpGenericAdaptor::Expm1OpGenericAdaptor; + Expm1OpAdaptor(Expm1Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Expm1Op : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = Expm1OpAdaptor; + template + using GenericAdaptor = Expm1OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.exponential_minus_one"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::Expm1Op) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::FftOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FftOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FftOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FftOpGenericAdaptorBase(FftOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::FftTypeAttr getFftTypeAttr(); + ::mlir::mhlo::FftType getFftType(); + ::mlir::DenseIntElementsAttr getFftLengthAttr(); + ::mlir::DenseIntElementsAttr getFftLength(); +}; +} // namespace detail +template +class FftOpGenericAdaptor : public detail::FftOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FftOpGenericAdaptorBase; +public: + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FftOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FftOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FftOpAdaptor : public FftOpGenericAdaptor<::mlir::ValueRange> { +public: + using FftOpGenericAdaptor::FftOpGenericAdaptor; + FftOpAdaptor(FftOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FftOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FftOpAdaptor; + template + using GenericAdaptor = FftOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("fft_length"), ::llvm::StringRef("fft_type")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFftLengthAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFftLengthAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFftTypeAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFftTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.fft"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::FftTypeAttr getFftTypeAttr(); + ::mlir::mhlo::FftType getFftType(); + ::mlir::DenseIntElementsAttr getFftLengthAttr(); + ::mlir::DenseIntElementsAttr getFftLength(); + void setFftTypeAttr(::mlir::mhlo::FftTypeAttr attr); + void setFftType(::mlir::mhlo::FftType attrValue); + void setFftLengthAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::mhlo::FftTypeAttr fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::mhlo::FftTypeAttr fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::mhlo::FftTypeAttr fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::mhlo::FftType fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::mhlo::FftType fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::mhlo::FftType fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::FftOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::FloorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FloorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FloorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FloorOpGenericAdaptorBase(FloorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class FloorOpGenericAdaptor : public detail::FloorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FloorOpGenericAdaptorBase; +public: + FloorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FloorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FloorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FloorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FloorOpAdaptor : public FloorOpGenericAdaptor<::mlir::ValueRange> { +public: + using FloorOpGenericAdaptor::FloorOpGenericAdaptor; + FloorOpAdaptor(FloorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FloorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = FloorOpAdaptor; + template + using GenericAdaptor = FloorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.floor"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::FloorOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::FusionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FusionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FusionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FusionOpGenericAdaptorBase(FusionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::FusionKindAttr getFusionKindAttr(); + ::std::optional<::mlir::mhlo::FusionKind> getFusionKind(); + ::mlir::ArrayAttr getOutputOperandAliasesAttr(); + ::mlir::ArrayAttr getOutputOperandAliases(); + ::mlir::Region &getFusedComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class FusionOpGenericAdaptor : public detail::FusionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FusionOpGenericAdaptorBase; +public: + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FusionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FusionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FusionOpAdaptor : public FusionOpGenericAdaptor<::mlir::ValueRange> { +public: + using FusionOpGenericAdaptor::FusionOpGenericAdaptor; + FusionOpAdaptor(FusionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FusionOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = FusionOpAdaptor; + template + using GenericAdaptor = FusionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("fusion_kind"), ::llvm::StringRef("output_operand_aliases")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFusionKindAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFusionKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getOutputOperandAliasesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getOutputOperandAliasesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.fusion"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Operation::result_range getResults(); + ::mlir::Region &getFusedComputation(); + ::mlir::mhlo::FusionKindAttr getFusionKindAttr(); + ::std::optional<::mlir::mhlo::FusionKind> getFusionKind(); + ::mlir::ArrayAttr getOutputOperandAliasesAttr(); + ::mlir::ArrayAttr getOutputOperandAliases(); + void setFusionKindAttr(::mlir::mhlo::FusionKindAttr attr); + void setFusionKind(::std::optional<::mlir::mhlo::FusionKind> attrValue); + void setOutputOperandAliasesAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeFusionKindAttr(); + ::mlir::Attribute removeOutputOperandAliasesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange results, ::mlir::ValueRange inputs, /*optional*/::mlir::mhlo::FusionKindAttr fusion_kind, /*optional*/::mlir::ArrayAttr output_operand_aliases); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::FusionOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::GatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GatherOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GatherOpGenericAdaptorBase(GatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); +}; +} // namespace detail +template +class GatherOpGenericAdaptor : public detail::GatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GatherOpGenericAdaptorBase; +public: + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GatherOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GatherOpAdaptor : public GatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using GatherOpGenericAdaptor::GatherOpGenericAdaptor; + GatherOpAdaptor(GatherOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GatherOpAdaptor; + template + using GenericAdaptor = GatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("indices_are_sorted"), ::llvm::StringRef("slice_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIndicesAreSortedAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIndicesAreSortedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getSliceSizesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getSliceSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getStartIndices(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + void setDimensionNumbersAttr(::mlir::mhlo::GatherDimensionNumbersAttr attr); + void setSliceSizesAttr(::mlir::DenseIntElementsAttr attr); + void setIndicesAreSortedAttr(::mlir::BoolAttr attr); + void setIndicesAreSorted(::std::optional attrValue); + ::mlir::Attribute removeIndicesAreSortedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/::mlir::BoolAttr indices_are_sorted); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, /*optional*/bool indices_are_sorted = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::GatherOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::GetDimensionSizeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GetDimensionSizeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GetDimensionSizeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GetDimensionSizeOpGenericAdaptorBase(GetDimensionSizeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); +}; +} // namespace detail +template +class GetDimensionSizeOpGenericAdaptor : public detail::GetDimensionSizeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GetDimensionSizeOpGenericAdaptorBase; +public: + GetDimensionSizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GetDimensionSizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GetDimensionSizeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GetDimensionSizeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GetDimensionSizeOpAdaptor : public GetDimensionSizeOpGenericAdaptor<::mlir::ValueRange> { +public: + using GetDimensionSizeOpGenericAdaptor::GetDimensionSizeOpGenericAdaptor; + GetDimensionSizeOpAdaptor(GetDimensionSizeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GetDimensionSizeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = GetDimensionSizeOpAdaptor; + template + using GenericAdaptor = GetDimensionSizeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.get_dimension_size"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint64_t dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::GetDimensionSizeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::GetTupleElementOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GetTupleElementOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GetTupleElementOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GetTupleElementOpGenericAdaptorBase(GetTupleElementOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIndexAttr(); + uint32_t getIndex(); +}; +} // namespace detail +template +class GetTupleElementOpGenericAdaptor : public detail::GetTupleElementOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GetTupleElementOpGenericAdaptorBase; +public: + GetTupleElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GetTupleElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GetTupleElementOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GetTupleElementOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GetTupleElementOpAdaptor : public GetTupleElementOpGenericAdaptor<::mlir::ValueRange> { +public: + using GetTupleElementOpGenericAdaptor::GetTupleElementOpGenericAdaptor; + GetTupleElementOpAdaptor(GetTupleElementOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GetTupleElementOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GetTupleElementOpAdaptor; + template + using GenericAdaptor = GetTupleElementOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIndexAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.get_tuple_element"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getIndexAttr(); + uint32_t getIndex(); + void setIndexAttr(::mlir::IntegerAttr attr); + void setIndex(uint32_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::IntegerAttr index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::IntegerAttr index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, uint32_t index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, uint32_t index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint32_t index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::GetTupleElementOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::IfOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IfOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IfOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IfOpGenericAdaptorBase(IfOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::Region &getTrueBranch(); + ::mlir::Region &getFalseBranch(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class IfOpGenericAdaptor : public detail::IfOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IfOpGenericAdaptorBase; +public: + IfOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IfOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IfOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IfOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getPred() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IfOpAdaptor : public IfOpGenericAdaptor<::mlir::ValueRange> { +public: + using IfOpGenericAdaptor::IfOpGenericAdaptor; + IfOpAdaptor(IfOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IfOp : public ::mlir::Op::Impl, ::mlir::OpTrait::VariadicResults, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::SingleBlock, ::mlir::OpTrait::SingleBlockImplicitTerminator::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = IfOpAdaptor; + template + using GenericAdaptor = IfOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.if"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getPred(); + ::mlir::OpOperand &getPredMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getTrueBranch(); + ::mlir::Region &getFalseBranch(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value pred); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value pred); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::IfOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ImagOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ImagOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ImagOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ImagOpGenericAdaptorBase(ImagOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ImagOpGenericAdaptor : public detail::ImagOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ImagOpGenericAdaptorBase; +public: + ImagOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ImagOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ImagOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ImagOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ImagOpAdaptor : public ImagOpGenericAdaptor<::mlir::ValueRange> { +public: + using ImagOpGenericAdaptor::ImagOpGenericAdaptor; + ImagOpAdaptor(ImagOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ImagOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ImagOpAdaptor; + template + using GenericAdaptor = ImagOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.imag"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ImagOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::InfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + InfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + InfeedOpGenericAdaptorBase(InfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getInfeedConfigAttr(); + ::llvm::StringRef getInfeedConfig(); + ::mlir::ArrayAttr getLayoutAttr(); + ::std::optional< ::mlir::ArrayAttr > getLayout(); +}; +} // namespace detail +template +class InfeedOpGenericAdaptor : public detail::InfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InfeedOpGenericAdaptorBase; +public: + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + InfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InfeedOpAdaptor : public InfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using InfeedOpGenericAdaptor::InfeedOpGenericAdaptor; + InfeedOpAdaptor(InfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class InfeedOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = InfeedOpAdaptor; + template + using GenericAdaptor = InfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("infeed_config"), ::llvm::StringRef("layout")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getInfeedConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getInfeedConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.infeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getInfeedConfigAttr(); + ::llvm::StringRef getInfeedConfig(); + ::mlir::ArrayAttr getLayoutAttr(); + ::std::optional< ::mlir::ArrayAttr > getLayout(); + void setInfeedConfigAttr(::mlir::StringAttr attr); + void setInfeedConfig(::llvm::StringRef attrValue); + void setLayoutAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeLayoutAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value token, ::mlir::StringAttr infeed_config, /*optional*/::mlir::ArrayAttr layout); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value token, ::llvm::StringRef infeed_config, /*optional*/::mlir::ArrayAttr layout); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::InfeedOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::IotaOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IotaOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IotaOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IotaOpGenericAdaptorBase(IotaOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); +}; +} // namespace detail +template +class IotaOpGenericAdaptor : public detail::IotaOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IotaOpGenericAdaptorBase; +public: + IotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IotaOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IotaOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IotaOpAdaptor : public IotaOpGenericAdaptor<::mlir::ValueRange> { +public: + using IotaOpGenericAdaptor::IotaOpGenericAdaptor; + IotaOpAdaptor(IotaOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IotaOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = IotaOpAdaptor; + template + using GenericAdaptor = IotaOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("iota_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIotaDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIotaDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.iota"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutput(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); + void setIotaDimensionAttr(::mlir::IntegerAttr attr); + void setIotaDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::IntegerAttr iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::IntegerAttr iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, uint64_t iota_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, uint64_t iota_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::IotaOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::IsFiniteOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IsFiniteOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IsFiniteOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IsFiniteOpGenericAdaptorBase(IsFiniteOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class IsFiniteOpGenericAdaptor : public detail::IsFiniteOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IsFiniteOpGenericAdaptorBase; +public: + IsFiniteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IsFiniteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IsFiniteOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IsFiniteOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getX() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IsFiniteOpAdaptor : public IsFiniteOpGenericAdaptor<::mlir::ValueRange> { +public: + using IsFiniteOpGenericAdaptor::IsFiniteOpGenericAdaptor; + IsFiniteOpAdaptor(IsFiniteOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IsFiniteOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = IsFiniteOpAdaptor; + template + using GenericAdaptor = IsFiniteOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.is_finite"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getX(); + ::mlir::OpOperand &getXMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getY(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type y, ::mlir::Value x); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value x); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value x); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::IsFiniteOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::Log1pOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Log1pOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Log1pOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Log1pOpGenericAdaptorBase(Log1pOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class Log1pOpGenericAdaptor : public detail::Log1pOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Log1pOpGenericAdaptorBase; +public: + Log1pOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Log1pOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Log1pOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Log1pOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Log1pOpAdaptor : public Log1pOpGenericAdaptor<::mlir::ValueRange> { +public: + using Log1pOpGenericAdaptor::Log1pOpGenericAdaptor; + Log1pOpAdaptor(Log1pOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Log1pOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = Log1pOpAdaptor; + template + using GenericAdaptor = Log1pOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.log_plus_one"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::Log1pOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::LogOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class LogOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + LogOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + LogOpGenericAdaptorBase(LogOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class LogOpGenericAdaptor : public detail::LogOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::LogOpGenericAdaptorBase; +public: + LogOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + LogOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : LogOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + LogOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class LogOpAdaptor : public LogOpGenericAdaptor<::mlir::ValueRange> { +public: + using LogOpGenericAdaptor::LogOpGenericAdaptor; + LogOpAdaptor(LogOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class LogOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = LogOpAdaptor; + template + using GenericAdaptor = LogOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.log"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::LogOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::LogisticOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class LogisticOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + LogisticOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + LogisticOpGenericAdaptorBase(LogisticOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class LogisticOpGenericAdaptor : public detail::LogisticOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::LogisticOpGenericAdaptorBase; +public: + LogisticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + LogisticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : LogisticOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + LogisticOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class LogisticOpAdaptor : public LogisticOpGenericAdaptor<::mlir::ValueRange> { +public: + using LogisticOpGenericAdaptor::LogisticOpGenericAdaptor; + LogisticOpAdaptor(LogisticOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class LogisticOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = LogisticOpAdaptor; + template + using GenericAdaptor = LogisticOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.logistic"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::LogisticOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::MapOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MapOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MapOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MapOpGenericAdaptorBase(MapOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class MapOpGenericAdaptor : public detail::MapOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MapOpGenericAdaptorBase; +public: + MapOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MapOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MapOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MapOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MapOpAdaptor : public MapOpGenericAdaptor<::mlir::ValueRange> { +public: + using MapOpGenericAdaptor::MapOpGenericAdaptor; + MapOpAdaptor(MapOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MapOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::SingleBlock, ::mlir::OpTrait::SingleBlockImplicitTerminator::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = MapOpAdaptor; + template + using GenericAdaptor = MapOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.map"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::MapOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::MaxOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MaxOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MaxOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MaxOpGenericAdaptorBase(MaxOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class MaxOpGenericAdaptor : public detail::MaxOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MaxOpGenericAdaptorBase; +public: + MaxOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MaxOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MaxOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MaxOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MaxOpAdaptor : public MaxOpGenericAdaptor<::mlir::ValueRange> { +public: + using MaxOpGenericAdaptor::MaxOpGenericAdaptor; + MaxOpAdaptor(MaxOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MaxOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MaxOpAdaptor; + template + using GenericAdaptor = MaxOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.maximum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::MaxOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::MinOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MinOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MinOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MinOpGenericAdaptorBase(MinOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class MinOpGenericAdaptor : public detail::MinOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MinOpGenericAdaptorBase; +public: + MinOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MinOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MinOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MinOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MinOpAdaptor : public MinOpGenericAdaptor<::mlir::ValueRange> { +public: + using MinOpGenericAdaptor::MinOpGenericAdaptor; + MinOpAdaptor(MinOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MinOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MinOpAdaptor; + template + using GenericAdaptor = MinOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.minimum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::MinOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::MulOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MulOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MulOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MulOpGenericAdaptorBase(MulOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class MulOpGenericAdaptor : public detail::MulOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MulOpGenericAdaptorBase; +public: + MulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MulOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MulOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MulOpAdaptor : public MulOpGenericAdaptor<::mlir::ValueRange> { +public: + using MulOpGenericAdaptor::MulOpGenericAdaptor; + MulOpAdaptor(MulOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MulOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MulOpAdaptor; + template + using GenericAdaptor = MulOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.multiply"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::MulOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::NegOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class NegOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + NegOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + NegOpGenericAdaptorBase(NegOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class NegOpGenericAdaptor : public detail::NegOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::NegOpGenericAdaptorBase; +public: + NegOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + NegOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : NegOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + NegOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class NegOpAdaptor : public NegOpGenericAdaptor<::mlir::ValueRange> { +public: + using NegOpGenericAdaptor::NegOpGenericAdaptor; + NegOpAdaptor(NegOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class NegOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = NegOpAdaptor; + template + using GenericAdaptor = NegOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.negate"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::NegOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::NotOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class NotOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + NotOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + NotOpGenericAdaptorBase(NotOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class NotOpGenericAdaptor : public detail::NotOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::NotOpGenericAdaptorBase; +public: + NotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + NotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : NotOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + NotOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class NotOpAdaptor : public NotOpGenericAdaptor<::mlir::ValueRange> { +public: + using NotOpGenericAdaptor::NotOpGenericAdaptor; + NotOpAdaptor(NotOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class NotOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = NotOpAdaptor; + template + using GenericAdaptor = NotOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.not"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::NotOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::OptimizationBarrierOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OptimizationBarrierOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OptimizationBarrierOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OptimizationBarrierOpGenericAdaptorBase(OptimizationBarrierOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class OptimizationBarrierOpGenericAdaptor : public detail::OptimizationBarrierOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OptimizationBarrierOpGenericAdaptorBase; +public: + OptimizationBarrierOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OptimizationBarrierOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OptimizationBarrierOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OptimizationBarrierOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OptimizationBarrierOpAdaptor : public OptimizationBarrierOpGenericAdaptor<::mlir::ValueRange> { +public: + using OptimizationBarrierOpGenericAdaptor::OptimizationBarrierOpGenericAdaptor; + OptimizationBarrierOpAdaptor(OptimizationBarrierOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OptimizationBarrierOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = OptimizationBarrierOpAdaptor; + template + using GenericAdaptor = OptimizationBarrierOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.optimization_barrier"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::MutableOperandRange getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Operation::result_range getResult(); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::OptimizationBarrierOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::OrOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OrOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OrOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OrOpGenericAdaptorBase(OrOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class OrOpGenericAdaptor : public detail::OrOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OrOpGenericAdaptorBase; +public: + OrOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OrOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OrOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OrOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OrOpAdaptor : public OrOpGenericAdaptor<::mlir::ValueRange> { +public: + using OrOpGenericAdaptor::OrOpGenericAdaptor; + OrOpAdaptor(OrOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OrOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = OrOpAdaptor; + template + using GenericAdaptor = OrOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.or"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::OrOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::OutfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OutfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OutfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OutfeedOpGenericAdaptorBase(OutfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getOutfeedConfigAttr(); + ::llvm::StringRef getOutfeedConfig(); +}; +} // namespace detail +template +class OutfeedOpGenericAdaptor : public detail::OutfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OutfeedOpGenericAdaptorBase; +public: + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OutfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OutfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + ValueT getToken() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OutfeedOpAdaptor : public OutfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using OutfeedOpGenericAdaptor::OutfeedOpGenericAdaptor; + OutfeedOpAdaptor(OutfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OutfeedOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = OutfeedOpAdaptor; + template + using GenericAdaptor = OutfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("outfeed_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getOutfeedConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getOutfeedConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.outfeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Value getToken(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getOutfeedConfigAttr(); + ::llvm::StringRef getOutfeedConfig(); + void setOutfeedConfigAttr(::mlir::StringAttr attr); + void setOutfeedConfig(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::StringAttr outfeed_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::StringAttr outfeed_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::StringAttr outfeed_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::Value token, ::llvm::StringRef outfeed_config = ""); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value token, ::llvm::StringRef outfeed_config = ""); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::Value token, ::llvm::StringRef outfeed_config = ""); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::OutfeedOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::PadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PadOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PadOpGenericAdaptorBase(PadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getEdgePaddingLowAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingLow(); + ::mlir::DenseIntElementsAttr getEdgePaddingHighAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingHigh(); + ::mlir::DenseIntElementsAttr getInteriorPaddingAttr(); + ::mlir::DenseIntElementsAttr getInteriorPadding(); +}; +} // namespace detail +template +class PadOpGenericAdaptor : public detail::PadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PadOpGenericAdaptorBase; +public: + PadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PadOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getPaddingValue() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PadOpAdaptor : public PadOpGenericAdaptor<::mlir::ValueRange> { +public: + using PadOpGenericAdaptor::PadOpGenericAdaptor; + PadOpAdaptor(PadOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = PadOpAdaptor; + template + using GenericAdaptor = PadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("edge_padding_high"), ::llvm::StringRef("edge_padding_low"), ::llvm::StringRef("interior_padding")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEdgePaddingHighAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEdgePaddingHighAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getEdgePaddingLowAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getEdgePaddingLowAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getInteriorPaddingAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getInteriorPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.pad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getPaddingValue(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getPaddingValueMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getEdgePaddingLowAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingLow(); + ::mlir::DenseIntElementsAttr getEdgePaddingHighAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingHigh(); + ::mlir::DenseIntElementsAttr getInteriorPaddingAttr(); + ::mlir::DenseIntElementsAttr getInteriorPadding(); + void setEdgePaddingLowAttr(::mlir::DenseIntElementsAttr attr); + void setEdgePaddingHighAttr(::mlir::DenseIntElementsAttr attr); + void setInteriorPaddingAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::DenseIntElementsAttr edge_padding_low, ::mlir::DenseIntElementsAttr edge_padding_high, ::mlir::DenseIntElementsAttr interior_padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::DenseIntElementsAttr edge_padding_low, ::mlir::DenseIntElementsAttr edge_padding_high, ::mlir::DenseIntElementsAttr interior_padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::DenseIntElementsAttr edge_padding_low, ::mlir::DenseIntElementsAttr edge_padding_high, ::mlir::DenseIntElementsAttr interior_padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::PadOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::PartitionIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PartitionIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PartitionIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PartitionIdOpGenericAdaptorBase(PartitionIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PartitionIdOpGenericAdaptor : public detail::PartitionIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PartitionIdOpGenericAdaptorBase; +public: + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PartitionIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PartitionIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PartitionIdOpAdaptor : public PartitionIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using PartitionIdOpGenericAdaptor::PartitionIdOpGenericAdaptor; + PartitionIdOpAdaptor(PartitionIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PartitionIdOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = PartitionIdOpAdaptor; + template + using GenericAdaptor = PartitionIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.partition_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::PartitionIdOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::PopulationCountOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PopulationCountOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PopulationCountOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PopulationCountOpGenericAdaptorBase(PopulationCountOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PopulationCountOpGenericAdaptor : public detail::PopulationCountOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PopulationCountOpGenericAdaptorBase; +public: + PopulationCountOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PopulationCountOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PopulationCountOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PopulationCountOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PopulationCountOpAdaptor : public PopulationCountOpGenericAdaptor<::mlir::ValueRange> { +public: + using PopulationCountOpGenericAdaptor::PopulationCountOpGenericAdaptor; + PopulationCountOpAdaptor(PopulationCountOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PopulationCountOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = PopulationCountOpAdaptor; + template + using GenericAdaptor = PopulationCountOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.popcnt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::PopulationCountOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::PowOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PowOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PowOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PowOpGenericAdaptorBase(PowOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PowOpGenericAdaptor : public detail::PowOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PowOpGenericAdaptorBase; +public: + PowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PowOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PowOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PowOpAdaptor : public PowOpGenericAdaptor<::mlir::ValueRange> { +public: + using PowOpGenericAdaptor::PowOpGenericAdaptor; + PowOpAdaptor(PowOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PowOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = PowOpAdaptor; + template + using GenericAdaptor = PowOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.power"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::PowOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RealDynamicSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RealDynamicSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RealDynamicSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RealDynamicSliceOpGenericAdaptorBase(RealDynamicSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RealDynamicSliceOpGenericAdaptor : public detail::RealDynamicSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RealDynamicSliceOpGenericAdaptorBase; +public: + RealDynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RealDynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RealDynamicSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RealDynamicSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getLimitIndices() { + return (*getODSOperands(2).begin()); + } + + ValueT getStrides() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RealDynamicSliceOpAdaptor : public RealDynamicSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using RealDynamicSliceOpGenericAdaptor::RealDynamicSliceOpGenericAdaptor; + RealDynamicSliceOpAdaptor(RealDynamicSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RealDynamicSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<4>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = RealDynamicSliceOpAdaptor; + template + using GenericAdaptor = RealDynamicSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.real_dynamic_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::RankedTensorType> getStartIndices(); + ::mlir::TypedValue<::mlir::RankedTensorType> getLimitIndices(); + ::mlir::TypedValue<::mlir::RankedTensorType> getStrides(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + ::mlir::OpOperand &getLimitIndicesMutable(); + ::mlir::OpOperand &getStridesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value limit_indices, ::mlir::Value strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value limit_indices, ::mlir::Value strides); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RealDynamicSliceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RealOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RealOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RealOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RealOpGenericAdaptorBase(RealOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RealOpGenericAdaptor : public detail::RealOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RealOpGenericAdaptorBase; +public: + RealOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RealOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RealOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RealOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RealOpAdaptor : public RealOpGenericAdaptor<::mlir::ValueRange> { +public: + using RealOpGenericAdaptor::RealOpGenericAdaptor; + RealOpAdaptor(RealOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RealOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = RealOpAdaptor; + template + using GenericAdaptor = RealOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.real"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RealOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RecvOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RecvOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RecvOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RecvOpGenericAdaptorBase(RecvOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); +}; +} // namespace detail +template +class RecvOpGenericAdaptor : public detail::RecvOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RecvOpGenericAdaptorBase; +public: + RecvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RecvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RecvOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RecvOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RecvOpAdaptor : public RecvOpGenericAdaptor<::mlir::ValueRange> { +public: + using RecvOpGenericAdaptor::RecvOpGenericAdaptor; + RecvOpAdaptor(RecvOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RecvOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = RecvOpAdaptor; + template + using GenericAdaptor = RecvOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.recv"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + ::mlir::Attribute removeIsHostTransferAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RecvOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReduceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceOpGenericAdaptorBase(ReduceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceOpGenericAdaptor : public detail::ReduceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceOpGenericAdaptorBase; +public: + ReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getInitValues() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceOpAdaptor : public ReduceOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceOpGenericAdaptor::ReduceOpGenericAdaptor; + ReduceOpAdaptor(ReduceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceOpAdaptor; + template + using GenericAdaptor = ReduceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reduce"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getInitValues(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getInitValuesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getBody(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReduceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReducePrecisionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReducePrecisionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReducePrecisionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReducePrecisionOpGenericAdaptorBase(ReducePrecisionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getExponentBitsAttr(); + uint32_t getExponentBits(); + ::mlir::IntegerAttr getMantissaBitsAttr(); + uint32_t getMantissaBits(); +}; +} // namespace detail +template +class ReducePrecisionOpGenericAdaptor : public detail::ReducePrecisionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReducePrecisionOpGenericAdaptorBase; +public: + ReducePrecisionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReducePrecisionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReducePrecisionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReducePrecisionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReducePrecisionOpAdaptor : public ReducePrecisionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReducePrecisionOpGenericAdaptor::ReducePrecisionOpGenericAdaptor; + ReducePrecisionOpAdaptor(ReducePrecisionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReducePrecisionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReducePrecisionOpAdaptor; + template + using GenericAdaptor = ReducePrecisionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("exponent_bits"), ::llvm::StringRef("mantissa_bits")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getExponentBitsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getExponentBitsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getMantissaBitsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getMantissaBitsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reduce_precision"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOutput(); + ::mlir::IntegerAttr getExponentBitsAttr(); + uint32_t getExponentBits(); + ::mlir::IntegerAttr getMantissaBitsAttr(); + uint32_t getMantissaBits(); + void setExponentBitsAttr(::mlir::IntegerAttr attr); + void setExponentBits(uint32_t attrValue); + void setMantissaBitsAttr(::mlir::IntegerAttr attr); + void setMantissaBits(uint32_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::Value operand, ::mlir::IntegerAttr exponent_bits, ::mlir::IntegerAttr mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::IntegerAttr exponent_bits, ::mlir::IntegerAttr mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr exponent_bits, ::mlir::IntegerAttr mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output, ::mlir::Value operand, uint32_t exponent_bits, uint32_t mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, uint32_t exponent_bits, uint32_t mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint32_t exponent_bits, uint32_t mantissa_bits); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReducePrecisionOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReduceScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceScatterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceScatterOpGenericAdaptorBase(ReduceScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceScatterOpGenericAdaptor : public detail::ReduceScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceScatterOpGenericAdaptorBase; +public: + ReduceScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceScatterOpAdaptor : public ReduceScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceScatterOpGenericAdaptor::ReduceScatterOpGenericAdaptor; + ReduceScatterOpAdaptor(ReduceScatterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::SameOperandsAndResultElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceScatterOpAdaptor; + template + using GenericAdaptor = ReduceScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("scatter_dimension"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getScatterDimensionAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getScatterDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reduce_scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComputation(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelHandle(); + ::mlir::UnitAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + void setScatterDimensionAttr(::mlir::IntegerAttr attr); + void setScatterDimension(uint64_t attrValue); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::UnitAttr attr); + void setUseGlobalDeviceIds(bool attrValue); + ::mlir::Attribute removeChannelHandleAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result_type, ::mlir::Value operand, ::mlir::IntegerAttr scatter_dimension, ::mlir::DenseIntElementsAttr replica_groups, ::mlir::mhlo::ChannelHandleAttr channel_handle); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::IntegerAttr scatter_dimension, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr scatter_dimension, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::UnitAttr use_global_device_ids); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, uint64_t scatter_dimension, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint64_t scatter_dimension, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool use_global_device_ids = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 4 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReduceScatterOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReduceWindowOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceWindowOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceWindowOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceWindowOpGenericAdaptorBase(ReduceWindowOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::mlir::DenseIntElementsAttr getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getBaseDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBaseDilations(); + ::mlir::DenseIntElementsAttr getWindowDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDilations(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceWindowOpGenericAdaptor : public detail::ReduceWindowOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceWindowOpGenericAdaptorBase; +public: + ReduceWindowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceWindowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceWindowOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceWindowOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getInitValues() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceWindowOpAdaptor : public ReduceWindowOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceWindowOpGenericAdaptor::ReduceWindowOpGenericAdaptor; + ReduceWindowOpAdaptor(ReduceWindowOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceWindowOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceWindowOpAdaptor; + template + using GenericAdaptor = ReduceWindowOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("base_dilations"), ::llvm::StringRef("padding"), ::llvm::StringRef("window_dilations"), ::llvm::StringRef("window_dimensions"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBaseDilationsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBaseDilationsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getWindowDilationsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getWindowDilationsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getWindowDimensionsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getWindowDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reduce_window"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getInitValues(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getInitValuesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getBody(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::mlir::DenseIntElementsAttr getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getBaseDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBaseDilations(); + ::mlir::DenseIntElementsAttr getWindowDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDilations(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + void setWindowDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setBaseDilationsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowDilationsAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removeBaseDilationsAttr(); + ::mlir::Attribute removeWindowDilationsAttr(); + ::mlir::Attribute removePaddingAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Type result_type, Value operand, Value init_value, DenseIntElementsAttr window_dimensions, DenseIntElementsAttr window_strides, DenseIntElementsAttr base_dilations, DenseIntElementsAttr window_dilations, DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ValueRange operands, ValueRange init_values, DenseIntElementsAttr window_dimensions, DenseIntElementsAttr window_strides, DenseIntElementsAttr base_dilations, DenseIntElementsAttr window_dilations, DenseIntElementsAttr padding, function_ref bodyBuilder); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr base_dilations, /*optional*/::mlir::DenseIntElementsAttr window_dilations, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr base_dilations, /*optional*/::mlir::DenseIntElementsAttr window_dilations, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + ::mlir::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 5 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Get the operation used for reduction applied to `result_index`th result. + Operation *getReductionOp(int result_index); + + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReduceWindowOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RemOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RemOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RemOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RemOpGenericAdaptorBase(RemOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RemOpGenericAdaptor : public detail::RemOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RemOpGenericAdaptorBase; +public: + RemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RemOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RemOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RemOpAdaptor : public RemOpGenericAdaptor<::mlir::ValueRange> { +public: + using RemOpGenericAdaptor::RemOpGenericAdaptor; + RemOpAdaptor(RemOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RemOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = RemOpAdaptor; + template + using GenericAdaptor = RemOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.remainder"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RemOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReplicaIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReplicaIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReplicaIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReplicaIdOpGenericAdaptorBase(ReplicaIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReplicaIdOpGenericAdaptor : public detail::ReplicaIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReplicaIdOpGenericAdaptorBase; +public: + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReplicaIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReplicaIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReplicaIdOpAdaptor : public ReplicaIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReplicaIdOpGenericAdaptor::ReplicaIdOpGenericAdaptor; + ReplicaIdOpAdaptor(ReplicaIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReplicaIdOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReplicaIdOpAdaptor; + template + using GenericAdaptor = ReplicaIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.replica_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReplicaIdOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReshapeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReshapeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReshapeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReshapeOpGenericAdaptorBase(ReshapeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReshapeOpGenericAdaptor : public detail::ReshapeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReshapeOpGenericAdaptorBase; +public: + ReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReshapeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReshapeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReshapeOpAdaptor : public ReshapeOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReshapeOpGenericAdaptor::ReshapeOpGenericAdaptor; + ReshapeOpAdaptor(ReshapeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReshapeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReshapeOpAdaptor; + template + using GenericAdaptor = ReshapeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reshape"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReshapeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReturnOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReturnOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReturnOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReturnOpGenericAdaptorBase(ReturnOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReturnOpGenericAdaptor : public detail::ReturnOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReturnOpGenericAdaptorBase; +public: + ReturnOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReturnOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReturnOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReturnOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getResults() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReturnOpAdaptor : public ReturnOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReturnOpGenericAdaptor::ReturnOpGenericAdaptor; + ReturnOpAdaptor(ReturnOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReturnOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReturnOpAdaptor; + template + using GenericAdaptor = ReturnOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.return"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getResults(); + ::mlir::MutableOperandRange getResultsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange results); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReturnOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ReverseOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReverseOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReverseOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReverseOpGenericAdaptorBase(ReverseOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); +}; +} // namespace detail +template +class ReverseOpGenericAdaptor : public detail::ReverseOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReverseOpGenericAdaptorBase; +public: + ReverseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReverseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReverseOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReverseOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReverseOpAdaptor : public ReverseOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReverseOpGenericAdaptor::ReverseOpGenericAdaptor; + ReverseOpAdaptor(ReverseOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReverseOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReverseOpAdaptor; + template + using GenericAdaptor = ReverseOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.reverse"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ReverseOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RngBitGeneratorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RngBitGeneratorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RngBitGeneratorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RngBitGeneratorOpGenericAdaptorBase(RngBitGeneratorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::RngAlgorithmAttr getRngAlgorithmAttr(); + ::mlir::mhlo::RngAlgorithm getRngAlgorithm(); +}; +} // namespace detail +template +class RngBitGeneratorOpGenericAdaptor : public detail::RngBitGeneratorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RngBitGeneratorOpGenericAdaptorBase; +public: + RngBitGeneratorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RngBitGeneratorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RngBitGeneratorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RngBitGeneratorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInitialState() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RngBitGeneratorOpAdaptor : public RngBitGeneratorOpGenericAdaptor<::mlir::ValueRange> { +public: + using RngBitGeneratorOpGenericAdaptor::RngBitGeneratorOpGenericAdaptor; + RngBitGeneratorOpAdaptor(RngBitGeneratorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RngBitGeneratorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = RngBitGeneratorOpAdaptor; + template + using GenericAdaptor = RngBitGeneratorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("rng_algorithm")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getRngAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getRngAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.rng_bit_generator"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getInitialState(); + ::mlir::OpOperand &getInitialStateMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOutputState(); + ::mlir::TypedValue<::mlir::RankedTensorType> getOutput(); + ::mlir::mhlo::RngAlgorithmAttr getRngAlgorithmAttr(); + ::mlir::mhlo::RngAlgorithm getRngAlgorithm(); + void setRngAlgorithmAttr(::mlir::mhlo::RngAlgorithmAttr attr); + void setRngAlgorithm(::mlir::mhlo::RngAlgorithm attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output_state, ::mlir::Type output, ::mlir::mhlo::RngAlgorithmAttr rng_algorithm, ::mlir::Value initial_state); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::mhlo::RngAlgorithmAttr rng_algorithm, ::mlir::Value initial_state); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type output_state, ::mlir::Type output, ::mlir::mhlo::RngAlgorithm rng_algorithm, ::mlir::Value initial_state); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::mhlo::RngAlgorithm rng_algorithm, ::mlir::Value initial_state); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RngBitGeneratorOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RngOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RngOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RngOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RngOpGenericAdaptorBase(RngOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::RngDistributionAttr getRngDistributionAttr(); + ::mlir::mhlo::RngDistribution getRngDistribution(); +}; +} // namespace detail +template +class RngOpGenericAdaptor : public detail::RngOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RngOpGenericAdaptorBase; +public: + RngOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RngOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RngOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RngOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getShape() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RngOpAdaptor : public RngOpGenericAdaptor<::mlir::ValueRange> { +public: + using RngOpGenericAdaptor::RngOpGenericAdaptor; + RngOpAdaptor(RngOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RngOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = RngOpAdaptor; + template + using GenericAdaptor = RngOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("rng_distribution")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getRngDistributionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getRngDistributionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.rng"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::RankedTensorType> getA(); + ::mlir::TypedValue<::mlir::RankedTensorType> getB(); + ::mlir::TypedValue<::mlir::RankedTensorType> getShape(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getShapeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + ::mlir::mhlo::RngDistributionAttr getRngDistributionAttr(); + ::mlir::mhlo::RngDistribution getRngDistribution(); + void setRngDistributionAttr(::mlir::mhlo::RngDistributionAttr attr); + void setRngDistribution(::mlir::mhlo::RngDistribution attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistributionAttr rng_distribution); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistributionAttr rng_distribution); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistributionAttr rng_distribution); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistribution rng_distribution); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistribution rng_distribution); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value shape, ::mlir::mhlo::RngDistribution rng_distribution); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RngOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RoundNearestEvenOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RoundNearestEvenOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RoundNearestEvenOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RoundNearestEvenOpGenericAdaptorBase(RoundNearestEvenOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RoundNearestEvenOpGenericAdaptor : public detail::RoundNearestEvenOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RoundNearestEvenOpGenericAdaptorBase; +public: + RoundNearestEvenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RoundNearestEvenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RoundNearestEvenOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RoundNearestEvenOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RoundNearestEvenOpAdaptor : public RoundNearestEvenOpGenericAdaptor<::mlir::ValueRange> { +public: + using RoundNearestEvenOpGenericAdaptor::RoundNearestEvenOpGenericAdaptor; + RoundNearestEvenOpAdaptor(RoundNearestEvenOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RoundNearestEvenOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = RoundNearestEvenOpAdaptor; + template + using GenericAdaptor = RoundNearestEvenOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.round_nearest_even"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RoundNearestEvenOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RoundOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RoundOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RoundOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RoundOpGenericAdaptorBase(RoundOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RoundOpGenericAdaptor : public detail::RoundOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RoundOpGenericAdaptorBase; +public: + RoundOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RoundOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RoundOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RoundOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RoundOpAdaptor : public RoundOpGenericAdaptor<::mlir::ValueRange> { +public: + using RoundOpGenericAdaptor::RoundOpGenericAdaptor; + RoundOpAdaptor(RoundOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RoundOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = RoundOpAdaptor; + template + using GenericAdaptor = RoundOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.round_nearest_afz"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RoundOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::RsqrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RsqrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RsqrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RsqrtOpGenericAdaptorBase(RsqrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RsqrtOpGenericAdaptor : public detail::RsqrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RsqrtOpGenericAdaptorBase; +public: + RsqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RsqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RsqrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RsqrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RsqrtOpAdaptor : public RsqrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using RsqrtOpGenericAdaptor::RsqrtOpGenericAdaptor; + RsqrtOpAdaptor(RsqrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RsqrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = RsqrtOpAdaptor; + template + using GenericAdaptor = RsqrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.rsqrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::RsqrtOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScatterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ScatterOpGenericAdaptorBase(ScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbersAttr(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + ::mlir::BoolAttr getUniqueIndicesAttr(); + bool getUniqueIndices(); + ::mlir::Region &getUpdateComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ScatterOpGenericAdaptor : public detail::ScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScatterOpGenericAdaptorBase; +public: + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + ValueT getScatterIndices() { + return (*getODSOperands(1).begin()); + } + + RangeT getUpdates() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScatterOpAdaptor : public ScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScatterOpGenericAdaptor::ScatterOpGenericAdaptor; + ScatterOpAdaptor(ScatterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScatterOpAdaptor; + template + using GenericAdaptor = ScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("indices_are_sorted"), ::llvm::StringRef("scatter_dimension_numbers"), ::llvm::StringRef("unique_indices")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIndicesAreSortedAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIndicesAreSortedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getScatterDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getScatterDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getUniqueIndicesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getUniqueIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::TypedValue<::mlir::TensorType> getScatterIndices(); + ::mlir::Operation::operand_range getUpdates(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::OpOperand &getScatterIndicesMutable(); + ::mlir::MutableOperandRange getUpdatesMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getUpdateComputation(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbersAttr(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + ::mlir::BoolAttr getUniqueIndicesAttr(); + bool getUniqueIndices(); + void setScatterDimensionNumbersAttr(::mlir::mhlo::ScatterDimensionNumbersAttr attr); + void setIndicesAreSortedAttr(::mlir::BoolAttr attr); + void setIndicesAreSorted(::std::optional attrValue); + void setUniqueIndicesAttr(::mlir::BoolAttr attr); + void setUniqueIndices(::std::optional attrValue); + ::mlir::Attribute removeIndicesAreSortedAttr(); + ::mlir::Attribute removeUniqueIndicesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::mlir::Value scatter_indices, ::mlir::ValueRange updates, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted, /*optional*/::mlir::BoolAttr unique_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value scatter_indices, ::mlir::ValueRange updates, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted, /*optional*/::mlir::BoolAttr unique_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, ::mlir::Value scatter_indices, ::mlir::ValueRange updates, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/bool indices_are_sorted = false, /*optional*/bool unique_indices = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value scatter_indices, ::mlir::ValueRange updates, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/bool indices_are_sorted = false, /*optional*/bool unique_indices = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ScatterOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SelectAndScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SelectAndScatterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SelectAndScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SelectAndScatterOpGenericAdaptorBase(SelectAndScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::Region &getSelect(); + ::mlir::Region &getScatter(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class SelectAndScatterOpGenericAdaptor : public detail::SelectAndScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SelectAndScatterOpGenericAdaptorBase; +public: + SelectAndScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SelectAndScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SelectAndScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SelectAndScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getSource() { + return (*getODSOperands(1).begin()); + } + + ValueT getInitValue() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SelectAndScatterOpAdaptor : public SelectAndScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using SelectAndScatterOpGenericAdaptor::SelectAndScatterOpGenericAdaptor; + SelectAndScatterOpAdaptor(SelectAndScatterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SelectAndScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OneResult, ::mlir::OpTrait::OneTypedResult<::mlir::TensorType>::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SelectAndScatterOpAdaptor; + template + using GenericAdaptor = SelectAndScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("padding"), ::llvm::StringRef("window_dimensions"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getWindowDimensionsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getWindowDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.select_and_scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getSource(); + ::mlir::TypedValue<::mlir::TensorType> getInitValue(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getSourceMutable(); + ::mlir::OpOperand &getInitValueMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getSelect(); + ::mlir::Region &getScatter(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + void setWindowDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeWindowDimensionsAttr(); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value source, ::mlir::Value init_value, /*optional*/::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value source, ::mlir::Value init_value, /*optional*/::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value source, ::mlir::Value init_value, /*optional*/::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SelectAndScatterOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SelectOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SelectOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SelectOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SelectOpGenericAdaptorBase(SelectOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SelectOpGenericAdaptor : public detail::SelectOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SelectOpGenericAdaptorBase; +public: + SelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SelectOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SelectOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getPred() { + return (*getODSOperands(0).begin()); + } + + ValueT getOnTrue() { + return (*getODSOperands(1).begin()); + } + + ValueT getOnFalse() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SelectOpAdaptor : public SelectOpGenericAdaptor<::mlir::ValueRange> { +public: + using SelectOpGenericAdaptor::SelectOpGenericAdaptor; + SelectOpAdaptor(SelectOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SelectOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::hlo::OpTrait::BroadcastingElementwise, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = SelectOpAdaptor; + template + using GenericAdaptor = SelectOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.select"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getPred(); + ::mlir::TypedValue<::mlir::TensorType> getOnTrue(); + ::mlir::TypedValue<::mlir::TensorType> getOnFalse(); + ::mlir::OpOperand &getPredMutable(); + ::mlir::OpOperand &getOnTrueMutable(); + ::mlir::OpOperand &getOnFalseMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value pred, ::mlir::Value on_true, ::mlir::Value on_false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value pred, ::mlir::Value on_true, ::mlir::Value on_false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value pred, ::mlir::Value on_true, ::mlir::Value on_false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SelectOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SendOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SendOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SendOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SendOpGenericAdaptorBase(SendOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); +}; +} // namespace detail +template +class SendOpGenericAdaptor : public detail::SendOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SendOpGenericAdaptorBase; +public: + SendOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SendOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SendOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SendOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + ValueT getToken() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SendOpAdaptor : public SendOpGenericAdaptor<::mlir::ValueRange> { +public: + using SendOpGenericAdaptor::SendOpGenericAdaptor; + SendOpAdaptor(SendOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SendOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SendOpAdaptor; + template + using GenericAdaptor = SendOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.send"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Value getToken(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + ::mlir::Attribute removeIsHostTransferAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SendOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SetDimensionSizeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SetDimensionSizeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SetDimensionSizeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SetDimensionSizeOpGenericAdaptorBase(SetDimensionSizeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); +}; +} // namespace detail +template +class SetDimensionSizeOpGenericAdaptor : public detail::SetDimensionSizeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SetDimensionSizeOpGenericAdaptorBase; +public: + SetDimensionSizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SetDimensionSizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SetDimensionSizeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SetDimensionSizeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getSize() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SetDimensionSizeOpAdaptor : public SetDimensionSizeOpGenericAdaptor<::mlir::ValueRange> { +public: + using SetDimensionSizeOpGenericAdaptor::SetDimensionSizeOpGenericAdaptor; + SetDimensionSizeOpAdaptor(SetDimensionSizeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SetDimensionSizeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = SetDimensionSizeOpAdaptor; + template + using GenericAdaptor = SetDimensionSizeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.set_dimension_size"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getSize(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getSizeMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value size, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value size, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value size, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value size, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value size, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value size, uint64_t dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SetDimensionSizeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ShiftLeftOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftLeftOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftLeftOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftLeftOpGenericAdaptorBase(ShiftLeftOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ShiftLeftOpGenericAdaptor : public detail::ShiftLeftOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftLeftOpGenericAdaptorBase; +public: + ShiftLeftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftLeftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftLeftOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftLeftOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftLeftOpAdaptor : public ShiftLeftOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftLeftOpGenericAdaptor::ShiftLeftOpGenericAdaptor; + ShiftLeftOpAdaptor(ShiftLeftOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftLeftOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftLeftOpAdaptor; + template + using GenericAdaptor = ShiftLeftOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.shift_left"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ShiftLeftOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ShiftRightArithmeticOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftRightArithmeticOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftRightArithmeticOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftRightArithmeticOpGenericAdaptorBase(ShiftRightArithmeticOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ShiftRightArithmeticOpGenericAdaptor : public detail::ShiftRightArithmeticOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftRightArithmeticOpGenericAdaptorBase; +public: + ShiftRightArithmeticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftRightArithmeticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftRightArithmeticOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftRightArithmeticOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftRightArithmeticOpAdaptor : public ShiftRightArithmeticOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftRightArithmeticOpGenericAdaptor::ShiftRightArithmeticOpGenericAdaptor; + ShiftRightArithmeticOpAdaptor(ShiftRightArithmeticOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftRightArithmeticOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftRightArithmeticOpAdaptor; + template + using GenericAdaptor = ShiftRightArithmeticOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.shift_right_arithmetic"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ShiftRightArithmeticOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::ShiftRightLogicalOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftRightLogicalOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftRightLogicalOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftRightLogicalOpGenericAdaptorBase(ShiftRightLogicalOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ShiftRightLogicalOpGenericAdaptor : public detail::ShiftRightLogicalOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftRightLogicalOpGenericAdaptorBase; +public: + ShiftRightLogicalOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftRightLogicalOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftRightLogicalOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftRightLogicalOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftRightLogicalOpAdaptor : public ShiftRightLogicalOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftRightLogicalOpGenericAdaptor::ShiftRightLogicalOpGenericAdaptor; + ShiftRightLogicalOpAdaptor(ShiftRightLogicalOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftRightLogicalOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftRightLogicalOpAdaptor; + template + using GenericAdaptor = ShiftRightLogicalOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.shift_right_logical"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::ShiftRightLogicalOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SignOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SignOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SignOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SignOpGenericAdaptorBase(SignOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SignOpGenericAdaptor : public detail::SignOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SignOpGenericAdaptorBase; +public: + SignOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SignOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SignOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SignOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SignOpAdaptor : public SignOpGenericAdaptor<::mlir::ValueRange> { +public: + using SignOpGenericAdaptor::SignOpGenericAdaptor; + SignOpAdaptor(SignOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SignOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = SignOpAdaptor; + template + using GenericAdaptor = SignOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.sign"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SignOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SineOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SineOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SineOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SineOpGenericAdaptorBase(SineOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SineOpGenericAdaptor : public detail::SineOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SineOpGenericAdaptorBase; +public: + SineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SineOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SineOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SineOpAdaptor : public SineOpGenericAdaptor<::mlir::ValueRange> { +public: + using SineOpGenericAdaptor::SineOpGenericAdaptor; + SineOpAdaptor(SineOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SineOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = SineOpAdaptor; + template + using GenericAdaptor = SineOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.sine"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SineOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SliceOpGenericAdaptorBase(SliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getStartIndicesAttr(); + ::mlir::DenseIntElementsAttr getStartIndices(); + ::mlir::DenseIntElementsAttr getLimitIndicesAttr(); + ::mlir::DenseIntElementsAttr getLimitIndices(); + ::mlir::DenseIntElementsAttr getStridesAttr(); + ::mlir::DenseIntElementsAttr getStrides(); +}; +} // namespace detail +template +class SliceOpGenericAdaptor : public detail::SliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SliceOpGenericAdaptorBase; +public: + SliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SliceOpAdaptor : public SliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using SliceOpGenericAdaptor::SliceOpGenericAdaptor; + SliceOpAdaptor(SliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SliceOpAdaptor; + template + using GenericAdaptor = SliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("limit_indices"), ::llvm::StringRef("start_indices"), ::llvm::StringRef("strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLimitIndicesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLimitIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getStartIndicesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getStartIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getStridesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getStartIndicesAttr(); + ::mlir::DenseIntElementsAttr getStartIndices(); + ::mlir::DenseIntElementsAttr getLimitIndicesAttr(); + ::mlir::DenseIntElementsAttr getLimitIndices(); + ::mlir::DenseIntElementsAttr getStridesAttr(); + ::mlir::DenseIntElementsAttr getStrides(); + void setStartIndicesAttr(::mlir::DenseIntElementsAttr attr); + void setLimitIndicesAttr(::mlir::DenseIntElementsAttr attr); + void setStridesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr start_indices, ::mlir::DenseIntElementsAttr limit_indices, ::mlir::DenseIntElementsAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr start_indices, ::mlir::DenseIntElementsAttr limit_indices, ::mlir::DenseIntElementsAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr start_indices, ::mlir::DenseIntElementsAttr limit_indices, ::mlir::DenseIntElementsAttr strides); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SliceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SortOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SortOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SortOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SortOpGenericAdaptorBase(SortOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + ::mlir::BoolAttr getIsStableAttr(); + bool getIsStable(); + ::mlir::Region &getComparator(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class SortOpGenericAdaptor : public detail::SortOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SortOpGenericAdaptorBase; +public: + SortOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SortOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SortOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SortOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SortOpAdaptor : public SortOpGenericAdaptor<::mlir::ValueRange> { +public: + using SortOpGenericAdaptor::SortOpGenericAdaptor; + SortOpAdaptor(SortOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SortOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = SortOpAdaptor; + template + using GenericAdaptor = SortOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension"), ::llvm::StringRef("is_stable")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsStableAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsStableAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.sort"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComparator(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + ::mlir::BoolAttr getIsStableAttr(); + bool getIsStable(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(::std::optional attrValue); + void setIsStableAttr(::mlir::BoolAttr attr); + void setIsStable(::std::optional attrValue); + ::mlir::Attribute removeDimensionAttr(); + ::mlir::Attribute removeIsStableAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ValueRange inputs, int64_t dimension = -1, bool is_stable = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, /*optional*/::mlir::IntegerAttr dimension, /*optional*/::mlir::BoolAttr is_stable); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, /*optional*/::mlir::IntegerAttr dimension, /*optional*/::mlir::BoolAttr is_stable); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultType0, ::mlir::ValueRange inputs, /*optional*/uint64_t dimension = -1, /*optional*/bool is_stable = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, /*optional*/uint64_t dimension = -1, /*optional*/bool is_stable = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SortOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SqrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SqrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SqrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SqrtOpGenericAdaptorBase(SqrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SqrtOpGenericAdaptor : public detail::SqrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SqrtOpGenericAdaptorBase; +public: + SqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SqrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SqrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SqrtOpAdaptor : public SqrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using SqrtOpGenericAdaptor::SqrtOpGenericAdaptor; + SqrtOpAdaptor(SqrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SqrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = SqrtOpAdaptor; + template + using GenericAdaptor = SqrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.sqrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SqrtOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::StochasticConvertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class StochasticConvertOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + StochasticConvertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + StochasticConvertOpGenericAdaptorBase(StochasticConvertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class StochasticConvertOpGenericAdaptor : public detail::StochasticConvertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::StochasticConvertOpGenericAdaptorBase; +public: + StochasticConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + StochasticConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : StochasticConvertOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + StochasticConvertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getRandom() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class StochasticConvertOpAdaptor : public StochasticConvertOpGenericAdaptor<::mlir::ValueRange> { +public: + using StochasticConvertOpGenericAdaptor::StochasticConvertOpGenericAdaptor; + StochasticConvertOpAdaptor(StochasticConvertOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class StochasticConvertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = StochasticConvertOpAdaptor; + template + using GenericAdaptor = StochasticConvertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.stochastic_convert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getRandom(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getRandomMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand, ::mlir::Value random); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value random); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::StochasticConvertOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::SubtractOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SubtractOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SubtractOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SubtractOpGenericAdaptorBase(SubtractOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SubtractOpGenericAdaptor : public detail::SubtractOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SubtractOpGenericAdaptorBase; +public: + SubtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SubtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SubtractOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SubtractOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SubtractOpAdaptor : public SubtractOpGenericAdaptor<::mlir::ValueRange> { +public: + using SubtractOpGenericAdaptor::SubtractOpGenericAdaptor; + SubtractOpAdaptor(SubtractOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SubtractOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SubtractOpAdaptor; + template + using GenericAdaptor = SubtractOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.subtract"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::SubtractOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TanOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TanOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TanOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TanOpGenericAdaptorBase(TanOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TanOpGenericAdaptor : public detail::TanOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TanOpGenericAdaptorBase; +public: + TanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TanOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TanOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TanOpAdaptor : public TanOpGenericAdaptor<::mlir::ValueRange> { +public: + using TanOpGenericAdaptor::TanOpGenericAdaptor; + TanOpAdaptor(TanOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TanOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = TanOpAdaptor; + template + using GenericAdaptor = TanOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.tan"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TanOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TanhOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TanhOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TanhOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TanhOpGenericAdaptorBase(TanhOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TanhOpGenericAdaptor : public detail::TanhOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TanhOpGenericAdaptorBase; +public: + TanhOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TanhOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TanhOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TanhOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TanhOpAdaptor : public TanhOpGenericAdaptor<::mlir::ValueRange> { +public: + using TanhOpGenericAdaptor::TanhOpGenericAdaptor; + TanhOpAdaptor(TanhOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TanhOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = TanhOpAdaptor; + template + using GenericAdaptor = TanhOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.tanh"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TanhOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TopKOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TopKOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TopKOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TopKOpGenericAdaptorBase(TopKOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getKAttr(); + uint64_t getK(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class TopKOpGenericAdaptor : public detail::TopKOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TopKOpGenericAdaptorBase; +public: + TopKOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TopKOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TopKOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TopKOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TopKOpAdaptor : public TopKOpGenericAdaptor<::mlir::ValueRange> { +public: + using TopKOpGenericAdaptor::TopKOpGenericAdaptor; + TopKOpAdaptor(TopKOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TopKOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TopKOpAdaptor; + template + using GenericAdaptor = TopKOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("k")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getKAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getKAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.topk"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getValues(); + ::mlir::TypedValue<::mlir::TensorType> getIndices(); + ::mlir::Region &getBody(); + ::mlir::IntegerAttr getKAttr(); + uint64_t getK(); + void setKAttr(::mlir::IntegerAttr attr); + void setK(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type values, ::mlir::Type indices, ::mlir::Value operand, ::mlir::IntegerAttr k); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::IntegerAttr k); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::IntegerAttr k); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type values, ::mlir::Type indices, ::mlir::Value operand, uint64_t k); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, uint64_t k); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, uint64_t k); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TopKOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TorchIndexSelectOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TorchIndexSelectOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TorchIndexSelectOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TorchIndexSelectOpGenericAdaptorBase(TorchIndexSelectOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimAttr(); + uint64_t getDim(); + ::mlir::IntegerAttr getBatchDimsAttr(); + uint64_t getBatchDims(); +}; +} // namespace detail +template +class TorchIndexSelectOpGenericAdaptor : public detail::TorchIndexSelectOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TorchIndexSelectOpGenericAdaptorBase; +public: + TorchIndexSelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TorchIndexSelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TorchIndexSelectOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TorchIndexSelectOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getIndex() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TorchIndexSelectOpAdaptor : public TorchIndexSelectOpGenericAdaptor<::mlir::ValueRange> { +public: + using TorchIndexSelectOpGenericAdaptor::TorchIndexSelectOpGenericAdaptor; + TorchIndexSelectOpAdaptor(TorchIndexSelectOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TorchIndexSelectOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TorchIndexSelectOpAdaptor; + template + using GenericAdaptor = TorchIndexSelectOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_dims"), ::llvm::StringRef("dim")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchDimsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDimAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDimAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.torch_index_select"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::TypedValue<::mlir::TensorType> getIndex(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getIndexMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDimAttr(); + uint64_t getDim(); + ::mlir::IntegerAttr getBatchDimsAttr(); + uint64_t getBatchDims(); + void setDimAttr(::mlir::IntegerAttr attr); + void setDim(uint64_t attrValue); + void setBatchDimsAttr(::mlir::IntegerAttr attr); + void setBatchDims(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value index, ::mlir::IntegerAttr dim, ::mlir::IntegerAttr batch_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value index, ::mlir::IntegerAttr dim, ::mlir::IntegerAttr batch_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::Value index, uint64_t dim, uint64_t batch_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value index, uint64_t dim, uint64_t batch_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TorchIndexSelectOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TraceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TraceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TraceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TraceOpGenericAdaptorBase(TraceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getTagAttr(); + ::llvm::StringRef getTag(); +}; +} // namespace detail +template +class TraceOpGenericAdaptor : public detail::TraceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TraceOpGenericAdaptorBase; +public: + TraceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TraceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TraceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TraceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TraceOpAdaptor : public TraceOpGenericAdaptor<::mlir::ValueRange> { +public: + using TraceOpGenericAdaptor::TraceOpGenericAdaptor; + TraceOpAdaptor(TraceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TraceOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = TraceOpAdaptor; + template + using GenericAdaptor = TraceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("tag")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getTagAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getTagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.trace"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getTagAttr(); + ::llvm::StringRef getTag(); + void setTagAttr(::mlir::StringAttr attr); + void setTag(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::StringAttr tag); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::StringAttr tag); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::llvm::StringRef tag); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::llvm::StringRef tag); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TraceOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TransposeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TransposeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TransposeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TransposeOpGenericAdaptorBase(TransposeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getPermutationAttr(); + ::mlir::DenseIntElementsAttr getPermutation(); +}; +} // namespace detail +template +class TransposeOpGenericAdaptor : public detail::TransposeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TransposeOpGenericAdaptorBase; +public: + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TransposeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TransposeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TransposeOpAdaptor : public TransposeOpGenericAdaptor<::mlir::ValueRange> { +public: + using TransposeOpGenericAdaptor::TransposeOpGenericAdaptor; + TransposeOpAdaptor(TransposeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TransposeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TransposeOpAdaptor; + template + using GenericAdaptor = TransposeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("permutation")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPermutationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPermutationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.transpose"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getPermutationAttr(); + ::mlir::DenseIntElementsAttr getPermutation(); + void setPermutationAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::DenseIntElementsAttr permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr permutation); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + ::mlir::LogicalResult reifyReturnTypeShapes(::mlir::OpBuilder&builder, ::mlir::ValueRange operands, ::llvm::SmallVectorImpl<::mlir::Value> &reifiedReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TransposeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TriangularSolveOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TriangularSolveOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TriangularSolveOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TriangularSolveOpGenericAdaptorBase(TriangularSolveOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getLeftSideAttr(); + bool getLeftSide(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + ::mlir::BoolAttr getUnitDiagonalAttr(); + bool getUnitDiagonal(); + ::mlir::mhlo::TransposeAttr getTransposeAAttr(); + ::mlir::mhlo::Transpose getTransposeA(); +}; +} // namespace detail +template +class TriangularSolveOpGenericAdaptor : public detail::TriangularSolveOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TriangularSolveOpGenericAdaptorBase; +public: + TriangularSolveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TriangularSolveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TriangularSolveOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TriangularSolveOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TriangularSolveOpAdaptor : public TriangularSolveOpGenericAdaptor<::mlir::ValueRange> { +public: + using TriangularSolveOpGenericAdaptor::TriangularSolveOpGenericAdaptor; + TriangularSolveOpAdaptor(TriangularSolveOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TriangularSolveOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultElementType, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType> { +public: + using Op::Op; + using Op::print; + using Adaptor = TriangularSolveOpAdaptor; + template + using GenericAdaptor = TriangularSolveOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("left_side"), ::llvm::StringRef("lower"), ::llvm::StringRef("transpose_a"), ::llvm::StringRef("unit_diagonal")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLeftSideAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLeftSideAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getLowerAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getTransposeAAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getTransposeAAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getUnitDiagonalAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getUnitDiagonalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.triangular_solve"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getA(); + ::mlir::TypedValue<::mlir::TensorType> getB(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getLeftSideAttr(); + bool getLeftSide(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + ::mlir::BoolAttr getUnitDiagonalAttr(); + bool getUnitDiagonal(); + ::mlir::mhlo::TransposeAttr getTransposeAAttr(); + ::mlir::mhlo::Transpose getTransposeA(); + void setLeftSideAttr(::mlir::BoolAttr attr); + void setLeftSide(bool attrValue); + void setLowerAttr(::mlir::BoolAttr attr); + void setLower(bool attrValue); + void setUnitDiagonalAttr(::mlir::BoolAttr attr); + void setUnitDiagonal(bool attrValue); + void setTransposeAAttr(::mlir::mhlo::TransposeAttr attr); + void setTransposeA(::mlir::mhlo::Transpose attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value a, ::mlir::Value b, ::mlir::BoolAttr left_side, ::mlir::BoolAttr lower, ::mlir::BoolAttr unit_diagonal, ::mlir::mhlo::TransposeAttr transpose_a); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::BoolAttr left_side, ::mlir::BoolAttr lower, ::mlir::BoolAttr unit_diagonal, ::mlir::mhlo::TransposeAttr transpose_a); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::BoolAttr left_side, ::mlir::BoolAttr lower, ::mlir::BoolAttr unit_diagonal, ::mlir::mhlo::TransposeAttr transpose_a); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value a, ::mlir::Value b, bool left_side, bool lower, bool unit_diagonal, ::mlir::mhlo::Transpose transpose_a); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, bool left_side, bool lower, bool unit_diagonal, ::mlir::mhlo::Transpose transpose_a); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, bool left_side, bool lower, bool unit_diagonal, ::mlir::mhlo::Transpose transpose_a); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 4 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TriangularSolveOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::TupleOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TupleOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TupleOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TupleOpGenericAdaptorBase(TupleOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TupleOpGenericAdaptor : public detail::TupleOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TupleOpGenericAdaptorBase; +public: + TupleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TupleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TupleOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TupleOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getVal() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TupleOpAdaptor : public TupleOpGenericAdaptor<::mlir::ValueRange> { +public: + using TupleOpGenericAdaptor::TupleOpGenericAdaptor; + TupleOpAdaptor(TupleOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TupleOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TupleOpAdaptor; + template + using GenericAdaptor = TupleOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.tuple"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getVal(); + ::mlir::MutableOperandRange getValMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::ValueRange val); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::TupleOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::UnaryEinsumOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class UnaryEinsumOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + UnaryEinsumOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + UnaryEinsumOpGenericAdaptorBase(UnaryEinsumOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getEinsumConfigAttr(); + ::llvm::StringRef getEinsumConfig(); +}; +} // namespace detail +template +class UnaryEinsumOpGenericAdaptor : public detail::UnaryEinsumOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::UnaryEinsumOpGenericAdaptorBase; +public: + UnaryEinsumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + UnaryEinsumOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : UnaryEinsumOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + UnaryEinsumOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class UnaryEinsumOpAdaptor : public UnaryEinsumOpGenericAdaptor<::mlir::ValueRange> { +public: + using UnaryEinsumOpGenericAdaptor::UnaryEinsumOpGenericAdaptor; + UnaryEinsumOpAdaptor(UnaryEinsumOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class UnaryEinsumOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = UnaryEinsumOpAdaptor; + template + using GenericAdaptor = UnaryEinsumOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("einsum_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEinsumConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEinsumConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.unary_einsum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getEinsumConfigAttr(); + ::llvm::StringRef getEinsumConfig(); + void setEinsumConfigAttr(::mlir::StringAttr attr); + void setEinsumConfig(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::mlir::StringAttr einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::StringAttr einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value operand, ::llvm::StringRef einsum_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::llvm::StringRef einsum_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::UnaryEinsumOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::UniformDequantizeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class UniformDequantizeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + UniformDequantizeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + UniformDequantizeOpGenericAdaptorBase(UniformDequantizeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class UniformDequantizeOpGenericAdaptor : public detail::UniformDequantizeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::UniformDequantizeOpGenericAdaptorBase; +public: + UniformDequantizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + UniformDequantizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : UniformDequantizeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + UniformDequantizeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class UniformDequantizeOpAdaptor : public UniformDequantizeOpGenericAdaptor<::mlir::ValueRange> { +public: + using UniformDequantizeOpGenericAdaptor::UniformDequantizeOpGenericAdaptor; + UniformDequantizeOpAdaptor(UniformDequantizeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class UniformDequantizeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::InferTensorType, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = UniformDequantizeOpAdaptor; + template + using GenericAdaptor = UniformDequantizeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.uniform_dequantize"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::UniformDequantizeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::UniformQuantizeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class UniformQuantizeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + UniformQuantizeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + UniformQuantizeOpGenericAdaptorBase(UniformQuantizeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class UniformQuantizeOpGenericAdaptor : public detail::UniformQuantizeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::UniformQuantizeOpGenericAdaptorBase; +public: + UniformQuantizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + UniformQuantizeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : UniformQuantizeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + UniformQuantizeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class UniformQuantizeOpAdaptor : public UniformQuantizeOpGenericAdaptor<::mlir::ValueRange> { +public: + using UniformQuantizeOpGenericAdaptor::UniformQuantizeOpGenericAdaptor; + UniformQuantizeOpAdaptor(UniformQuantizeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class UniformQuantizeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::OpTrait::SameOperandsAndResultShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = UniformQuantizeOpAdaptor; + template + using GenericAdaptor = UniformQuantizeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.uniform_quantize"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getOperand(); + ::mlir::OpOperand &getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value operand); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::UniformQuantizeOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::WhileOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class WhileOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + WhileOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + WhileOpGenericAdaptorBase(WhileOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::Region &getCond(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class WhileOpGenericAdaptor : public detail::WhileOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::WhileOpGenericAdaptorBase; +public: + WhileOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + WhileOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : WhileOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + WhileOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperand() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class WhileOpAdaptor : public WhileOpGenericAdaptor<::mlir::ValueRange> { +public: + using WhileOpGenericAdaptor::WhileOpGenericAdaptor; + WhileOpAdaptor(WhileOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class WhileOp : public ::mlir::Op::Impl, ::mlir::OpTrait::VariadicResults, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::SingleBlock, ::mlir::OpTrait::SingleBlockImplicitTerminator::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::HasRecursiveMemoryEffects, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = WhileOpAdaptor; + template + using GenericAdaptor = WhileOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.while"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOperand(); + ::mlir::MutableOperandRange getOperandMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getCond(); + ::mlir::Region &getBody(); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); +public: + // Method of OpAsmOpInterface used during custom printing to name the block + // arguments in the nested regions. We name both the condition and the body + // regions entry arguments the same way, with a `iterArg` prefix. Since the + // two regions are side-by-side they will have the same name, which allows + // us to print them once and share it for the two regions, and still be able + // to parse them back. + void getAsmBlockArgumentNames(Region ®ion, OpAsmSetValueNameFn setNameFn) { + for (BlockArgument arg : region.getArguments()) + setNameFn(arg, "iterArg"); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::WhileOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::XlaRngGetAndUpdateStateOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class XlaRngGetAndUpdateStateOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + XlaRngGetAndUpdateStateOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + XlaRngGetAndUpdateStateOpGenericAdaptorBase(XlaRngGetAndUpdateStateOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDeltaAttr(); + uint64_t getDelta(); +}; +} // namespace detail +template +class XlaRngGetAndUpdateStateOpGenericAdaptor : public detail::XlaRngGetAndUpdateStateOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::XlaRngGetAndUpdateStateOpGenericAdaptorBase; +public: + XlaRngGetAndUpdateStateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + XlaRngGetAndUpdateStateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : XlaRngGetAndUpdateStateOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + XlaRngGetAndUpdateStateOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class XlaRngGetAndUpdateStateOpAdaptor : public XlaRngGetAndUpdateStateOpGenericAdaptor<::mlir::ValueRange> { +public: + using XlaRngGetAndUpdateStateOpGenericAdaptor::XlaRngGetAndUpdateStateOpGenericAdaptor; + XlaRngGetAndUpdateStateOpAdaptor(XlaRngGetAndUpdateStateOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class XlaRngGetAndUpdateStateOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = XlaRngGetAndUpdateStateOpAdaptor; + template + using GenericAdaptor = XlaRngGetAndUpdateStateOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("delta")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDeltaAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDeltaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.xla.rng_get_and_update_state"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDeltaAttr(); + uint64_t getDelta(); + void setDeltaAttr(::mlir::IntegerAttr attr); + void setDelta(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::IntegerAttr delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::IntegerAttr delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::IntegerAttr delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, uint64_t delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, uint64_t delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, uint64_t delta); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + static ::mlir::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + // Relax the strict default implementation with one that allows + // for StableHLO-specific differences. + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::XlaRngGetAndUpdateStateOp) + +namespace mlir { +namespace mhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::mhlo::XorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class XorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + XorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + XorOpGenericAdaptorBase(XorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class XorOpGenericAdaptor : public detail::XorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::XorOpGenericAdaptorBase; +public: + XorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + XorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : XorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + XorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class XorOpAdaptor : public XorOpGenericAdaptor<::mlir::ValueRange> { +public: + using XorOpGenericAdaptor::XorOpGenericAdaptor; + XorOpAdaptor(XorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class XorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::OpTrait::IsCommutative, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::InferShapedTypeOpInterface::Trait, ::mlir::hlo::OpTrait::CompatibleOperandsAndResultType, ::mlir::OpTrait::SameOperandsAndResultShape, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = XorOpAdaptor; + template + using GenericAdaptor = XorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("mhlo.xor"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getLhs(); + ::mlir::TypedValue<::mlir::TensorType> getRhs(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::TypedValue<::mlir::TensorType> getResult(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::LogicalResult inferReturnTypeComponents(::mlir::MLIRContext*context, ::std::optional<::mlir::Location> location, ::mlir::ValueShapeRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::ShapedTypeComponents>&inferredReturnShapes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + LogicalResult reifyReturnTypeShapes( + OpBuilder& builder, ValueRange operands, + SmallVectorImpl& reifiedReturnShapes) { + return ::mlir::hlo::deriveShapeFromOperand(&builder, getOperation(), + operands.front(), + &reifiedReturnShapes); + } + static bool isCompatibleReturnTypes(TypeRange l, TypeRange r) { + return mlir::hlo::isCompatibleForHloTypeInference(l, r); + } +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::XorOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_typedefs_inc_gen/mhlo/IR/hlo_ops_typedefs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_typedefs_inc_gen/mhlo/IR/hlo_ops_typedefs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..ea820363296ca46eff7a03a83c663c9731bcd256 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/hlo_ops_typedefs_inc_gen/mhlo/IR/hlo_ops_typedefs.h.inc @@ -0,0 +1,59 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* TypeDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_TYPEDEF_CLASSES +#undef GET_TYPEDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace mhlo { +class AsyncBundleType; +class AsyncBundleType : public ::mlir::Type::TypeBase { +public: + using Base::Base; + // Return the number of held types. + size_t size() const; + + // Iterate over the held elements. + using iterator = ArrayRef::iterator; + iterator begin() const { return getTypes().begin(); } + iterator end() const { return getTypes().end(); } + + // Return the element type at index 'index'. + Type getType(size_t index) const { + assert(index < size() && "invalid index for tuple type"); + return getTypes()[index]; + } + + // Puts a flattened list of types in this bundle into `types` + void getFlattenedTypes(SmallVectorImpl &types); + static SmallVector getFlattenedTypes(AsyncBundleType t) { + SmallVector fTypes; + t.getFlattenedTypes(fTypes); + return fTypes; + } + + static AsyncBundleType get(::mlir::MLIRContext *context, ::llvm::ArrayRef types); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"async_bundle"}; + } + + static ::mlir::Type parse(::mlir::AsmParser &odsParser); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::llvm::ArrayRef getTypes() const; +}; +} // namespace mhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::mhlo::AsyncBundleType) + +#endif // GET_TYPEDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/legalize_to_linalg_utils/mhlo/utils/legalize_to_linalg_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/legalize_to_linalg_utils/mhlo/utils/legalize_to_linalg_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..218d3c084869d2dad9e624e69389f3428b20c019 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/legalize_to_linalg_utils/mhlo/utils/legalize_to_linalg_utils.h @@ -0,0 +1,189 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file supports the lowering of CHLO/HLO/LHLO dialect to Linalg dialect. + +#ifndef MLIR_HLO_DIALECT_MHLO_TRANSFORMS_LEGALIZE_TO_LINALG_UTILS_H_ +#define MLIR_HLO_DIALECT_MHLO_TRANSFORMS_LEGALIZE_TO_LINALG_UTILS_H_ + +#include +#include +#include +#include +#include + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringSet.h" +#include "mhlo/transforms/map_mhlo_to_scalar_op.h" +#include "mlir/Dialect/Linalg/IR/Linalg.h" +#include "mlir/Dialect/Linalg/Utils/Utils.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/IR/AffineExpr.h" +#include "mlir/IR/Attributes.h" +#include "mlir/IR/Builders.h" +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Location.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/Operation.h" +#include "mlir/IR/OperationSupport.h" +#include "mlir/IR/TypeUtilities.h" +#include "mlir/Support/LLVM.h" +#include "mlir/Support/LogicalResult.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +namespace mhlo { + +/// Returns an ArrayAttr that contains `nLoops` attributes. All the attributes +/// are "parallel" except the last `nReduction` elements, where are "reduction" +/// attributes. +SmallVector getParallelAndReductionIterators( + unsigned nLoops, unsigned nReduction); + +/// Returns an ArrayAttr that contains `nParallelLoops` "parallel" attributes. +SmallVector getNParallelLoopsAttrs( + unsigned nParallelLoops); + +/// Generates an init sparse tensor. +Value getEmptySparseTensor(OpBuilder& b, Location loc, ShapedType type, + ArrayRef dynSizes); + +/// Generates a tensor.empty op. +Value getEmptyTensor(OpBuilder& b, Location loc, ShapedType type, + ArrayRef dynSizes); + +/// Generates an empty tensor for the result of the operation, which could be a +/// dense tensor or a sparse tensor. +Value getEmptyTensorFor(OpBuilder& b, Location loc, ShapedType resultType, + Operation* op, ValueRange operands); + +/// Sparsifies a (block of) operation(s) that cannot be handled directly +/// by the sparse compiler but has well-known semi-ring semantics. +/// +/// This yields something of the following form: +/// +/// %result = sparse_tensor.unary %values[0] +/// present={ +/// ^bb1(%val): +/// ... codegen proceeds here using %val .... +/// sparse_tensor.yield +/// } +/// absent={} +/// linalg.yield %result +Value preSparsify(Operation* op, llvm::SmallVector& values, Type rtp, + OpBuilder* b); + +/// Finalizes sparse semi-ring construction. +Value postSparsify(Operation* op, Value semiring, Value result, OpBuilder* b); + +/// Returns true if all operands are tensors with rank 0. +bool allOperandsAreScalarTensors(Operation* op); + +/// Returns true if parent op is linalg. +bool isInBodyOfLinalgOps(Operation* op); + +/// Converts a HLO operation to a linalg.generic op that contains the +/// corresponding scalar operations. +template +class PointwiseToLinalgConverter : public OpConversionPattern { + public: + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + OpTy op, typename OpTy::Adaptor adaptor, + ConversionPatternRewriter& rewriter) const final { + auto loc = op.getLoc(); + // Find maximum rank / number of loops. + auto getRank = [](Value v) { + return v.getType().cast().getRank(); + }; + auto isScalar = [&](Value v) { return getRank(v) == 0; }; + auto it = llvm::find_if_not(adaptor.getOperands(), isScalar); + Value maxRankArg = + it != adaptor.getOperands().end() ? *it : adaptor.getOperands().front(); + int64_t nloops = getRank(maxRankArg); + + // Apply only if all operands are scalar or have the same rank. Some ops, + // like `mhlo.select`, support implicit broadcasting of scalars. + if (!llvm::all_of(adaptor.getOperands(), [&](Value v) { + int64_t r = getRank(v); + return r == 0 || r == nloops; + })) { + return rewriter.notifyMatchFailure( + op, "Operands must be os same rank or scalar."); + } + + // Find result type, if on tensors. + std::optional resultTy; + resultTy = this->typeConverter->convertType(op->getResultTypes().front()) + .template dyn_cast(); + + // Check result type compatibility. + if (!resultTy || !resultTy->hasRank() || resultTy->getRank() != nloops || + !(resultTy->getElementType().isSignlessIntOrFloat() || + resultTy->getElementType().isa())) { + return rewriter.notifyMatchFailure( + op, "mismatched operand/result types or iterator count"); + } + + if (allOperandsAreScalarTensors(op) && isInBodyOfLinalgOps(op)) + return failure(); + + // Find input/output values and types. + ValueRange inputs = adaptor.getOperands(); + Value output = + getEmptyTensorFor(rewriter, loc, *resultTy, op, adaptor.getOperands()); + + // Create indexing maps. + AffineMap scalarMap = AffineMap::get(nloops, 0, rewriter.getContext()); + AffineMap idMap = rewriter.getMultiDimIdentityMap(nloops); + SmallVector maps; + for (Value v : inputs) maps.push_back(isScalar(v) ? scalarMap : idMap); + maps.push_back(idMap); + + // Build `linalg.generic` op. + bool failed = false; + auto linalgOp = rewriter.create( + loc, resultTy ? *resultTy : TypeRange{}, inputs, output, maps, + getNParallelLoopsAttrs(nloops), + [&](OpBuilder& nestedBuilder, Location /*nested_loc*/, + ValueRange args) { + Type innerResultTy = getElementTypeOrSelf(output); + auto argvec = llvm::to_vector<2>(args.take_front(inputs.size())); + auto semiring = preSparsify(op, argvec, innerResultTy, &rewriter); + Value innerResult = mhlo::MhloOpToStdScalarOp::mapOp( + op, innerResultTy, argvec, &rewriter); + if (innerResult == nullptr) { + failed = true; + } else { + innerResult = postSparsify(op, semiring, innerResult, &rewriter); + nestedBuilder.create(loc, innerResult); + } + }, + linalg::getPrunedAttributeList(op)); + if (failed) return failure(); + + rewriter.replaceOp(op, linalgOp->getResults()); + return success(); + } +}; + +} // namespace mhlo + +} // namespace mlir + +#endif // MLIR_HLO_DIALECT_MHLO_TRANSFORMS_LEGALIZE_TO_LINALG_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f5a1f7c013cfa6e3a8312baefe86565dcd8df1a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops.h @@ -0,0 +1,64 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the operations used in the LHLO dialect. + +#ifndef MLIR_HLO_LHLO_IR_LHLO_OPS_H +#define MLIR_HLO_LHLO_IR_LHLO_OPS_H + +#include "lhlo/IR/lhlo_ops_structs.h" +#include "lhlo/IR/lhlo_structured_interface.h" +#include "llvm/ADT/StringRef.h" +#include "mhlo/IR/hlo_ops.h" +#include "mlir/Dialect/Bufferization/IR/Bufferization.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/IR/Attributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/Location.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/IR/Operation.h" +#include "mlir/IR/Types.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" +#include "mlir/Interfaces/CopyOpInterface.h" +#include "mlir/Interfaces/LoopLikeInterface.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" +#include "mlir/Interfaces/ViewLikeInterface.h" + +namespace mlir { +class OpBuilder; +namespace lmhlo { + +class LmhloDialect : public Dialect { + public: + explicit LmhloDialect(MLIRContext *context); + static StringRef getDialectNamespace() { return "lmhlo"; } + + // Parses an attribute registered to this dialect. + Attribute parseAttribute(DialectAsmParser &parser, Type type) const override; + + // Prints an attribute registered to this dialect. + void printAttribute(Attribute attr, DialectAsmPrinter &os) const override; +}; + +} // namespace lmhlo +} // end namespace mlir + +#define GET_OP_CLASSES +#include "lhlo/IR/lhlo_ops.h.inc" + +#endif // MLIR_HLO_LHLO_IR_LHLO_OPS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops_structs.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops_structs.h new file mode 100644 index 0000000000000000000000000000000000000000..593249a71eb060bf8d10caabfd29c09f4912e5f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/IR/lhlo_ops_structs.h @@ -0,0 +1,30 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines structures used in LMHLO dialect. + +#ifndef MLIR_HLO_LHLO_IR_LHLO_OPS_STRUCTS_H +#define MLIR_HLO_LHLO_IR_LHLO_OPS_STRUCTS_H + +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Types.h" + +// Order matters, this .inc header is not self-contained, and relies on the +// #includes above. +#define GET_ATTRDEF_CLASSES +#include "lhlo/IR/lhlo_ops_structs.h.inc" + +#endif // MLIR_HLO_LHLO_IR_LHLO_OPS_STRUCTS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/utils/lhlo_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/utils/lhlo_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..007e9ddc7ea19ddc700c7dbbd0a90ed14b80d3c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo/lhlo/utils/lhlo_utils.h @@ -0,0 +1,78 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_LHLO_UTILS_LHLO_UTILS_H +#define MLIR_HLO_LHLO_UTILS_LHLO_UTILS_H + +#include + +#include "mhlo/IR/hlo_ops_common.h" +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Types.h" +#include "stablehlo/dialect/TypeInference.h" + +namespace mlir { +namespace lmhlo { + +// TODO(b/236017415): remove when mhlo uses prefix accessor. +namespace accessor_dispatch { +template +auto getOutputs(OpT op, int) -> decltype(op.getOutputs(), ValueRange{}) { + return op.getOutputs(); +} +template +auto getOutputs(OpT op, char) -> decltype(op.results(), ValueRange{}) { + return op.results(); +} + +template +auto getInputs(OpT op, int) -> decltype(op.getInputs(), ValueRange{}) { + return op.getInputs(); +} +template +auto getInputs(OpT op, char) -> decltype(op.operands(), ValueRange{}) { + return op.operands(); +} +} // namespace accessor_dispatch + +template +static LogicalResult verifyAllReduce(OpT op) { + if (failed(hlo::verifyReplicaGroups(op.getLoc(), op.getReplicaGroups(), + /*allGroupsMustHaveSameSize=*/false, + op.getUseGlobalDeviceIds(), + /*expectedGroupSize=*/std::nullopt))) + return failure(); + + // AllReduce has variadic operands and results that have the same size. + // Each member of the operand should have the same type as the corresponding + // member of the result. + for (auto it : llvm::enumerate( + llvm::zip(accessor_dispatch::getInputs(op, 0).getTypes(), + accessor_dispatch::getOutputs(op, 0).getTypes()))) { + Type operandType = std::get<0>(it.value()); + Type resultType = std::get<1>(it.value()); + if (operandType != resultType) + return op.emitOpError("requires operand #") + << it.index() << " (type: " << operandType << ") and result #" + << it.index() << " (type: " << resultType << ") to have same type"; + } + return success(); +} + +} // namespace lmhlo +} // namespace mlir + +#endif // MLIR_HLO_LHLO_UTILS_LHLO_UTILS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu/lhlo_gpu/IR/lhlo_gpu_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu/lhlo_gpu/IR/lhlo_gpu_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..75d5f338693d425b376f68f5f04160727b3d2deb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu/lhlo_gpu/IR/lhlo_gpu_ops.h @@ -0,0 +1,45 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the operations used in the LHLO dialect. + +#ifndef MLIR_HLO_LHLO_GPU_IR_LHLO_GPU_OPS_H +#define MLIR_HLO_LHLO_GPU_IR_LHLO_GPU_OPS_H + +#include "llvm/ADT/StringRef.h" +#include "mhlo/IR/hlo_ops.h" +#include "mlir/IR/Attributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/Location.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/IR/Operation.h" +#include "mlir/IR/Types.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" + +namespace mlir { +class OpBuilder; +} // namespace mlir + +// Include order below matters. +#include "lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc" +#include "lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc" +#define GET_ATTRDEF_CLASSES +#include "lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc" +#define GET_OP_CLASSES +#include "lhlo_gpu/IR/lhlo_gpu_ops.h.inc" + +#endif // MLIR_HLO_LHLO_GPU_IR_LHLO_GPU_OPS_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_attrdefs_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_attrdefs_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..3da68441223b428e5edc3389d2a3e2080e6ebdcc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_attrdefs_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_attrdefs.h.inc @@ -0,0 +1,137 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ActivationAttr; +class ConvolutionBackendConfigAttr; +class CublasLtMatmulEpilogueAttr; +class FusedMHAAlgorithmConfigAttr; +class FusedMhaBackwardDagSignatureAttr; +class FusedMhaDagSignatureAttr; +namespace detail { +struct ActivationAttrStorage; +} // namespace detail +class ActivationAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ActivationAttr get(::mlir::MLIRContext *context, ::mlir::lmhlo_gpu::Activation value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"activation"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::lmhlo_gpu::Activation getValue() const; +}; +namespace detail { +struct ConvolutionBackendConfigAttrStorage; +} // namespace detail +class ConvolutionBackendConfigAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static ConvolutionBackendConfigAttr get(::mlir::MLIRContext *context, int64_t algorithm, bool tensor_ops_enabled, ::llvm::ArrayRef knob_ids, ::llvm::ArrayRef knob_values, bool is_cudnn_frontend, bool is_cudnn_reordered_int8, int64_t workspace_size, ::llvm::ArrayRef operand_0_layout, ::llvm::ArrayRef operand_1_layout, ::llvm::ArrayRef result_layout); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"convolution_backend_config"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getAlgorithm() const; + bool getTensorOpsEnabled() const; + ::llvm::ArrayRef getKnobIds() const; + ::llvm::ArrayRef getKnobValues() const; + bool getIsCudnnFrontend() const; + bool getIsCudnnReorderedInt8() const; + int64_t getWorkspaceSize() const; + ::llvm::ArrayRef getOperand_0Layout() const; + ::llvm::ArrayRef getOperand_1Layout() const; + ::llvm::ArrayRef getResultLayout() const; +}; +namespace detail { +struct CublasLtMatmulEpilogueAttrStorage; +} // namespace detail +class CublasLtMatmulEpilogueAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static CublasLtMatmulEpilogueAttr get(::mlir::MLIRContext *context, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"epilogue"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getValue() const; +}; +namespace detail { +struct FusedMHAAlgorithmConfigAttrStorage; +} // namespace detail +class FusedMHAAlgorithmConfigAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static FusedMHAAlgorithmConfigAttr get(::mlir::MLIRContext *context, int64_t algorithm, ::llvm::ArrayRef knob_ids, ::llvm::ArrayRef knob_values, int64_t workspace_size); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"fHMA_algorithm_config"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getAlgorithm() const; + ::llvm::ArrayRef getKnobIds() const; + ::llvm::ArrayRef getKnobValues() const; + int64_t getWorkspaceSize() const; +}; +namespace detail { +struct FusedMhaBackwardDagSignatureAttrStorage; +} // namespace detail +class FusedMhaBackwardDagSignatureAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static FusedMhaBackwardDagSignatureAttr get(::mlir::MLIRContext *context, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"fused_mha_backward_dag"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getValue() const; +}; +namespace detail { +struct FusedMhaDagSignatureAttrStorage; +} // namespace detail +class FusedMhaDagSignatureAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static FusedMhaDagSignatureAttr get(::mlir::MLIRContext *context, ::mlir::lmhlo_gpu::FusedMhaDagSignature value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"fused_mha_dag"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::lmhlo_gpu::FusedMhaDagSignature getValue() const; +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ActivationAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_dialect_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_dialect_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..d6f68d09ec3c84137350c237d9020f5eeaf314cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_dialect_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_dialect.h.inc @@ -0,0 +1,34 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: lhlo_gpu_ops_enums.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace lmhlo_gpu { + +class LmhloGpuDialect : public ::mlir::Dialect { + explicit LmhloGpuDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~LmhloGpuDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("lmhlo_gpu"); + } + + /// Parse an attribute registered to this dialect. + ::mlir::Attribute parseAttribute(::mlir::DialectAsmParser &parser, + ::mlir::Type type) const override; + + /// Print an attribute registered to this dialect. + void printAttribute(::mlir::Attribute attr, + ::mlir::DialectAsmPrinter &os) const override; +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::LmhloGpuDialect) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_enums_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_enums_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..d7462b53c75db25a25eeb51c0a111ed4a44a4058 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_enums_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops_enums.h.inc @@ -0,0 +1,355 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: lhlo_gpu_ops_enums.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace lmhlo_gpu { +// Activation applied with fused convolution +enum class Activation : uint32_t { + None = 0, + Sigmoid = 1, + Tanh = 2, + Relu = 3, + Relu6 = 4, + ReluX = 5, + BandPass = 6, + Elu = 7, + LeakyRelu = 8, +}; + +::std::optional symbolizeActivation(uint32_t); +::llvm::StringRef stringifyActivation(Activation); +::std::optional symbolizeActivation(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForActivation() { + return 8; +} + + +inline ::llvm::StringRef stringifyEnum(Activation enumValue) { + return stringifyActivation(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeActivation(str); +} +} // namespace lmhlo_gpu +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::lmhlo_gpu::Activation, ::mlir::lmhlo_gpu::Activation> { + template + static FailureOr<::mlir::lmhlo_gpu::Activation> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Activation applied with fused convolution"); + + // Symbolize the keyword. + if (::std::optional<::mlir::lmhlo_gpu::Activation> attr = ::mlir::lmhlo_gpu::symbolizeEnum<::mlir::lmhlo_gpu::Activation>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Activation applied with fused convolution specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::lmhlo_gpu::Activation value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::lmhlo_gpu::Activation> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::lmhlo_gpu::Activation getEmptyKey() { + return static_cast<::mlir::lmhlo_gpu::Activation>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::lmhlo_gpu::Activation getTombstoneKey() { + return static_cast<::mlir::lmhlo_gpu::Activation>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::lmhlo_gpu::Activation &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::lmhlo_gpu::Activation &lhs, const ::mlir::lmhlo_gpu::Activation &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace lmhlo_gpu { +// Epilogue for cublasLt matmul +enum class CublasLtMatmulEpilogue : uint32_t { + Default = 0, + Bias = 1, + Relu = 2, + BiasRelu = 3, + Gelu = 4, + BiasGelu = 5, + GeluAux = 6, + BiasGeluAux = 7, +}; + +::std::optional symbolizeCublasLtMatmulEpilogue(uint32_t); +::llvm::StringRef stringifyCublasLtMatmulEpilogue(CublasLtMatmulEpilogue); +::std::optional symbolizeCublasLtMatmulEpilogue(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForCublasLtMatmulEpilogue() { + return 7; +} + + +inline ::llvm::StringRef stringifyEnum(CublasLtMatmulEpilogue enumValue) { + return stringifyCublasLtMatmulEpilogue(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeCublasLtMatmulEpilogue(str); +} +} // namespace lmhlo_gpu +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue> { + template + static FailureOr<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Epilogue for cublasLt matmul"); + + // Symbolize the keyword. + if (::std::optional<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue> attr = ::mlir::lmhlo_gpu::symbolizeEnum<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid Epilogue for cublasLt matmul specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEmptyKey() { + return static_cast<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getTombstoneKey() { + return static_cast<::mlir::lmhlo_gpu::CublasLtMatmulEpilogue>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue &lhs, const ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace lmhlo_gpu { +// DAG configuration for Fused Multi-Headed Attention Backward +enum class FusedMhaBackwardDagSignature : uint32_t { + BackwardScaleBiasSoftmaxDropout = 0, + BackwardScaleBiasSoftmax = 1, + BackwardScaleBiasMaskSoftmax = 2, + BackwardScaleBiasMaskSoftmaxDropout = 3, +}; + +::std::optional symbolizeFusedMhaBackwardDagSignature(uint32_t); +::llvm::StringRef stringifyFusedMhaBackwardDagSignature(FusedMhaBackwardDagSignature); +::std::optional symbolizeFusedMhaBackwardDagSignature(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForFusedMhaBackwardDagSignature() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(FusedMhaBackwardDagSignature enumValue) { + return stringifyFusedMhaBackwardDagSignature(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeFusedMhaBackwardDagSignature(str); +} +} // namespace lmhlo_gpu +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature> { + template + static FailureOr<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for DAG configuration for Fused Multi-Headed Attention Backward"); + + // Symbolize the keyword. + if (::std::optional<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature> attr = ::mlir::lmhlo_gpu::symbolizeEnum<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid DAG configuration for Fused Multi-Headed Attention Backward specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getEmptyKey() { + return static_cast<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getTombstoneKey() { + return static_cast<::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature &lhs, const ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace lmhlo_gpu { +// DAG configuration for Fused Multi-Headed Attention +enum class FusedMhaDagSignature : uint32_t { + Default = 0, + ScaleBiasMaskSoftmax = 1, + ScaleBiasMaskSoftmaxDropout = 2, + ScaleMaskSoftmax = 3, + ScaleMaskSoftmaxDropout = 4, + SoftmaxDropout = 5, + Softmax = 6, + ScaleBiasSoftmaxDropout = 7, + ScaleBiasSoftmax = 8, +}; + +::std::optional symbolizeFusedMhaDagSignature(uint32_t); +::llvm::StringRef stringifyFusedMhaDagSignature(FusedMhaDagSignature); +::std::optional symbolizeFusedMhaDagSignature(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForFusedMhaDagSignature() { + return 8; +} + + +inline ::llvm::StringRef stringifyEnum(FusedMhaDagSignature enumValue) { + return stringifyFusedMhaDagSignature(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeFusedMhaDagSignature(str); +} +} // namespace lmhlo_gpu +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::lmhlo_gpu::FusedMhaDagSignature, ::mlir::lmhlo_gpu::FusedMhaDagSignature> { + template + static FailureOr<::mlir::lmhlo_gpu::FusedMhaDagSignature> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for DAG configuration for Fused Multi-Headed Attention"); + + // Symbolize the keyword. + if (::std::optional<::mlir::lmhlo_gpu::FusedMhaDagSignature> attr = ::mlir::lmhlo_gpu::symbolizeEnum<::mlir::lmhlo_gpu::FusedMhaDagSignature>(enumKeyword)) + return *attr; + return parser.emitError(loc, "invalid DAG configuration for Fused Multi-Headed Attention specification: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::lmhlo_gpu::FusedMhaDagSignature value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::lmhlo_gpu::FusedMhaDagSignature> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::lmhlo_gpu::FusedMhaDagSignature getEmptyKey() { + return static_cast<::mlir::lmhlo_gpu::FusedMhaDagSignature>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::lmhlo_gpu::FusedMhaDagSignature getTombstoneKey() { + return static_cast<::mlir::lmhlo_gpu::FusedMhaDagSignature>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::lmhlo_gpu::FusedMhaDagSignature &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::lmhlo_gpu::FusedMhaDagSignature &lhs, const ::mlir::lmhlo_gpu::FusedMhaDagSignature &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..d02e409e79394ed7b757244fd7a27b03b4da45d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_inc_gen/lhlo_gpu/IR/lhlo_gpu_ops.h.inc @@ -0,0 +1,5153 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: lhlo_gpu_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace lmhlo_gpu { +class AllGatherDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllGatherStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllReduceDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllReduceStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllToAllDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllToAllStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CholeskyOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CollectivePermuteDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CollectivePermuteStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvBackwardFilterOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvBackwardInputOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardFusedOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardFusedSideInputOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardGraphOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CublasLtMatmulF8Op; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CublasLtMatmulOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CudnnConvReorderFilterAndBiasOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CudnnConvReorderFilterOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class GEMMOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ReduceScatterDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ReduceScatterStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class fusedMHABackwardOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class fusedMHAOp; +} // namespace lmhlo_gpu +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllGatherDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllGatherDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllGatherDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllGatherDoneOpGenericAdaptorBase(AllGatherDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllGatherDoneOpGenericAdaptor : public detail::AllGatherDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllGatherDoneOpGenericAdaptorBase; +public: + AllGatherDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllGatherDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllGatherDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllGatherDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllGatherDoneOpAdaptor : public AllGatherDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllGatherDoneOpGenericAdaptor::AllGatherDoneOpGenericAdaptor; + AllGatherDoneOpAdaptor(AllGatherDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllGatherDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllGatherDoneOpAdaptor; + template + using GenericAdaptor = AllGatherDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_gather_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllGatherDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllGatherStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllGatherStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllGatherStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllGatherStartOpGenericAdaptorBase(AllGatherStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getAllGatherDimensionAttr(); + uint64_t getAllGatherDimension(); +}; +} // namespace detail +template +class AllGatherStartOpGenericAdaptor : public detail::AllGatherStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllGatherStartOpGenericAdaptorBase; +public: + AllGatherStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllGatherStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllGatherStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllGatherStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllGatherStartOpAdaptor : public AllGatherStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllGatherStartOpGenericAdaptor::AllGatherStartOpGenericAdaptor; + AllGatherStartOpAdaptor(AllGatherStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllGatherStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllGatherStartOpAdaptor; + template + using GenericAdaptor = AllGatherStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("all_gather_dimension"), ::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAllGatherDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAllGatherDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_gather_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getAllGatherDimensionAttr(); + uint64_t getAllGatherDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setAllGatherDimensionAttr(::mlir::IntegerAttr attr); + void setAllGatherDimension(uint64_t attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t all_gather_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllGatherStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllReduceDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceDoneOpGenericAdaptorBase(AllReduceDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllReduceDoneOpGenericAdaptor : public detail::AllReduceDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceDoneOpGenericAdaptorBase; +public: + AllReduceDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllReduceDoneOpAdaptor : public AllReduceDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceDoneOpGenericAdaptor::AllReduceDoneOpGenericAdaptor; + AllReduceDoneOpAdaptor(AllReduceDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceDoneOpAdaptor; + template + using GenericAdaptor = AllReduceDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_reduce_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllReduceDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllReduceStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceStartOpGenericAdaptorBase(AllReduceStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class AllReduceStartOpGenericAdaptor : public detail::AllReduceStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceStartOpGenericAdaptorBase; +public: + AllReduceStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllReduceStartOpAdaptor : public AllReduceStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceStartOpGenericAdaptor::AllReduceStartOpGenericAdaptor; + AllReduceStartOpAdaptor(AllReduceStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceStartOpAdaptor; + template + using GenericAdaptor = AllReduceStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_reduce_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 5 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllReduceStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllToAllDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllDoneOpGenericAdaptorBase(AllToAllDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllToAllDoneOpGenericAdaptor : public detail::AllToAllDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllDoneOpGenericAdaptorBase; +public: + AllToAllDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllDoneOpAdaptor : public AllToAllDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllDoneOpGenericAdaptor::AllToAllDoneOpGenericAdaptor; + AllToAllDoneOpAdaptor(AllToAllDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllDoneOpAdaptor; + template + using GenericAdaptor = AllToAllDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_to_all_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllToAllDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllToAllStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllStartOpGenericAdaptorBase(AllToAllStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); +}; +} // namespace detail +template +class AllToAllStartOpGenericAdaptor : public detail::AllToAllStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllStartOpGenericAdaptorBase; +public: + AllToAllStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllStartOpAdaptor : public AllToAllStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllStartOpGenericAdaptor::AllToAllStartOpGenericAdaptor; + AllToAllStartOpAdaptor(AllToAllStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllStartOpAdaptor; + template + using GenericAdaptor = AllToAllStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("split_dimension"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getSplitDimensionAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getSplitDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_to_all_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setSplitDimensionAttr(::mlir::IntegerAttr attr); + void setSplitDimension(::std::optional attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + ::mlir::Attribute removeSplitDimensionAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllToAllStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CholeskyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CholeskyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CholeskyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CholeskyOpGenericAdaptorBase(CholeskyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getIsLowerAttr(); + bool getIsLower(); +}; +} // namespace detail +template +class CholeskyOpGenericAdaptor : public detail::CholeskyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CholeskyOpGenericAdaptorBase; +public: + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CholeskyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CholeskyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(2).begin()); + } + + ValueT getInfo() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CholeskyOpAdaptor : public CholeskyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CholeskyOpGenericAdaptor::CholeskyOpGenericAdaptor; + CholeskyOpAdaptor(CholeskyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CholeskyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CholeskyOpAdaptor; + template + using GenericAdaptor = CholeskyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("is_lower")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIsLowerAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIsLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cholesky"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getInfo(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::OpOperand &getInfoMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getIsLowerAttr(); + bool getIsLower(); + void setIsLowerAttr(::mlir::BoolAttr attr); + void setIsLower(bool attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, ::mlir::BoolAttr is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, ::mlir::BoolAttr is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, bool is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, bool is_lower); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CholeskyOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CollectivePermuteDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteDoneOpGenericAdaptorBase(CollectivePermuteDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CollectivePermuteDoneOpGenericAdaptor : public detail::CollectivePermuteDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteDoneOpGenericAdaptorBase; +public: + CollectivePermuteDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteDoneOpAdaptor : public CollectivePermuteDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteDoneOpGenericAdaptor::CollectivePermuteDoneOpGenericAdaptor; + CollectivePermuteDoneOpAdaptor(CollectivePermuteDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteDoneOpAdaptor; + template + using GenericAdaptor = CollectivePermuteDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.collective_permute_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CollectivePermuteDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CollectivePermuteStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteStartOpGenericAdaptorBase(CollectivePermuteStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); +}; +} // namespace detail +template +class CollectivePermuteStartOpGenericAdaptor : public detail::CollectivePermuteStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteStartOpGenericAdaptorBase; +public: + CollectivePermuteStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteStartOpAdaptor : public CollectivePermuteStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteStartOpGenericAdaptor::CollectivePermuteStartOpGenericAdaptor; + CollectivePermuteStartOpAdaptor(CollectivePermuteStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteStartOpAdaptor; + template + using GenericAdaptor = CollectivePermuteStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("source_target_pairs")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getSourceTargetPairsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getSourceTargetPairsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.collective_permute_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + void setSourceTargetPairsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + ::mlir::Attribute removeChannelIdAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, bool is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, bool is_sync); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CollectivePermuteStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvBackwardFilterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvBackwardFilterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvBackwardFilterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvBackwardFilterOpGenericAdaptorBase(ConvBackwardFilterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvBackwardFilterOpGenericAdaptor : public detail::ConvBackwardFilterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvBackwardFilterOpGenericAdaptorBase; +public: + ConvBackwardFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvBackwardFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvBackwardFilterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvBackwardFilterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getDOutput() { + return (*getODSOperands(1).begin()); + } + + ValueT getDFilter() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvBackwardFilterOpAdaptor : public ConvBackwardFilterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvBackwardFilterOpGenericAdaptor::ConvBackwardFilterOpGenericAdaptor; + ConvBackwardFilterOpAdaptor(ConvBackwardFilterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvBackwardFilterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvBackwardFilterOpAdaptor; + template + using GenericAdaptor = ConvBackwardFilterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_backwardfilter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getDFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::OpOperand &getDFilterMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvBackwardFilterOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvBackwardInputOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvBackwardInputOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvBackwardInputOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvBackwardInputOpGenericAdaptorBase(ConvBackwardInputOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvBackwardInputOpGenericAdaptor : public detail::ConvBackwardInputOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvBackwardInputOpGenericAdaptorBase; +public: + ConvBackwardInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvBackwardInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvBackwardInputOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvBackwardInputOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getDOutput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getDInput() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvBackwardInputOpAdaptor : public ConvBackwardInputOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvBackwardInputOpGenericAdaptor::ConvBackwardInputOpGenericAdaptor; + ConvBackwardInputOpAdaptor(ConvBackwardInputOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvBackwardInputOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvBackwardInputOpAdaptor; + template + using GenericAdaptor = ConvBackwardInputOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_backwardinput"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getDInput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getDInputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvBackwardInputOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardFusedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardFusedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardFusedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardFusedOpGenericAdaptorBase(ConvForwardFusedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getLeakyreluAlphaAttr(); + ::llvm::APFloat getLeakyreluAlpha(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardFusedOpGenericAdaptor : public detail::ConvForwardFusedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardFusedOpGenericAdaptorBase; +public: + ConvForwardFusedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardFusedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardFusedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardFusedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getBias() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardFusedOpAdaptor : public ConvForwardFusedOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardFusedOpGenericAdaptor::ConvForwardFusedOpGenericAdaptor; + ConvForwardFusedOpAdaptor(ConvForwardFusedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardFusedOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardFusedOpAdaptor; + template + using GenericAdaptor = ConvForwardFusedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("activation_mode"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("leakyrelu_alpha"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getActivationModeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getActivationModeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getLeakyreluAlphaAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getLeakyreluAlphaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_fused"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getBiasMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getLeakyreluAlphaAttr(); + ::llvm::APFloat getLeakyreluAlpha(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setActivationModeAttr(::mlir::lmhlo_gpu::ActivationAttr attr); + void setActivationMode(::mlir::lmhlo_gpu::Activation attrValue); + void setLeakyreluAlphaAttr(::mlir::FloatAttr attr); + void setLeakyreluAlpha(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 13 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardFusedOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardFusedSideInputOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardFusedSideInputOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardFusedSideInputOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardFusedSideInputOpGenericAdaptorBase(ConvForwardFusedSideInputOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getSideInputScaleAttr(); + ::llvm::APFloat getSideInputScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardFusedSideInputOpGenericAdaptor : public detail::ConvForwardFusedSideInputOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardFusedSideInputOpGenericAdaptorBase; +public: + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardFusedSideInputOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getBias() { + return (*getODSOperands(2).begin()); + } + + ValueT getSideInput() { + return (*getODSOperands(3).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(4).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardFusedSideInputOpAdaptor : public ConvForwardFusedSideInputOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardFusedSideInputOpGenericAdaptor::ConvForwardFusedSideInputOpGenericAdaptor; + ConvForwardFusedSideInputOpAdaptor(ConvForwardFusedSideInputOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardFusedSideInputOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardFusedSideInputOpAdaptor; + template + using GenericAdaptor = ConvForwardFusedSideInputOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("activation_mode"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("side_input_scale"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getActivationModeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getActivationModeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getSideInputScaleAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getSideInputScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_fused_with_side_input"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getSideInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getBiasMutable(); + ::mlir::OpOperand &getSideInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getSideInputScaleAttr(); + ::llvm::APFloat getSideInputScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setActivationModeAttr(::mlir::lmhlo_gpu::ActivationAttr attr); + void setActivationMode(::mlir::lmhlo_gpu::Activation attrValue); + void setSideInputScaleAttr(::mlir::FloatAttr attr); + void setSideInputScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 13 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardFusedSideInputOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardGraphOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardGraphOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardGraphOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardGraphOpGenericAdaptorBase(ConvForwardGraphOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::IntegerAttr getNAuxOutputsAttr(); + uint32_t getNAuxOutputs(); + ::mlir::StringAttr getSerializedGraphAttr(); + ::llvm::StringRef getSerializedGraph(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardGraphOpGenericAdaptor : public detail::ConvForwardGraphOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardGraphOpGenericAdaptorBase; +public: + ConvForwardGraphOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardGraphOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardGraphOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardGraphOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + RangeT getBinaryOperands() { + return getODSOperands(2); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getAuxOutputs() { + return getODSOperands(4); + } + + ValueT getScratch() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardGraphOpAdaptor : public ConvForwardGraphOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardGraphOpGenericAdaptor::ConvForwardGraphOpGenericAdaptor; + ConvForwardGraphOpAdaptor(ConvForwardGraphOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardGraphOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardGraphOpAdaptor; + template + using GenericAdaptor = ConvForwardGraphOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("n_aux_outputs"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("serialized_graph"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getNAuxOutputsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getNAuxOutputsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getSerializedGraphAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getSerializedGraphAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(13); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 13); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_graph"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::Operation::operand_range getBinaryOperands(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::Operation::operand_range getAuxOutputs(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::MutableOperandRange getBinaryOperandsMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::MutableOperandRange getAuxOutputsMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::IntegerAttr getNAuxOutputsAttr(); + uint32_t getNAuxOutputs(); + ::mlir::StringAttr getSerializedGraphAttr(); + ::llvm::StringRef getSerializedGraph(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setNAuxOutputsAttr(::mlir::IntegerAttr attr); + void setNAuxOutputs(uint32_t attrValue); + void setSerializedGraphAttr(::mlir::StringAttr attr); + void setSerializedGraph(::llvm::StringRef attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::IntegerAttr n_aux_outputs, ::mlir::StringAttr serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::IntegerAttr n_aux_outputs, ::mlir::StringAttr serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, uint32_t n_aux_outputs, ::llvm::StringRef serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, uint32_t n_aux_outputs, ::llvm::StringRef serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 14 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardGraphOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardOpGenericAdaptorBase(ConvForwardOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardOpGenericAdaptor : public detail::ConvForwardOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardOpGenericAdaptorBase; +public: + ConvForwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardOpAdaptor : public ConvForwardOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardOpGenericAdaptor::ConvForwardOpGenericAdaptor; + ConvForwardOpAdaptor(ConvForwardOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardOpAdaptor; + template + using GenericAdaptor = ConvForwardOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CublasLtMatmulF8Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CublasLtMatmulF8OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CublasLtMatmulF8OpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CublasLtMatmulF8OpGenericAdaptorBase(CublasLtMatmulF8Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); +}; +} // namespace detail +template +class CublasLtMatmulF8OpGenericAdaptor : public detail::CublasLtMatmulF8OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CublasLtMatmulF8OpGenericAdaptorBase; +public: + CublasLtMatmulF8OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CublasLtMatmulF8OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CublasLtMatmulF8OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CublasLtMatmulF8OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + ValueT getAScale() { + return (*getODSOperands(3).begin()); + } + + ValueT getBScale() { + return (*getODSOperands(4).begin()); + } + + ValueT getCScale() { + return (*getODSOperands(5).begin()); + } + + ValueT getDScale() { + return (*getODSOperands(6).begin()); + } + + ValueT getD() { + return (*getODSOperands(7).begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(8); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getDAmax() { + auto operands = getODSOperands(9); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CublasLtMatmulF8OpAdaptor : public CublasLtMatmulF8OpGenericAdaptor<::mlir::ValueRange> { +public: + using CublasLtMatmulF8OpGenericAdaptor::CublasLtMatmulF8OpGenericAdaptor; + CublasLtMatmulF8OpAdaptor(CublasLtMatmulF8Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CublasLtMatmulF8Op : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CublasLtMatmulF8OpAdaptor; + template + using GenericAdaptor = CublasLtMatmulF8OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("epilogue"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getEpilogueAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getEpilogueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cublas.lt.matmul.f8"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::TypedValue<::mlir::MemRefType> getAScale(); + ::mlir::TypedValue<::mlir::MemRefType> getBScale(); + ::mlir::TypedValue<::mlir::MemRefType> getCScale(); + ::mlir::TypedValue<::mlir::MemRefType> getDScale(); + ::mlir::TypedValue<::mlir::MemRefType> getD(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getDAmax(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + ::mlir::OpOperand &getAScaleMutable(); + ::mlir::OpOperand &getBScaleMutable(); + ::mlir::OpOperand &getCScaleMutable(); + ::mlir::OpOperand &getDScaleMutable(); + ::mlir::OpOperand &getDMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::MutableOperandRange getDAmaxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setEpilogueAttr(::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr attr); + void setEpilogue(::mlir::lmhlo_gpu::CublasLtMatmulEpilogue attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(uint64_t attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 8 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CublasLtMatmulF8Op) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CublasLtMatmulOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CublasLtMatmulOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CublasLtMatmulOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CublasLtMatmulOpGenericAdaptorBase(CublasLtMatmulOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); +}; +} // namespace detail +template +class CublasLtMatmulOpGenericAdaptor : public detail::CublasLtMatmulOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CublasLtMatmulOpGenericAdaptorBase; +public: + CublasLtMatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CublasLtMatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CublasLtMatmulOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CublasLtMatmulOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + ValueT getD() { + return (*getODSOperands(3).begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(4); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getAux() { + auto operands = getODSOperands(5); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CublasLtMatmulOpAdaptor : public CublasLtMatmulOpGenericAdaptor<::mlir::ValueRange> { +public: + using CublasLtMatmulOpGenericAdaptor::CublasLtMatmulOpGenericAdaptor; + CublasLtMatmulOpAdaptor(CublasLtMatmulOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CublasLtMatmulOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CublasLtMatmulOpAdaptor; + template + using GenericAdaptor = CublasLtMatmulOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("epilogue"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getEpilogueAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getEpilogueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cublas.lt.matmul"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::TypedValue<::mlir::MemRefType> getD(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getAux(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + ::mlir::OpOperand &getDMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::MutableOperandRange getAuxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setEpilogueAttr(::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr attr); + void setEpilogue(::mlir::lmhlo_gpu::CublasLtMatmulEpilogue attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(uint64_t attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 8 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CublasLtMatmulOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CudnnConvReorderFilterAndBiasOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CudnnConvReorderFilterAndBiasOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CudnnConvReorderFilterAndBiasOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CudnnConvReorderFilterAndBiasOpGenericAdaptorBase(CudnnConvReorderFilterAndBiasOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); +}; +} // namespace detail +template +class CudnnConvReorderFilterAndBiasOpGenericAdaptor : public detail::CudnnConvReorderFilterAndBiasOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CudnnConvReorderFilterAndBiasOpGenericAdaptorBase; +public: + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CudnnConvReorderFilterAndBiasOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getFilterInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getBiasInput() { + return (*getODSOperands(1).begin()); + } + + ValueT getFilterOutput() { + return (*getODSOperands(2).begin()); + } + + ValueT getBiasOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CudnnConvReorderFilterAndBiasOpAdaptor : public CudnnConvReorderFilterAndBiasOpGenericAdaptor<::mlir::ValueRange> { +public: + using CudnnConvReorderFilterAndBiasOpGenericAdaptor::CudnnConvReorderFilterAndBiasOpGenericAdaptor; + CudnnConvReorderFilterAndBiasOpAdaptor(CudnnConvReorderFilterAndBiasOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CudnnConvReorderFilterAndBiasOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CudnnConvReorderFilterAndBiasOpAdaptor; + template + using GenericAdaptor = CudnnConvReorderFilterAndBiasOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("filter_dims")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFilterDimsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFilterDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cudnn_conv_reorder_filter_and_bias"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getFilterInput(); + ::mlir::TypedValue<::mlir::MemRefType> getBiasInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilterOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getBiasOutput(); + ::mlir::OpOperand &getFilterInputMutable(); + ::mlir::OpOperand &getBiasInputMutable(); + ::mlir::OpOperand &getFilterOutputMutable(); + ::mlir::OpOperand &getBiasOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); + void setFilterDimsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value filter_input, ::mlir::Value bias_input, ::mlir::Value filter_output, ::mlir::Value bias_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value filter_input, ::mlir::Value bias_input, ::mlir::Value filter_output, ::mlir::Value bias_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CudnnConvReorderFilterAndBiasOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CudnnConvReorderFilterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CudnnConvReorderFilterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CudnnConvReorderFilterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CudnnConvReorderFilterOpGenericAdaptorBase(CudnnConvReorderFilterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); +}; +} // namespace detail +template +class CudnnConvReorderFilterOpGenericAdaptor : public detail::CudnnConvReorderFilterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CudnnConvReorderFilterOpGenericAdaptorBase; +public: + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CudnnConvReorderFilterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getFilterInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilterOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CudnnConvReorderFilterOpAdaptor : public CudnnConvReorderFilterOpGenericAdaptor<::mlir::ValueRange> { +public: + using CudnnConvReorderFilterOpGenericAdaptor::CudnnConvReorderFilterOpGenericAdaptor; + CudnnConvReorderFilterOpAdaptor(CudnnConvReorderFilterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CudnnConvReorderFilterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CudnnConvReorderFilterOpAdaptor; + template + using GenericAdaptor = CudnnConvReorderFilterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("filter_dims")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFilterDimsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFilterDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cudnn_conv_reorder_filter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getFilterInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilterOutput(); + ::mlir::OpOperand &getFilterInputMutable(); + ::mlir::OpOperand &getFilterOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); + void setFilterDimsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value filter_input, ::mlir::Value filter_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value filter_input, ::mlir::Value filter_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CudnnConvReorderFilterOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::GEMMOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GEMMOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GEMMOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GEMMOpGenericAdaptorBase(GEMMOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::IntegerAttr getAlgorithmAttr(); + ::std::optional getAlgorithm(); +}; +} // namespace detail +template +class GEMMOpGenericAdaptor : public detail::GEMMOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GEMMOpGenericAdaptorBase; +public: + GEMMOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GEMMOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GEMMOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GEMMOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GEMMOpAdaptor : public GEMMOpGenericAdaptor<::mlir::ValueRange> { +public: + using GEMMOpGenericAdaptor::GEMMOpGenericAdaptor; + GEMMOpAdaptor(GEMMOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GEMMOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GEMMOpAdaptor; + template + using GenericAdaptor = GEMMOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.gemm"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::IntegerAttr getAlgorithmAttr(); + ::std::optional getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(::std::optional attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + ::mlir::Attribute removeAlgorithmAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::GEMMOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ReduceScatterDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceScatterDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceScatterDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceScatterDoneOpGenericAdaptorBase(ReduceScatterDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReduceScatterDoneOpGenericAdaptor : public detail::ReduceScatterDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceScatterDoneOpGenericAdaptorBase; +public: + ReduceScatterDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceScatterDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceScatterDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceScatterDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceScatterDoneOpAdaptor : public ReduceScatterDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceScatterDoneOpGenericAdaptor::ReduceScatterDoneOpGenericAdaptor; + ReduceScatterDoneOpAdaptor(ReduceScatterDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceScatterDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceScatterDoneOpAdaptor; + template + using GenericAdaptor = ReduceScatterDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.reduce_scatter_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ReduceScatterDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ReduceScatterStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceScatterStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceScatterStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceScatterStartOpGenericAdaptorBase(ReduceScatterStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceScatterStartOpGenericAdaptor : public detail::ReduceScatterStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceScatterStartOpGenericAdaptorBase; +public: + ReduceScatterStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceScatterStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceScatterStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceScatterStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceScatterStartOpAdaptor : public ReduceScatterStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceScatterStartOpGenericAdaptor::ReduceScatterStartOpGenericAdaptor; + ReduceScatterStartOpAdaptor(ReduceScatterStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceScatterStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceScatterStartOpAdaptor; + template + using GenericAdaptor = ReduceScatterStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("scatter_dimension"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getScatterDimensionAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getScatterDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.reduce_scatter_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setScatterDimensionAttr(::mlir::IntegerAttr attr); + void setScatterDimension(uint64_t attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t scatter_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ReduceScatterStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::fusedMHABackwardOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class fusedMHABackwardOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + fusedMHABackwardOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + fusedMHABackwardOpGenericAdaptorBase(fusedMHABackwardOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbers(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); +}; +} // namespace detail +template +class fusedMHABackwardOpGenericAdaptor : public detail::fusedMHABackwardOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::fusedMHABackwardOpGenericAdaptorBase; +public: + fusedMHABackwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + fusedMHABackwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : fusedMHABackwardOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + fusedMHABackwardOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBmm1GradGemm1Rhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getBmm1GradGemm2Rhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getBmm2GradGemm2Rhs() { + return (*getODSOperands(2).begin()); + } + + ValueT getBmm2GradGemm1Lhs() { + return (*getODSOperands(3).begin()); + } + + ValueT getDOutput() { + return (*getODSOperands(4).begin()); + } + + ValueT getMask() { + auto operands = getODSOperands(5); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getDBmm1Lhs() { + return (*getODSOperands(6).begin()); + } + + ValueT getDBmm1Rhs() { + return (*getODSOperands(7).begin()); + } + + ValueT getDBmm2Rhs() { + return (*getODSOperands(8).begin()); + } + + ValueT getD_S() { + return (*getODSOperands(9).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(10).begin()); + } + + ValueT getDBias() { + auto operands = getODSOperands(11); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class fusedMHABackwardOpAdaptor : public fusedMHABackwardOpGenericAdaptor<::mlir::ValueRange> { +public: + using fusedMHABackwardOpGenericAdaptor::fusedMHABackwardOpGenericAdaptor; + fusedMHABackwardOpAdaptor(fusedMHABackwardOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class fusedMHABackwardOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = fusedMHABackwardOpAdaptor; + template + using GenericAdaptor = fusedMHABackwardOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm_config"), ::llvm::StringRef("bmm1_grad_gemm1_dot_dimension_numbers"), ::llvm::StringRef("bmm1_grad_gemm2_dot_dimension_numbers"), ::llvm::StringRef("bmm2_grad_gemm1_dot_dimension_numbers"), ::llvm::StringRef("bmm2_grad_gemm2_dot_dimension_numbers"), ::llvm::StringRef("dropout_rate"), ::llvm::StringRef("fmha_scale"), ::llvm::StringRef("fused_mha_dag"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("seed")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBmm1GradGemm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBmm1GradGemm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBmm1GradGemm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBmm1GradGemm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBmm2GradGemm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBmm2GradGemm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getBmm2GradGemm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getBmm2GradGemm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getDropoutRateAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getDropoutRateAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getFmhaScaleAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getFmhaScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getFusedMhaDagAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getFusedMhaDagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getSeedAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getSeedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.fMHABackward"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getBmm1GradGemm1Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm1GradGemm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm2GradGemm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm2GradGemm1Lhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getMask(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm1Lhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm1Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getD_S(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getDBias(); + ::mlir::OpOperand &getBmm1GradGemm1RhsMutable(); + ::mlir::OpOperand &getBmm1GradGemm2RhsMutable(); + ::mlir::OpOperand &getBmm2GradGemm2RhsMutable(); + ::mlir::OpOperand &getBmm2GradGemm1LhsMutable(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::MutableOperandRange getMaskMutable(); + ::mlir::OpOperand &getDBmm1LhsMutable(); + ::mlir::OpOperand &getDBmm1RhsMutable(); + ::mlir::OpOperand &getDBmm2RhsMutable(); + ::mlir::OpOperand &getD_SMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::MutableOperandRange getDBiasMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbers(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); + void setBmm1GradGemm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm1GradGemm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2GradGemm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2GradGemm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setFmhaScaleAttr(::mlir::FloatAttr attr); + void setFmhaScale(::llvm::APFloat attrValue); + void setFusedMhaDagAttr(::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr attr); + void setFusedMhaDag(::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature attrValue); + void setAlgorithmConfigAttr(::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr attr); + void setDropoutRateAttr(::mlir::FloatAttr attr); + void setDropoutRate(::std::optional<::llvm::APFloat> attrValue); + void setSeedAttr(::mlir::IntegerAttr attr); + void setSeed(::std::optional attrValue); + ::mlir::Attribute removeDropoutRateAttr(); + ::mlir::Attribute removeSeedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 10 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::fusedMHABackwardOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::fusedMHAOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class fusedMHAOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + fusedMHAOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + fusedMHAOpGenericAdaptorBase(fusedMHAOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbers(); + ::mlir::ArrayAttr getIntermediateTensorDimensionsAttr(); + ::mlir::ArrayAttr getIntermediateTensorDimensions(); + ::mlir::ArrayAttr getIntermediateTensorLayoutAttr(); + ::mlir::ArrayAttr getIntermediateTensorLayout(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); +}; +} // namespace detail +template +class fusedMHAOpGenericAdaptor : public detail::fusedMHAOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::fusedMHAOpGenericAdaptorBase; +public: + fusedMHAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + fusedMHAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : fusedMHAOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + fusedMHAOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhsBmm1() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhsBmm1() { + return (*getODSOperands(1).begin()); + } + + ValueT getRhsBmm2() { + return (*getODSOperands(2).begin()); + } + + ValueT getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(4); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getOutput() { + return (*getODSOperands(5).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(6).begin()); + } + + ValueT getActivation() { + auto operands = getODSOperands(7); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class fusedMHAOpAdaptor : public fusedMHAOpGenericAdaptor<::mlir::ValueRange> { +public: + using fusedMHAOpGenericAdaptor::fusedMHAOpGenericAdaptor; + fusedMHAOpAdaptor(fusedMHAOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class fusedMHAOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = fusedMHAOpAdaptor; + template + using GenericAdaptor = fusedMHAOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm_config"), ::llvm::StringRef("bmm1_dot_dimension_numbers"), ::llvm::StringRef("bmm2_dot_dimension_numbers"), ::llvm::StringRef("dropout_rate"), ::llvm::StringRef("fmha_scale"), ::llvm::StringRef("fused_mha_dag"), ::llvm::StringRef("intermediate_tensor_dimensions"), ::llvm::StringRef("intermediate_tensor_layout"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("seed")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBmm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBmm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBmm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBmm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDropoutRateAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDropoutRateAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFmhaScaleAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFmhaScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getFusedMhaDagAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getFusedMhaDagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getIntermediateTensorDimensionsAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getIntermediateTensorDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getIntermediateTensorLayoutAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getIntermediateTensorLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getSeedAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getSeedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.fMHA"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhsBmm1(); + ::mlir::TypedValue<::mlir::MemRefType> getRhsBmm1(); + ::mlir::TypedValue<::mlir::MemRefType> getRhsBmm2(); + ::mlir::TypedValue<::mlir::MemRefType> getMask(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getActivation(); + ::mlir::OpOperand &getLhsBmm1Mutable(); + ::mlir::OpOperand &getRhsBmm1Mutable(); + ::mlir::OpOperand &getRhsBmm2Mutable(); + ::mlir::MutableOperandRange getMaskMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::MutableOperandRange getActivationMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbers(); + ::mlir::ArrayAttr getIntermediateTensorDimensionsAttr(); + ::mlir::ArrayAttr getIntermediateTensorDimensions(); + ::mlir::ArrayAttr getIntermediateTensorLayoutAttr(); + ::mlir::ArrayAttr getIntermediateTensorLayout(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); + void setBmm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setIntermediateTensorDimensionsAttr(::mlir::ArrayAttr attr); + void setIntermediateTensorLayoutAttr(::mlir::ArrayAttr attr); + void setFmhaScaleAttr(::mlir::FloatAttr attr); + void setFmhaScale(::llvm::APFloat attrValue); + void setFusedMhaDagAttr(::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr attr); + void setFusedMhaDag(::mlir::lmhlo_gpu::FusedMhaDagSignature attrValue); + void setAlgorithmConfigAttr(::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr attr); + void setDropoutRateAttr(::mlir::FloatAttr attr); + void setDropoutRate(::std::optional<::llvm::APFloat> attrValue); + void setSeedAttr(::mlir::IntegerAttr attr); + void setSeed(::std::optional attrValue); + ::mlir::Attribute removeDropoutRateAttr(); + ::mlir::Attribute removeSeedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 10 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::fusedMHAOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_ops/lhlo_gpu/IR/lhlo_gpu_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_ops/lhlo_gpu/IR/lhlo_gpu_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..d02e409e79394ed7b757244fd7a27b03b4da45d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_gpu_ops_ops/lhlo_gpu/IR/lhlo_gpu_ops.h.inc @@ -0,0 +1,5153 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: lhlo_gpu_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace lmhlo_gpu { +class AllGatherDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllGatherStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllReduceDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllReduceStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllToAllDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class AllToAllStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CholeskyOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CollectivePermuteDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CollectivePermuteStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvBackwardFilterOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvBackwardInputOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardFusedOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardFusedSideInputOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardGraphOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ConvForwardOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CublasLtMatmulF8Op; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CublasLtMatmulOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CudnnConvReorderFilterAndBiasOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class CudnnConvReorderFilterOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class GEMMOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ReduceScatterDoneOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class ReduceScatterStartOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class fusedMHABackwardOp; +} // namespace lmhlo_gpu +} // namespace mlir +namespace mlir { +namespace lmhlo_gpu { +class fusedMHAOp; +} // namespace lmhlo_gpu +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllGatherDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllGatherDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllGatherDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllGatherDoneOpGenericAdaptorBase(AllGatherDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllGatherDoneOpGenericAdaptor : public detail::AllGatherDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllGatherDoneOpGenericAdaptorBase; +public: + AllGatherDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllGatherDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllGatherDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllGatherDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllGatherDoneOpAdaptor : public AllGatherDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllGatherDoneOpGenericAdaptor::AllGatherDoneOpGenericAdaptor; + AllGatherDoneOpAdaptor(AllGatherDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllGatherDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllGatherDoneOpAdaptor; + template + using GenericAdaptor = AllGatherDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_gather_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllGatherDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllGatherStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllGatherStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllGatherStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllGatherStartOpGenericAdaptorBase(AllGatherStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getAllGatherDimensionAttr(); + uint64_t getAllGatherDimension(); +}; +} // namespace detail +template +class AllGatherStartOpGenericAdaptor : public detail::AllGatherStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllGatherStartOpGenericAdaptorBase; +public: + AllGatherStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllGatherStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllGatherStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllGatherStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllGatherStartOpAdaptor : public AllGatherStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllGatherStartOpGenericAdaptor::AllGatherStartOpGenericAdaptor; + AllGatherStartOpAdaptor(AllGatherStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllGatherStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllGatherStartOpAdaptor; + template + using GenericAdaptor = AllGatherStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("all_gather_dimension"), ::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAllGatherDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAllGatherDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_gather_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getAllGatherDimensionAttr(); + uint64_t getAllGatherDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setAllGatherDimensionAttr(::mlir::IntegerAttr attr); + void setAllGatherDimension(uint64_t attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t all_gather_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t all_gather_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllGatherStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllReduceDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceDoneOpGenericAdaptorBase(AllReduceDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllReduceDoneOpGenericAdaptor : public detail::AllReduceDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceDoneOpGenericAdaptorBase; +public: + AllReduceDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllReduceDoneOpAdaptor : public AllReduceDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceDoneOpGenericAdaptor::AllReduceDoneOpGenericAdaptor; + AllReduceDoneOpAdaptor(AllReduceDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceDoneOpAdaptor; + template + using GenericAdaptor = AllReduceDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_reduce_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllReduceDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllReduceStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllReduceStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllReduceStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllReduceStartOpGenericAdaptorBase(AllReduceStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class AllReduceStartOpGenericAdaptor : public detail::AllReduceStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllReduceStartOpGenericAdaptorBase; +public: + AllReduceStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllReduceStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllReduceStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllReduceStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllReduceStartOpAdaptor : public AllReduceStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllReduceStartOpGenericAdaptor::AllReduceStartOpGenericAdaptor; + AllReduceStartOpAdaptor(AllReduceStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllReduceStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllReduceStartOpAdaptor; + template + using GenericAdaptor = AllReduceStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_reduce_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 5 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllReduceStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllToAllDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllDoneOpGenericAdaptorBase(AllToAllDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AllToAllDoneOpGenericAdaptor : public detail::AllToAllDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllDoneOpGenericAdaptorBase; +public: + AllToAllDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllDoneOpAdaptor : public AllToAllDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllDoneOpGenericAdaptor::AllToAllDoneOpGenericAdaptor; + AllToAllDoneOpAdaptor(AllToAllDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllDoneOpAdaptor; + template + using GenericAdaptor = AllToAllDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_to_all_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllToAllDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::AllToAllStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AllToAllStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AllToAllStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AllToAllStartOpGenericAdaptorBase(AllToAllStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); +}; +} // namespace detail +template +class AllToAllStartOpGenericAdaptor : public detail::AllToAllStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AllToAllStartOpGenericAdaptorBase; +public: + AllToAllStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AllToAllStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AllToAllStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AllToAllStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AllToAllStartOpAdaptor : public AllToAllStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using AllToAllStartOpGenericAdaptor::AllToAllStartOpGenericAdaptor; + AllToAllStartOpAdaptor(AllToAllStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AllToAllStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = AllToAllStartOpAdaptor; + template + using GenericAdaptor = AllToAllStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("split_dimension"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getSplitDimensionAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getSplitDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.all_to_all_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getSplitDimensionAttr(); + ::std::optional getSplitDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setSplitDimensionAttr(::mlir::IntegerAttr attr); + void setSplitDimension(::std::optional attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + ::mlir::Attribute removeSplitDimensionAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, /*optional*/::mlir::IntegerAttr split_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::AllToAllStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CholeskyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CholeskyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CholeskyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CholeskyOpGenericAdaptorBase(CholeskyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getIsLowerAttr(); + bool getIsLower(); +}; +} // namespace detail +template +class CholeskyOpGenericAdaptor : public detail::CholeskyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CholeskyOpGenericAdaptorBase; +public: + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CholeskyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CholeskyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(2).begin()); + } + + ValueT getInfo() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CholeskyOpAdaptor : public CholeskyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CholeskyOpGenericAdaptor::CholeskyOpGenericAdaptor; + CholeskyOpAdaptor(CholeskyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CholeskyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CholeskyOpAdaptor; + template + using GenericAdaptor = CholeskyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("is_lower")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIsLowerAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIsLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cholesky"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getInfo(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::OpOperand &getInfoMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getIsLowerAttr(); + bool getIsLower(); + void setIsLowerAttr(::mlir::BoolAttr attr); + void setIsLower(bool attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, ::mlir::BoolAttr is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, ::mlir::BoolAttr is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, bool is_lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output, ::mlir::Value scratch, ::mlir::Value info, bool is_lower); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CholeskyOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CollectivePermuteDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteDoneOpGenericAdaptorBase(CollectivePermuteDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CollectivePermuteDoneOpGenericAdaptor : public detail::CollectivePermuteDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteDoneOpGenericAdaptorBase; +public: + CollectivePermuteDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteDoneOpAdaptor : public CollectivePermuteDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteDoneOpGenericAdaptor::CollectivePermuteDoneOpGenericAdaptor; + CollectivePermuteDoneOpAdaptor(CollectivePermuteDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteDoneOpAdaptor; + template + using GenericAdaptor = CollectivePermuteDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.collective_permute_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CollectivePermuteDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CollectivePermuteStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CollectivePermuteStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CollectivePermuteStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CollectivePermuteStartOpGenericAdaptorBase(CollectivePermuteStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); +}; +} // namespace detail +template +class CollectivePermuteStartOpGenericAdaptor : public detail::CollectivePermuteStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CollectivePermuteStartOpGenericAdaptorBase; +public: + CollectivePermuteStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CollectivePermuteStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CollectivePermuteStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CollectivePermuteStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CollectivePermuteStartOpAdaptor : public CollectivePermuteStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using CollectivePermuteStartOpGenericAdaptor::CollectivePermuteStartOpGenericAdaptor; + CollectivePermuteStartOpAdaptor(CollectivePermuteStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CollectivePermuteStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CollectivePermuteStartOpAdaptor; + template + using GenericAdaptor = CollectivePermuteStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("source_target_pairs")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getSourceTargetPairsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getSourceTargetPairsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.collective_permute_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::DenseIntElementsAttr getSourceTargetPairsAttr(); + ::mlir::DenseIntElementsAttr getSourceTargetPairs(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + void setSourceTargetPairsAttr(::mlir::DenseIntElementsAttr attr); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + ::mlir::Attribute removeChannelIdAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, ::mlir::BoolAttr is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, bool is_sync); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr source_target_pairs, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, bool is_sync); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CollectivePermuteStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvBackwardFilterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvBackwardFilterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvBackwardFilterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvBackwardFilterOpGenericAdaptorBase(ConvBackwardFilterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvBackwardFilterOpGenericAdaptor : public detail::ConvBackwardFilterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvBackwardFilterOpGenericAdaptorBase; +public: + ConvBackwardFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvBackwardFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvBackwardFilterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvBackwardFilterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getDOutput() { + return (*getODSOperands(1).begin()); + } + + ValueT getDFilter() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvBackwardFilterOpAdaptor : public ConvBackwardFilterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvBackwardFilterOpGenericAdaptor::ConvBackwardFilterOpGenericAdaptor; + ConvBackwardFilterOpAdaptor(ConvBackwardFilterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvBackwardFilterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvBackwardFilterOpAdaptor; + template + using GenericAdaptor = ConvBackwardFilterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_backwardfilter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getDFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::OpOperand &getDFilterMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value d_output, ::mlir::Value d_filter, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvBackwardFilterOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvBackwardInputOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvBackwardInputOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvBackwardInputOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvBackwardInputOpGenericAdaptorBase(ConvBackwardInputOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvBackwardInputOpGenericAdaptor : public detail::ConvBackwardInputOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvBackwardInputOpGenericAdaptorBase; +public: + ConvBackwardInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvBackwardInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvBackwardInputOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvBackwardInputOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getDOutput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getDInput() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvBackwardInputOpAdaptor : public ConvBackwardInputOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvBackwardInputOpGenericAdaptor::ConvBackwardInputOpGenericAdaptor; + ConvBackwardInputOpAdaptor(ConvBackwardInputOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvBackwardInputOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvBackwardInputOpAdaptor; + template + using GenericAdaptor = ConvBackwardInputOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_backwardinput"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getDInput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getDInputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value d_output, ::mlir::Value filter, ::mlir::Value d_input, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvBackwardInputOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardFusedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardFusedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardFusedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardFusedOpGenericAdaptorBase(ConvForwardFusedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getLeakyreluAlphaAttr(); + ::llvm::APFloat getLeakyreluAlpha(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardFusedOpGenericAdaptor : public detail::ConvForwardFusedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardFusedOpGenericAdaptorBase; +public: + ConvForwardFusedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardFusedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardFusedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardFusedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getBias() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardFusedOpAdaptor : public ConvForwardFusedOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardFusedOpGenericAdaptor::ConvForwardFusedOpGenericAdaptor; + ConvForwardFusedOpAdaptor(ConvForwardFusedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardFusedOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardFusedOpAdaptor; + template + using GenericAdaptor = ConvForwardFusedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("activation_mode"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("leakyrelu_alpha"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getActivationModeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getActivationModeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getLeakyreluAlphaAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getLeakyreluAlphaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_fused"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getBiasMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getLeakyreluAlphaAttr(); + ::llvm::APFloat getLeakyreluAlpha(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setActivationModeAttr(::mlir::lmhlo_gpu::ActivationAttr attr); + void setActivationMode(::mlir::lmhlo_gpu::Activation attrValue); + void setLeakyreluAlphaAttr(::mlir::FloatAttr attr); + void setLeakyreluAlpha(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat leakyrelu_alpha, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 13 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardFusedOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardFusedSideInputOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardFusedSideInputOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardFusedSideInputOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardFusedSideInputOpGenericAdaptorBase(ConvForwardFusedSideInputOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getSideInputScaleAttr(); + ::llvm::APFloat getSideInputScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardFusedSideInputOpGenericAdaptor : public detail::ConvForwardFusedSideInputOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardFusedSideInputOpGenericAdaptorBase; +public: + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardFusedSideInputOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardFusedSideInputOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getBias() { + return (*getODSOperands(2).begin()); + } + + ValueT getSideInput() { + return (*getODSOperands(3).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(4).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardFusedSideInputOpAdaptor : public ConvForwardFusedSideInputOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardFusedSideInputOpGenericAdaptor::ConvForwardFusedSideInputOpGenericAdaptor; + ConvForwardFusedSideInputOpAdaptor(ConvForwardFusedSideInputOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardFusedSideInputOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardFusedSideInputOpAdaptor; + template + using GenericAdaptor = ConvForwardFusedSideInputOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("activation_mode"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("side_input_scale"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getActivationModeAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getActivationModeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getSideInputScaleAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getSideInputScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_fused_with_side_input"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getSideInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getBiasMutable(); + ::mlir::OpOperand &getSideInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ActivationAttr getActivationModeAttr(); + ::mlir::lmhlo_gpu::Activation getActivationMode(); + ::mlir::FloatAttr getSideInputScaleAttr(); + ::llvm::APFloat getSideInputScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setActivationModeAttr(::mlir::lmhlo_gpu::ActivationAttr attr); + void setActivationMode(::mlir::lmhlo_gpu::Activation attrValue); + void setSideInputScaleAttr(::mlir::FloatAttr attr); + void setSideInputScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ActivationAttr activation_mode, ::mlir::FloatAttr side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value bias, ::mlir::Value side_input, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::Activation activation_mode, ::llvm::APFloat side_input_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 13 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardFusedSideInputOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardGraphOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardGraphOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardGraphOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardGraphOpGenericAdaptorBase(ConvForwardGraphOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::IntegerAttr getNAuxOutputsAttr(); + uint32_t getNAuxOutputs(); + ::mlir::StringAttr getSerializedGraphAttr(); + ::llvm::StringRef getSerializedGraph(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardGraphOpGenericAdaptor : public detail::ConvForwardGraphOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardGraphOpGenericAdaptorBase; +public: + ConvForwardGraphOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardGraphOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardGraphOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardGraphOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + RangeT getBinaryOperands() { + return getODSOperands(2); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getAuxOutputs() { + return getODSOperands(4); + } + + ValueT getScratch() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardGraphOpAdaptor : public ConvForwardGraphOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardGraphOpGenericAdaptor::ConvForwardGraphOpGenericAdaptor; + ConvForwardGraphOpAdaptor(ConvForwardGraphOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardGraphOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardGraphOpAdaptor; + template + using GenericAdaptor = ConvForwardGraphOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("n_aux_outputs"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("serialized_graph"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getNAuxOutputsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getNAuxOutputsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + ::mlir::StringAttr getSerializedGraphAttrName() { + return getAttributeNameForIndex(11); + } + + static ::mlir::StringAttr getSerializedGraphAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 11); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(12); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 12); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(13); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 13); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward_graph"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::Operation::operand_range getBinaryOperands(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::Operation::operand_range getAuxOutputs(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::MutableOperandRange getBinaryOperandsMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::MutableOperandRange getAuxOutputsMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::IntegerAttr getNAuxOutputsAttr(); + uint32_t getNAuxOutputs(); + ::mlir::StringAttr getSerializedGraphAttr(); + ::llvm::StringRef getSerializedGraph(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setNAuxOutputsAttr(::mlir::IntegerAttr attr); + void setNAuxOutputs(uint32_t attrValue); + void setSerializedGraphAttr(::mlir::StringAttr attr); + void setSerializedGraph(::llvm::StringRef attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::IntegerAttr n_aux_outputs, ::mlir::StringAttr serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::IntegerAttr n_aux_outputs, ::mlir::StringAttr serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, uint32_t n_aux_outputs, ::llvm::StringRef serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::ValueRange binary_operands, ::mlir::Value output, ::mlir::ValueRange aux_outputs, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, uint32_t n_aux_outputs, ::llvm::StringRef serialized_graph, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 14 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardGraphOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ConvForwardOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvForwardOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvForwardOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvForwardOpGenericAdaptorBase(ConvForwardOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); +}; +} // namespace detail +template +class ConvForwardOpGenericAdaptor : public detail::ConvForwardOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvForwardOpGenericAdaptorBase; +public: + ConvForwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvForwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvForwardOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvForwardOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilter() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvForwardOpAdaptor : public ConvForwardOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvForwardOpGenericAdaptor::ConvForwardOpGenericAdaptor; + ConvForwardOpAdaptor(ConvForwardOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvForwardOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvForwardOpAdaptor; + template + using GenericAdaptor = ConvForwardOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config"), ::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("result_scale"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getResultScaleAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getResultScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(10); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 10); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.conv_forward"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilter(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getFilterMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getResultScaleAttr(); + ::llvm::APFloat getResultScale(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfigAttr(); + ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr getBackendConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setResultScaleAttr(::mlir::FloatAttr attr); + void setResultScale(::llvm::APFloat attrValue); + void setBackendConfigAttr(::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value filter, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat result_scale, ::mlir::lmhlo_gpu::ConvolutionBackendConfigAttr backend_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 11 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ConvForwardOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CublasLtMatmulF8Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CublasLtMatmulF8OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CublasLtMatmulF8OpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CublasLtMatmulF8OpGenericAdaptorBase(CublasLtMatmulF8Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); +}; +} // namespace detail +template +class CublasLtMatmulF8OpGenericAdaptor : public detail::CublasLtMatmulF8OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CublasLtMatmulF8OpGenericAdaptorBase; +public: + CublasLtMatmulF8OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CublasLtMatmulF8OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CublasLtMatmulF8OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CublasLtMatmulF8OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + ValueT getAScale() { + return (*getODSOperands(3).begin()); + } + + ValueT getBScale() { + return (*getODSOperands(4).begin()); + } + + ValueT getCScale() { + return (*getODSOperands(5).begin()); + } + + ValueT getDScale() { + return (*getODSOperands(6).begin()); + } + + ValueT getD() { + return (*getODSOperands(7).begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(8); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getDAmax() { + auto operands = getODSOperands(9); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CublasLtMatmulF8OpAdaptor : public CublasLtMatmulF8OpGenericAdaptor<::mlir::ValueRange> { +public: + using CublasLtMatmulF8OpGenericAdaptor::CublasLtMatmulF8OpGenericAdaptor; + CublasLtMatmulF8OpAdaptor(CublasLtMatmulF8Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CublasLtMatmulF8Op : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CublasLtMatmulF8OpAdaptor; + template + using GenericAdaptor = CublasLtMatmulF8OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("epilogue"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getEpilogueAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getEpilogueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cublas.lt.matmul.f8"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::TypedValue<::mlir::MemRefType> getAScale(); + ::mlir::TypedValue<::mlir::MemRefType> getBScale(); + ::mlir::TypedValue<::mlir::MemRefType> getCScale(); + ::mlir::TypedValue<::mlir::MemRefType> getDScale(); + ::mlir::TypedValue<::mlir::MemRefType> getD(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getDAmax(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + ::mlir::OpOperand &getAScaleMutable(); + ::mlir::OpOperand &getBScaleMutable(); + ::mlir::OpOperand &getCScaleMutable(); + ::mlir::OpOperand &getDScaleMutable(); + ::mlir::OpOperand &getDMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::MutableOperandRange getDAmaxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setEpilogueAttr(::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr attr); + void setEpilogue(::mlir::lmhlo_gpu::CublasLtMatmulEpilogue attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(uint64_t attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value a_scale, ::mlir::Value b_scale, ::mlir::Value c_scale, ::mlir::Value d_scale, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value d_amax, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 8 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CublasLtMatmulF8Op) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CublasLtMatmulOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CublasLtMatmulOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CublasLtMatmulOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CublasLtMatmulOpGenericAdaptorBase(CublasLtMatmulOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); +}; +} // namespace detail +template +class CublasLtMatmulOpGenericAdaptor : public detail::CublasLtMatmulOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CublasLtMatmulOpGenericAdaptorBase; +public: + CublasLtMatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CublasLtMatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CublasLtMatmulOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CublasLtMatmulOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + ValueT getD() { + return (*getODSOperands(3).begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(4); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getAux() { + auto operands = getODSOperands(5); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CublasLtMatmulOpAdaptor : public CublasLtMatmulOpGenericAdaptor<::mlir::ValueRange> { +public: + using CublasLtMatmulOpGenericAdaptor::CublasLtMatmulOpGenericAdaptor; + CublasLtMatmulOpAdaptor(CublasLtMatmulOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CublasLtMatmulOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CublasLtMatmulOpAdaptor; + template + using GenericAdaptor = CublasLtMatmulOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("epilogue"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getEpilogueAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getEpilogueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cublas.lt.matmul"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::TypedValue<::mlir::MemRefType> getD(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getAux(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + ::mlir::OpOperand &getDMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::MutableOperandRange getAuxMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr getEpilogueAttr(); + ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue getEpilogue(); + ::mlir::IntegerAttr getAlgorithmAttr(); + uint64_t getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setEpilogueAttr(::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr attr); + void setEpilogue(::mlir::lmhlo_gpu::CublasLtMatmulEpilogue attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(uint64_t attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogueAttr epilogue, ::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::Value d, /*optional*/::mlir::Value bias, /*optional*/::mlir::Value aux, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, ::mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue, uint64_t algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 8 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CublasLtMatmulOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CudnnConvReorderFilterAndBiasOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CudnnConvReorderFilterAndBiasOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CudnnConvReorderFilterAndBiasOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CudnnConvReorderFilterAndBiasOpGenericAdaptorBase(CudnnConvReorderFilterAndBiasOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); +}; +} // namespace detail +template +class CudnnConvReorderFilterAndBiasOpGenericAdaptor : public detail::CudnnConvReorderFilterAndBiasOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CudnnConvReorderFilterAndBiasOpGenericAdaptorBase; +public: + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CudnnConvReorderFilterAndBiasOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CudnnConvReorderFilterAndBiasOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getFilterInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getBiasInput() { + return (*getODSOperands(1).begin()); + } + + ValueT getFilterOutput() { + return (*getODSOperands(2).begin()); + } + + ValueT getBiasOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CudnnConvReorderFilterAndBiasOpAdaptor : public CudnnConvReorderFilterAndBiasOpGenericAdaptor<::mlir::ValueRange> { +public: + using CudnnConvReorderFilterAndBiasOpGenericAdaptor::CudnnConvReorderFilterAndBiasOpGenericAdaptor; + CudnnConvReorderFilterAndBiasOpAdaptor(CudnnConvReorderFilterAndBiasOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CudnnConvReorderFilterAndBiasOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CudnnConvReorderFilterAndBiasOpAdaptor; + template + using GenericAdaptor = CudnnConvReorderFilterAndBiasOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("filter_dims")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFilterDimsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFilterDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cudnn_conv_reorder_filter_and_bias"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getFilterInput(); + ::mlir::TypedValue<::mlir::MemRefType> getBiasInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilterOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getBiasOutput(); + ::mlir::OpOperand &getFilterInputMutable(); + ::mlir::OpOperand &getBiasInputMutable(); + ::mlir::OpOperand &getFilterOutputMutable(); + ::mlir::OpOperand &getBiasOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); + void setFilterDimsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value filter_input, ::mlir::Value bias_input, ::mlir::Value filter_output, ::mlir::Value bias_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value filter_input, ::mlir::Value bias_input, ::mlir::Value filter_output, ::mlir::Value bias_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CudnnConvReorderFilterAndBiasOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::CudnnConvReorderFilterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CudnnConvReorderFilterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CudnnConvReorderFilterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CudnnConvReorderFilterOpGenericAdaptorBase(CudnnConvReorderFilterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); +}; +} // namespace detail +template +class CudnnConvReorderFilterOpGenericAdaptor : public detail::CudnnConvReorderFilterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CudnnConvReorderFilterOpGenericAdaptorBase; +public: + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CudnnConvReorderFilterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CudnnConvReorderFilterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getFilterInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getFilterOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CudnnConvReorderFilterOpAdaptor : public CudnnConvReorderFilterOpGenericAdaptor<::mlir::ValueRange> { +public: + using CudnnConvReorderFilterOpGenericAdaptor::CudnnConvReorderFilterOpGenericAdaptor; + CudnnConvReorderFilterOpAdaptor(CudnnConvReorderFilterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CudnnConvReorderFilterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CudnnConvReorderFilterOpAdaptor; + template + using GenericAdaptor = CudnnConvReorderFilterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("filter_dims")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFilterDimsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFilterDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.cudnn_conv_reorder_filter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getFilterInput(); + ::mlir::TypedValue<::mlir::MemRefType> getFilterOutput(); + ::mlir::OpOperand &getFilterInputMutable(); + ::mlir::OpOperand &getFilterOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getFilterDimsAttr(); + ::mlir::DenseIntElementsAttr getFilterDims(); + void setFilterDimsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value filter_input, ::mlir::Value filter_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value filter_input, ::mlir::Value filter_output, ::mlir::DenseIntElementsAttr filter_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::CudnnConvReorderFilterOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::GEMMOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GEMMOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GEMMOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GEMMOpGenericAdaptorBase(GEMMOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::IntegerAttr getAlgorithmAttr(); + ::std::optional getAlgorithm(); +}; +} // namespace detail +template +class GEMMOpGenericAdaptor : public detail::GEMMOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GEMMOpGenericAdaptorBase; +public: + GEMMOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GEMMOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GEMMOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GEMMOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getC() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GEMMOpAdaptor : public GEMMOpGenericAdaptor<::mlir::ValueRange> { +public: + using GEMMOpGenericAdaptor::GEMMOpGenericAdaptor; + GEMMOpAdaptor(GEMMOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GEMMOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GEMMOpAdaptor; + template + using GenericAdaptor = GEMMOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm"), ::llvm::StringRef("alpha_imag"), ::llvm::StringRef("alpha_real"), ::llvm::StringRef("beta"), ::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getAlphaImagAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getAlphaImagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getAlphaRealAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getAlphaRealAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBetaAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBetaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.gemm"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getC(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getCMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + ::mlir::FloatAttr getAlphaRealAttr(); + ::llvm::APFloat getAlphaReal(); + ::mlir::FloatAttr getAlphaImagAttr(); + ::llvm::APFloat getAlphaImag(); + ::mlir::FloatAttr getBetaAttr(); + ::llvm::APFloat getBeta(); + ::mlir::IntegerAttr getAlgorithmAttr(); + ::std::optional getAlgorithm(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + void setAlphaRealAttr(::mlir::FloatAttr attr); + void setAlphaReal(::llvm::APFloat attrValue); + void setAlphaImagAttr(::mlir::FloatAttr attr); + void setAlphaImag(::llvm::APFloat attrValue); + void setBetaAttr(::mlir::FloatAttr attr); + void setBeta(::llvm::APFloat attrValue); + void setAlgorithmAttr(::mlir::IntegerAttr attr); + void setAlgorithm(::std::optional attrValue); + ::mlir::Attribute removePrecisionConfigAttr(); + ::mlir::Attribute removeAlgorithmAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::FloatAttr alpha_real, ::mlir::FloatAttr alpha_imag, ::mlir::FloatAttr beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value c, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::llvm::APFloat alpha_real, ::llvm::APFloat alpha_imag, ::llvm::APFloat beta, /*optional*/::mlir::IntegerAttr algorithm); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::GEMMOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ReduceScatterDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceScatterDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceScatterDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceScatterDoneOpGenericAdaptorBase(ReduceScatterDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReduceScatterDoneOpGenericAdaptor : public detail::ReduceScatterDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceScatterDoneOpGenericAdaptorBase; +public: + ReduceScatterDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceScatterDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceScatterDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceScatterDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceScatterDoneOpAdaptor : public ReduceScatterDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceScatterDoneOpGenericAdaptor::ReduceScatterDoneOpGenericAdaptor; + ReduceScatterDoneOpAdaptor(ReduceScatterDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceScatterDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceScatterDoneOpAdaptor; + template + using GenericAdaptor = ReduceScatterDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.reduce_scatter_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ReduceScatterDoneOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::ReduceScatterStartOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceScatterStartOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceScatterStartOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceScatterStartOpGenericAdaptorBase(ReduceScatterStartOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceScatterStartOpGenericAdaptor : public detail::ReduceScatterStartOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceScatterStartOpGenericAdaptorBase; +public: + ReduceScatterStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceScatterStartOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceScatterStartOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceScatterStartOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutputs() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceScatterStartOpAdaptor : public ReduceScatterStartOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceScatterStartOpGenericAdaptor::ReduceScatterStartOpGenericAdaptor; + ReduceScatterStartOpAdaptor(ReduceScatterStartOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceScatterStartOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceScatterStartOpAdaptor; + template + using GenericAdaptor = ReduceScatterStartOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_id"), ::llvm::StringRef("constrain_layout"), ::llvm::StringRef("is_sync"), ::llvm::StringRef("replica_groups"), ::llvm::StringRef("scatter_dimension"), ::llvm::StringRef("use_global_device_ids")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelIdAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelIdAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getConstrainLayoutAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getConstrainLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsSyncAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsSyncAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getReplicaGroupsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getReplicaGroupsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getScatterDimensionAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getScatterDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getUseGlobalDeviceIdsAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getUseGlobalDeviceIdsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.reduce_scatter_start"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getReplicaGroupsAttr(); + ::mlir::DenseIntElementsAttr getReplicaGroups(); + ::mlir::BoolAttr getConstrainLayoutAttr(); + bool getConstrainLayout(); + ::mlir::mhlo::ChannelHandleAttr getChannelIdAttr(); + ::std::optional<::mlir::mhlo::ChannelHandleAttr> getChannelId(); + ::mlir::BoolAttr getUseGlobalDeviceIdsAttr(); + bool getUseGlobalDeviceIds(); + ::mlir::BoolAttr getIsSyncAttr(); + bool getIsSync(); + ::mlir::IntegerAttr getScatterDimensionAttr(); + uint64_t getScatterDimension(); + void setReplicaGroupsAttr(::mlir::DenseIntElementsAttr attr); + void setConstrainLayoutAttr(::mlir::BoolAttr attr); + void setConstrainLayout(::std::optional attrValue); + void setChannelIdAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setUseGlobalDeviceIdsAttr(::mlir::BoolAttr attr); + void setUseGlobalDeviceIds(::std::optional attrValue); + void setIsSyncAttr(::mlir::BoolAttr attr); + void setIsSync(bool attrValue); + void setScatterDimensionAttr(::mlir::IntegerAttr attr); + void setScatterDimension(uint64_t attrValue); + ::mlir::Attribute removeConstrainLayoutAttr(); + ::mlir::Attribute removeChannelIdAttr(); + ::mlir::Attribute removeUseGlobalDeviceIdsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/::mlir::BoolAttr constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/::mlir::BoolAttr use_global_device_ids, ::mlir::BoolAttr is_sync, ::mlir::IntegerAttr scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t scatter_dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange outputs, ::mlir::DenseIntElementsAttr replica_groups, /*optional*/bool constrain_layout, /*optional*/::mlir::mhlo::ChannelHandleAttr channel_id, /*optional*/bool use_global_device_ids, bool is_sync, uint64_t scatter_dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::ReduceScatterStartOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::fusedMHABackwardOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class fusedMHABackwardOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + fusedMHABackwardOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + fusedMHABackwardOpGenericAdaptorBase(fusedMHABackwardOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbers(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); +}; +} // namespace detail +template +class fusedMHABackwardOpGenericAdaptor : public detail::fusedMHABackwardOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::fusedMHABackwardOpGenericAdaptorBase; +public: + fusedMHABackwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + fusedMHABackwardOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : fusedMHABackwardOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + fusedMHABackwardOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBmm1GradGemm1Rhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getBmm1GradGemm2Rhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getBmm2GradGemm2Rhs() { + return (*getODSOperands(2).begin()); + } + + ValueT getBmm2GradGemm1Lhs() { + return (*getODSOperands(3).begin()); + } + + ValueT getDOutput() { + return (*getODSOperands(4).begin()); + } + + ValueT getMask() { + auto operands = getODSOperands(5); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getDBmm1Lhs() { + return (*getODSOperands(6).begin()); + } + + ValueT getDBmm1Rhs() { + return (*getODSOperands(7).begin()); + } + + ValueT getDBmm2Rhs() { + return (*getODSOperands(8).begin()); + } + + ValueT getD_S() { + return (*getODSOperands(9).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(10).begin()); + } + + ValueT getDBias() { + auto operands = getODSOperands(11); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class fusedMHABackwardOpAdaptor : public fusedMHABackwardOpGenericAdaptor<::mlir::ValueRange> { +public: + using fusedMHABackwardOpGenericAdaptor::fusedMHABackwardOpGenericAdaptor; + fusedMHABackwardOpAdaptor(fusedMHABackwardOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class fusedMHABackwardOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = fusedMHABackwardOpAdaptor; + template + using GenericAdaptor = fusedMHABackwardOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm_config"), ::llvm::StringRef("bmm1_grad_gemm1_dot_dimension_numbers"), ::llvm::StringRef("bmm1_grad_gemm2_dot_dimension_numbers"), ::llvm::StringRef("bmm2_grad_gemm1_dot_dimension_numbers"), ::llvm::StringRef("bmm2_grad_gemm2_dot_dimension_numbers"), ::llvm::StringRef("dropout_rate"), ::llvm::StringRef("fmha_scale"), ::llvm::StringRef("fused_mha_dag"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("seed")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBmm1GradGemm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBmm1GradGemm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBmm1GradGemm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBmm1GradGemm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getBmm2GradGemm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getBmm2GradGemm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getBmm2GradGemm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getBmm2GradGemm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getDropoutRateAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getDropoutRateAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getFmhaScaleAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getFmhaScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getFusedMhaDagAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getFusedMhaDagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getSeedAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getSeedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.fMHABackward"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getBmm1GradGemm1Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm1GradGemm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm2GradGemm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getBmm2GradGemm1Lhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getMask(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm1Lhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm1Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDBmm2Rhs(); + ::mlir::TypedValue<::mlir::MemRefType> getD_S(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getDBias(); + ::mlir::OpOperand &getBmm1GradGemm1RhsMutable(); + ::mlir::OpOperand &getBmm1GradGemm2RhsMutable(); + ::mlir::OpOperand &getBmm2GradGemm2RhsMutable(); + ::mlir::OpOperand &getBmm2GradGemm1LhsMutable(); + ::mlir::OpOperand &getDOutputMutable(); + ::mlir::MutableOperandRange getMaskMutable(); + ::mlir::OpOperand &getDBmm1LhsMutable(); + ::mlir::OpOperand &getDBmm1RhsMutable(); + ::mlir::OpOperand &getDBmm2RhsMutable(); + ::mlir::OpOperand &getD_SMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::MutableOperandRange getDBiasMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1GradGemm2DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2GradGemm2DotDimensionNumbers(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); + void setBmm1GradGemm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm1GradGemm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2GradGemm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2GradGemm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setFmhaScaleAttr(::mlir::FloatAttr attr); + void setFmhaScale(::llvm::APFloat attrValue); + void setFusedMhaDagAttr(::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr attr); + void setFusedMhaDag(::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature attrValue); + void setAlgorithmConfigAttr(::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr attr); + void setDropoutRateAttr(::mlir::FloatAttr attr); + void setDropoutRate(::std::optional<::llvm::APFloat> attrValue); + void setSeedAttr(::mlir::IntegerAttr attr); + void setSeed(::std::optional attrValue); + ::mlir::Attribute removeDropoutRateAttr(); + ::mlir::Attribute removeSeedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value bmm1_grad_gemm1_rhs, ::mlir::Value bmm1_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm2_rhs, ::mlir::Value bmm2_grad_gemm1_lhs, ::mlir::Value d_output, /*optional*/::mlir::Value mask, ::mlir::Value d_bmm1_lhs, ::mlir::Value d_bmm1_rhs, ::mlir::Value d_bmm2_rhs, ::mlir::Value d_S, ::mlir::Value scratch, /*optional*/::mlir::Value d_bias, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_grad_gemm2_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_grad_gemm2_dot_dimension_numbers, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaBackwardDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 10 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::fusedMHABackwardOp) + +namespace mlir { +namespace lmhlo_gpu { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo_gpu::fusedMHAOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class fusedMHAOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + fusedMHAOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + fusedMHAOpGenericAdaptorBase(fusedMHAOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbers(); + ::mlir::ArrayAttr getIntermediateTensorDimensionsAttr(); + ::mlir::ArrayAttr getIntermediateTensorDimensions(); + ::mlir::ArrayAttr getIntermediateTensorLayoutAttr(); + ::mlir::ArrayAttr getIntermediateTensorLayout(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); +}; +} // namespace detail +template +class fusedMHAOpGenericAdaptor : public detail::fusedMHAOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::fusedMHAOpGenericAdaptorBase; +public: + fusedMHAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + fusedMHAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : fusedMHAOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + fusedMHAOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhsBmm1() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhsBmm1() { + return (*getODSOperands(1).begin()); + } + + ValueT getRhsBmm2() { + return (*getODSOperands(2).begin()); + } + + ValueT getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getBias() { + auto operands = getODSOperands(4); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + ValueT getOutput() { + return (*getODSOperands(5).begin()); + } + + ValueT getScratch() { + return (*getODSOperands(6).begin()); + } + + ValueT getActivation() { + auto operands = getODSOperands(7); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class fusedMHAOpAdaptor : public fusedMHAOpGenericAdaptor<::mlir::ValueRange> { +public: + using fusedMHAOpGenericAdaptor::fusedMHAOpGenericAdaptor; + fusedMHAOpAdaptor(fusedMHAOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class fusedMHAOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = fusedMHAOpAdaptor; + template + using GenericAdaptor = fusedMHAOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("algorithm_config"), ::llvm::StringRef("bmm1_dot_dimension_numbers"), ::llvm::StringRef("bmm2_dot_dimension_numbers"), ::llvm::StringRef("dropout_rate"), ::llvm::StringRef("fmha_scale"), ::llvm::StringRef("fused_mha_dag"), ::llvm::StringRef("intermediate_tensor_dimensions"), ::llvm::StringRef("intermediate_tensor_layout"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("seed")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getAlgorithmConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getAlgorithmConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBmm1DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBmm1DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getBmm2DotDimensionNumbersAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getBmm2DotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getDropoutRateAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getDropoutRateAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getFmhaScaleAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getFmhaScaleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getFusedMhaDagAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getFusedMhaDagAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getIntermediateTensorDimensionsAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getIntermediateTensorDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getIntermediateTensorLayoutAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getIntermediateTensorLayoutAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + ::mlir::StringAttr getSeedAttrName() { + return getAttributeNameForIndex(9); + } + + static ::mlir::StringAttr getSeedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 9); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo_gpu.fMHA"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhsBmm1(); + ::mlir::TypedValue<::mlir::MemRefType> getRhsBmm1(); + ::mlir::TypedValue<::mlir::MemRefType> getRhsBmm2(); + ::mlir::TypedValue<::mlir::MemRefType> getMask(); + ::mlir::TypedValue<::mlir::MemRefType> getBias(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getScratch(); + ::mlir::TypedValue<::mlir::MemRefType> getActivation(); + ::mlir::OpOperand &getLhsBmm1Mutable(); + ::mlir::OpOperand &getRhsBmm1Mutable(); + ::mlir::OpOperand &getRhsBmm2Mutable(); + ::mlir::MutableOperandRange getMaskMutable(); + ::mlir::MutableOperandRange getBiasMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getScratchMutable(); + ::mlir::MutableOperandRange getActivationMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm1DotDimensionNumbers(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getBmm2DotDimensionNumbers(); + ::mlir::ArrayAttr getIntermediateTensorDimensionsAttr(); + ::mlir::ArrayAttr getIntermediateTensorDimensions(); + ::mlir::ArrayAttr getIntermediateTensorLayoutAttr(); + ::mlir::ArrayAttr getIntermediateTensorLayout(); + ::mlir::FloatAttr getFmhaScaleAttr(); + ::llvm::APFloat getFmhaScale(); + ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr getFusedMhaDagAttr(); + ::mlir::lmhlo_gpu::FusedMhaDagSignature getFusedMhaDag(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfigAttr(); + ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr getAlgorithmConfig(); + ::mlir::FloatAttr getDropoutRateAttr(); + ::std::optional< ::llvm::APFloat > getDropoutRate(); + ::mlir::IntegerAttr getSeedAttr(); + ::std::optional getSeed(); + void setBmm1DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setBmm2DotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setIntermediateTensorDimensionsAttr(::mlir::ArrayAttr attr); + void setIntermediateTensorLayoutAttr(::mlir::ArrayAttr attr); + void setFmhaScaleAttr(::mlir::FloatAttr attr); + void setFmhaScale(::llvm::APFloat attrValue); + void setFusedMhaDagAttr(::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr attr); + void setFusedMhaDag(::mlir::lmhlo_gpu::FusedMhaDagSignature attrValue); + void setAlgorithmConfigAttr(::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr attr); + void setDropoutRateAttr(::mlir::FloatAttr attr); + void setDropoutRate(::std::optional<::llvm::APFloat> attrValue); + void setSeedAttr(::mlir::IntegerAttr attr); + void setSeed(::std::optional attrValue); + ::mlir::Attribute removeDropoutRateAttr(); + ::mlir::Attribute removeSeedAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::mlir::FloatAttr fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignatureAttr fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs_bmm1, ::mlir::Value rhs_bmm1, ::mlir::Value rhs_bmm2, /*optional*/::mlir::Value mask, /*optional*/::mlir::Value bias, ::mlir::Value output, ::mlir::Value scratch, /*optional*/::mlir::Value activation, ::mlir::mhlo::DotDimensionNumbersAttr bmm1_dot_dimension_numbers, ::mlir::mhlo::DotDimensionNumbersAttr bmm2_dot_dimension_numbers, ::mlir::ArrayAttr intermediate_tensor_dimensions, ::mlir::ArrayAttr intermediate_tensor_layout, ::llvm::APFloat fmha_scale, ::mlir::lmhlo_gpu::FusedMhaDagSignature fused_mha_dag, ::mlir::lmhlo_gpu::FusedMHAAlgorithmConfigAttr algorithm_config, /*optional*/::mlir::FloatAttr dropout_rate, /*optional*/::mlir::IntegerAttr seed); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 10 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo_gpu +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo_gpu::fusedMHAOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_inc_gen/lhlo/IR/lhlo_ops.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_inc_gen/lhlo/IR/lhlo_ops.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..3981e3098c2b7a01b548b2925addaa16a31e9400 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_inc_gen/lhlo/IR/lhlo_ops.h.inc @@ -0,0 +1,13398 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: lhlo_ops.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES) +#undef GET_OP_FWD_DEFINES +namespace mlir { +namespace lmhlo { +class FusionOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class AbsOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class AddOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class AndOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class Atan2Op; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BatchNormGradOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BatchNormInferenceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BatchNormTrainingOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BitcastConvertOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BitcastOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BroadcastInDimOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class BroadcastOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CaseOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CbrtOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CeilOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CholeskyOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ClampOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ClzOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CompareOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ComplexOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ConcatenateOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ConstantOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ConvertOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ConvolutionOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CopyOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CosineOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CustomCallOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DivOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DotGeneralOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DotOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicBitcastOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicBroadcastInDimOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicConvOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicGatherOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicIotaOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicPadOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicReshapeOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicSliceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class DynamicUpdateSliceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ExpOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class Expm1Op; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class FftOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class FloorOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class GatherOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ImagOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class InfeedOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class IotaOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class IsFiniteOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class Log1pOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class LogOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class LogisticOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class MapOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class MaxOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class MinOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class MulOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class NegOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class NotOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class OrOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class OutfeedOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class PadOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class PartitionIdOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class PopulationCountOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class PowOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RealDynamicSliceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RealOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RecvDoneOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RecvOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReduceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReducePrecisionOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReduceWindowOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RemOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReplicaIdOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReshapeOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ReverseOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RngGetAndUpdateStateOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RoundNearestEvenOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RoundOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class RsqrtOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ScatterOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SelectAndScatterOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SelectOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SendDoneOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SendOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ShiftLeftOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ShiftRightArithmeticOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class ShiftRightLogicalOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SignOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SineOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SliceOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SortOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SqrtOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class SubtractOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class TanOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class TanhOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class TransposeOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class TriangularSolveOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class WhileOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class XorOp; +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +class TerminatorOp; +} // namespace lmhlo +} // namespace mlir +#endif + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::FusionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FusionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FusionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FusionOpGenericAdaptorBase(FusionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + ::mlir::Region &getRegion(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class FusionOpGenericAdaptor : public detail::FusionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FusionOpGenericAdaptorBase; +public: + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FusionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FusionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FusionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FusionOpAdaptor : public FusionOpGenericAdaptor<::mlir::ValueRange> { +public: + using FusionOpGenericAdaptor::FusionOpGenericAdaptor; + FusionOpAdaptor(FusionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FusionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::RegionBranchOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FusionOpAdaptor; + template + using GenericAdaptor = FusionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("backend_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.fusion"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getRegion(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + void setBackendConfigAttr(::mlir::Attribute attr); + ::mlir::Attribute removeBackendConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ArrayRef attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getSuccessorRegions(::mlir::RegionBranchPoint point, ::llvm::SmallVectorImpl<::mlir::RegionSuccessor> ®ions); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + SmallVector getInputBuffers() { + SmallVector buffers; + for (auto load : getRegion().front().getOps()) { + buffers.push_back(load.getMemref()); + } + return buffers; + } + + SmallVector getOutputBuffers() { + SmallVector buffers; + for (auto store : getRegion().front().getOps()) { + buffers.push_back(store.getMemref()); + } + return buffers; + } + + SmallVector getFusionParameters() { + SmallVector buffers; + for (auto load : getRegion().front().getOps()) { + buffers.push_back(load); + } + return buffers; + } + + SmallVector getFusionResults() { + SmallVector buffers; + for (auto store : getRegion().front().getOps()) { + buffers.push_back(store.getTensor()); + } + return buffers; + } + + SmallVector getFusionRoots() { + SmallVector roots; + for (auto value : getFusionResults()) { + Operation* op = value.getDefiningOp(); + if (roots.empty() || roots.back() != op) { + roots.push_back(op); + } + } + return roots; + } +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::FusionOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::AbsOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AbsOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AbsOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AbsOpGenericAdaptorBase(AbsOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class AbsOpGenericAdaptor : public detail::AbsOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AbsOpGenericAdaptorBase; +public: + AbsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AbsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AbsOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AbsOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AbsOpAdaptor : public AbsOpGenericAdaptor<::mlir::ValueRange> { +public: + using AbsOpGenericAdaptor::AbsOpGenericAdaptor; + AbsOpAdaptor(AbsOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AbsOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = AbsOpAdaptor; + template + using GenericAdaptor = AbsOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.abs"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::AbsOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::AddOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AddOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AddOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AddOpGenericAdaptorBase(AddOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class AddOpGenericAdaptor : public detail::AddOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AddOpGenericAdaptorBase; +public: + AddOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AddOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AddOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AddOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AddOpAdaptor : public AddOpGenericAdaptor<::mlir::ValueRange> { +public: + using AddOpGenericAdaptor::AddOpGenericAdaptor; + AddOpAdaptor(AddOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AddOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = AddOpAdaptor; + template + using GenericAdaptor = AddOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.add"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::AddOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::AndOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class AndOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + AndOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + AndOpGenericAdaptorBase(AndOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class AndOpGenericAdaptor : public detail::AndOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::AndOpGenericAdaptorBase; +public: + AndOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + AndOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : AndOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + AndOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class AndOpAdaptor : public AndOpGenericAdaptor<::mlir::ValueRange> { +public: + using AndOpGenericAdaptor::AndOpGenericAdaptor; + AndOpAdaptor(AndOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class AndOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = AndOpAdaptor; + template + using GenericAdaptor = AndOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.and"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::AndOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::Atan2Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Atan2OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Atan2OpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Atan2OpGenericAdaptorBase(Atan2Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class Atan2OpGenericAdaptor : public detail::Atan2OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Atan2OpGenericAdaptorBase; +public: + Atan2OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Atan2OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Atan2OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Atan2OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Atan2OpAdaptor : public Atan2OpGenericAdaptor<::mlir::ValueRange> { +public: + using Atan2OpGenericAdaptor::Atan2OpGenericAdaptor; + Atan2OpAdaptor(Atan2Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Atan2Op : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = Atan2OpAdaptor; + template + using GenericAdaptor = Atan2OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.atan2"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::Atan2Op) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BatchNormGradOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormGradOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormGradOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormGradOpGenericAdaptorBase(BatchNormGradOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormGradOpGenericAdaptor : public detail::BatchNormGradOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormGradOpGenericAdaptorBase; +public: + BatchNormGradOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormGradOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormGradOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormGradOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getMean() { + return (*getODSOperands(2).begin()); + } + + ValueT getVariance() { + return (*getODSOperands(3).begin()); + } + + ValueT getGradOutput() { + return (*getODSOperands(4).begin()); + } + + ValueT getGradOperand() { + return (*getODSOperands(5).begin()); + } + + ValueT getGradScale() { + return (*getODSOperands(6).begin()); + } + + ValueT getGradOffset() { + return (*getODSOperands(7).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormGradOpAdaptor : public BatchNormGradOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormGradOpGenericAdaptor::BatchNormGradOpGenericAdaptor; + BatchNormGradOpAdaptor(BatchNormGradOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormGradOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormGradOpAdaptor; + template + using GenericAdaptor = BatchNormGradOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.batch_norm_grad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getScale(); + ::mlir::TypedValue<::mlir::MemRefType> getMean(); + ::mlir::TypedValue<::mlir::MemRefType> getVariance(); + ::mlir::TypedValue<::mlir::MemRefType> getGradOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getGradOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getGradScale(); + ::mlir::TypedValue<::mlir::MemRefType> getGradOffset(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getMeanMutable(); + ::mlir::OpOperand &getVarianceMutable(); + ::mlir::OpOperand &getGradOutputMutable(); + ::mlir::OpOperand &getGradOperandMutable(); + ::mlir::OpOperand &getGradScaleMutable(); + ::mlir::OpOperand &getGradOffsetMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::Value grad_operand, ::mlir::Value grad_scale, ::mlir::Value grad_offset, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::Value grad_operand, ::mlir::Value grad_scale, ::mlir::Value grad_offset, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::Value grad_operand, ::mlir::Value grad_scale, ::mlir::Value grad_offset, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value grad_output, ::mlir::Value grad_operand, ::mlir::Value grad_scale, ::mlir::Value grad_offset, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BatchNormGradOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BatchNormInferenceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormInferenceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormInferenceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormInferenceOpGenericAdaptorBase(BatchNormInferenceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormInferenceOpGenericAdaptor : public detail::BatchNormInferenceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormInferenceOpGenericAdaptorBase; +public: + BatchNormInferenceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormInferenceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormInferenceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormInferenceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getOffset() { + return (*getODSOperands(2).begin()); + } + + ValueT getMean() { + return (*getODSOperands(3).begin()); + } + + ValueT getVariance() { + return (*getODSOperands(4).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormInferenceOpAdaptor : public BatchNormInferenceOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormInferenceOpGenericAdaptor::BatchNormInferenceOpGenericAdaptor; + BatchNormInferenceOpAdaptor(BatchNormInferenceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormInferenceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormInferenceOpAdaptor; + template + using GenericAdaptor = BatchNormInferenceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.batch_norm_inference"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getScale(); + ::mlir::TypedValue<::mlir::MemRefType> getOffset(); + ::mlir::TypedValue<::mlir::MemRefType> getMean(); + ::mlir::TypedValue<::mlir::MemRefType> getVariance(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getOffsetMutable(); + ::mlir::OpOperand &getMeanMutable(); + ::mlir::OpOperand &getVarianceMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value output, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value output, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value output, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value mean, ::mlir::Value variance, ::mlir::Value output, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BatchNormInferenceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BatchNormTrainingOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BatchNormTrainingOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BatchNormTrainingOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BatchNormTrainingOpGenericAdaptorBase(BatchNormTrainingOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); +}; +} // namespace detail +template +class BatchNormTrainingOpGenericAdaptor : public detail::BatchNormTrainingOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BatchNormTrainingOpGenericAdaptorBase; +public: + BatchNormTrainingOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BatchNormTrainingOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BatchNormTrainingOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BatchNormTrainingOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScale() { + return (*getODSOperands(1).begin()); + } + + ValueT getOffset() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + ValueT getBatchMean() { + return (*getODSOperands(4).begin()); + } + + ValueT getBatchVar() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BatchNormTrainingOpAdaptor : public BatchNormTrainingOpGenericAdaptor<::mlir::ValueRange> { +public: + using BatchNormTrainingOpGenericAdaptor::BatchNormTrainingOpGenericAdaptor; + BatchNormTrainingOpAdaptor(BatchNormTrainingOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BatchNormTrainingOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BatchNormTrainingOpAdaptor; + template + using GenericAdaptor = BatchNormTrainingOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("epsilon"), ::llvm::StringRef("feature_index")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEpsilonAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEpsilonAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFeatureIndexAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFeatureIndexAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.batch_norm_training"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getScale(); + ::mlir::TypedValue<::mlir::MemRefType> getOffset(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::TypedValue<::mlir::MemRefType> getBatchMean(); + ::mlir::TypedValue<::mlir::MemRefType> getBatchVar(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScaleMutable(); + ::mlir::OpOperand &getOffsetMutable(); + ::mlir::OpOperand &getOutputMutable(); + ::mlir::OpOperand &getBatchMeanMutable(); + ::mlir::OpOperand &getBatchVarMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::FloatAttr getEpsilonAttr(); + ::llvm::APFloat getEpsilon(); + ::mlir::IntegerAttr getFeatureIndexAttr(); + uint64_t getFeatureIndex(); + void setEpsilonAttr(::mlir::FloatAttr attr); + void setEpsilon(::llvm::APFloat attrValue); + void setFeatureIndexAttr(::mlir::IntegerAttr attr); + void setFeatureIndex(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value output, ::mlir::Value batch_mean, ::mlir::Value batch_var, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value output, ::mlir::Value batch_mean, ::mlir::Value batch_var, ::mlir::FloatAttr epsilon, ::mlir::IntegerAttr feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value output, ::mlir::Value batch_mean, ::mlir::Value batch_var, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scale, ::mlir::Value offset, ::mlir::Value output, ::mlir::Value batch_mean, ::mlir::Value batch_var, ::llvm::APFloat epsilon, uint64_t feature_index); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BatchNormTrainingOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BitcastConvertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BitcastConvertOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BitcastConvertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BitcastConvertOpGenericAdaptorBase(BitcastConvertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class BitcastConvertOpGenericAdaptor : public detail::BitcastConvertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BitcastConvertOpGenericAdaptorBase; +public: + BitcastConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BitcastConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BitcastConvertOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BitcastConvertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BitcastConvertOpAdaptor : public BitcastConvertOpGenericAdaptor<::mlir::ValueRange> { +public: + using BitcastConvertOpGenericAdaptor::BitcastConvertOpGenericAdaptor; + BitcastConvertOpAdaptor(BitcastConvertOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BitcastConvertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = BitcastConvertOpAdaptor; + template + using GenericAdaptor = BitcastConvertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.bitcast_convert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BitcastConvertOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BitcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BitcastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BitcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BitcastOpGenericAdaptorBase(BitcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class BitcastOpGenericAdaptor : public detail::BitcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BitcastOpGenericAdaptorBase; +public: + BitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BitcastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BitcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BitcastOpAdaptor : public BitcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BitcastOpGenericAdaptor::BitcastOpGenericAdaptor; + BitcastOpAdaptor(BitcastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BitcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BitcastOpAdaptor; + template + using GenericAdaptor = BitcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.bitcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BitcastOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BroadcastInDimOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BroadcastInDimOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BroadcastInDimOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BroadcastInDimOpGenericAdaptorBase(BroadcastInDimOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); +}; +} // namespace detail +template +class BroadcastInDimOpGenericAdaptor : public detail::BroadcastInDimOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BroadcastInDimOpGenericAdaptorBase; +public: + BroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BroadcastInDimOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BroadcastInDimOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BroadcastInDimOpAdaptor : public BroadcastInDimOpGenericAdaptor<::mlir::ValueRange> { +public: + using BroadcastInDimOpGenericAdaptor::BroadcastInDimOpGenericAdaptor; + BroadcastInDimOpAdaptor(BroadcastInDimOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BroadcastInDimOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BroadcastInDimOpAdaptor; + template + using GenericAdaptor = BroadcastInDimOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.broadcast_in_dim"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BroadcastInDimOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::BroadcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BroadcastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + BroadcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + BroadcastOpGenericAdaptorBase(BroadcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastSizesAttr(); + ::mlir::DenseIntElementsAttr getBroadcastSizes(); +}; +} // namespace detail +template +class BroadcastOpGenericAdaptor : public detail::BroadcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BroadcastOpGenericAdaptorBase; +public: + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BroadcastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + BroadcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BroadcastOpAdaptor : public BroadcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BroadcastOpGenericAdaptor::BroadcastOpGenericAdaptor; + BroadcastOpAdaptor(BroadcastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class BroadcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BroadcastOpAdaptor; + template + using GenericAdaptor = BroadcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.broadcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastSizesAttr(); + ::mlir::DenseIntElementsAttr getBroadcastSizes(); + void setBroadcastSizesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::BroadcastOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CaseOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CaseOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CaseOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CaseOpGenericAdaptorBase(CaseOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::RegionRange getBranches(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class CaseOpGenericAdaptor : public detail::CaseOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CaseOpGenericAdaptorBase; +public: + CaseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CaseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CaseOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CaseOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getIndex() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CaseOpAdaptor : public CaseOpGenericAdaptor<::mlir::ValueRange> { +public: + using CaseOpGenericAdaptor::CaseOpGenericAdaptor; + CaseOpAdaptor(CaseOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CaseOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::RegionBranchOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CaseOpAdaptor; + template + using GenericAdaptor = CaseOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.case"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getIndex(); + ::mlir::OpOperand &getIndexMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::MutableArrayRef<::mlir::Region> getBranches(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value index, unsigned branchesCount); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value index, unsigned branchesCount); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes, unsigned numRegions); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getSuccessorRegions(::mlir::RegionBranchPoint point, ::llvm::SmallVectorImpl<::mlir::RegionSuccessor> ®ions); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CaseOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CbrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CbrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CbrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CbrtOpGenericAdaptorBase(CbrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CbrtOpGenericAdaptor : public detail::CbrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CbrtOpGenericAdaptorBase; +public: + CbrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CbrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CbrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CbrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CbrtOpAdaptor : public CbrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using CbrtOpGenericAdaptor::CbrtOpGenericAdaptor; + CbrtOpAdaptor(CbrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CbrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = CbrtOpAdaptor; + template + using GenericAdaptor = CbrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.cbrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CbrtOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CeilOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CeilOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CeilOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CeilOpGenericAdaptorBase(CeilOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CeilOpGenericAdaptor : public detail::CeilOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CeilOpGenericAdaptorBase; +public: + CeilOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CeilOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CeilOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CeilOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CeilOpAdaptor : public CeilOpGenericAdaptor<::mlir::ValueRange> { +public: + using CeilOpGenericAdaptor::CeilOpGenericAdaptor; + CeilOpAdaptor(CeilOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CeilOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = CeilOpAdaptor; + template + using GenericAdaptor = CeilOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.ceil"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CeilOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CholeskyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CholeskyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CholeskyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CholeskyOpGenericAdaptorBase(CholeskyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); +}; +} // namespace detail +template +class CholeskyOpGenericAdaptor : public detail::CholeskyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CholeskyOpGenericAdaptorBase; +public: + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CholeskyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CholeskyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CholeskyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CholeskyOpAdaptor : public CholeskyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CholeskyOpGenericAdaptor::CholeskyOpGenericAdaptor; + CholeskyOpAdaptor(CholeskyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CholeskyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = CholeskyOpAdaptor; + template + using GenericAdaptor = CholeskyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("lower")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLowerAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.cholesky"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + void setLowerAttr(::mlir::BoolAttr attr); + void setLower(::std::optional attrValue); + ::mlir::Attribute removeLowerAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value output, /*optional*/::mlir::BoolAttr lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value output, /*optional*/::mlir::BoolAttr lower); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value output, /*optional*/bool lower = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value output, /*optional*/bool lower = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CholeskyOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ClampOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ClampOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ClampOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ClampOpGenericAdaptorBase(ClampOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ClampOpGenericAdaptor : public detail::ClampOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ClampOpGenericAdaptorBase; +public: + ClampOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ClampOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ClampOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ClampOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMin() { + return (*getODSOperands(0).begin()); + } + + ValueT getOperand() { + return (*getODSOperands(1).begin()); + } + + ValueT getMax() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ClampOpAdaptor : public ClampOpGenericAdaptor<::mlir::ValueRange> { +public: + using ClampOpGenericAdaptor::ClampOpGenericAdaptor; + ClampOpAdaptor(ClampOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ClampOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ClampOpAdaptor; + template + using GenericAdaptor = ClampOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.clamp"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getMin(); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getMax(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getMinMutable(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getMaxMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value min, ::mlir::Value operand, ::mlir::Value max, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value min, ::mlir::Value operand, ::mlir::Value max, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ClampOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ClzOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ClzOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ClzOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ClzOpGenericAdaptorBase(ClzOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ClzOpGenericAdaptor : public detail::ClzOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ClzOpGenericAdaptorBase; +public: + ClzOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ClzOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ClzOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ClzOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ClzOpAdaptor : public ClzOpGenericAdaptor<::mlir::ValueRange> { +public: + using ClzOpGenericAdaptor::ClzOpGenericAdaptor; + ClzOpAdaptor(ClzOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ClzOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ClzOpAdaptor; + template + using GenericAdaptor = ClzOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.count_leading_zeros"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ClzOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CompareOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CompareOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CompareOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CompareOpGenericAdaptorBase(CompareOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + ::mlir::mhlo::ComparisonDirectionAttr getComparisonDirectionAttr(); + ::mlir::mhlo::ComparisonDirection getComparisonDirection(); + ::mlir::mhlo::ComparisonTypeAttr getCompareTypeAttr(); + ::std::optional<::mlir::mhlo::ComparisonType> getCompareType(); +}; +} // namespace detail +template +class CompareOpGenericAdaptor : public detail::CompareOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CompareOpGenericAdaptorBase; +public: + CompareOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CompareOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CompareOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CompareOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CompareOpAdaptor : public CompareOpGenericAdaptor<::mlir::ValueRange> { +public: + using CompareOpGenericAdaptor::CompareOpGenericAdaptor; + CompareOpAdaptor(CompareOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CompareOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CompareOpAdaptor; + template + using GenericAdaptor = CompareOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions"), ::llvm::StringRef("compare_type"), ::llvm::StringRef("comparison_direction")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getCompareTypeAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getCompareTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getComparisonDirectionAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getComparisonDirectionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.compare"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + ::mlir::mhlo::ComparisonDirectionAttr getComparisonDirectionAttr(); + ::mlir::mhlo::ComparisonDirection getComparisonDirection(); + ::mlir::mhlo::ComparisonTypeAttr getCompareTypeAttr(); + ::std::optional<::mlir::mhlo::ComparisonType> getCompareType(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setComparisonDirectionAttr(::mlir::mhlo::ComparisonDirectionAttr attr); + void setComparisonDirection(::mlir::mhlo::ComparisonDirection attrValue); + void setCompareTypeAttr(::mlir::mhlo::ComparisonTypeAttr attr); + void setCompareType(::std::optional<::mlir::mhlo::ComparisonType> attrValue); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + ::mlir::Attribute removeCompareTypeAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions, ::mlir::mhlo::ComparisonDirectionAttr comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions, ::mlir::mhlo::ComparisonDirectionAttr comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions, ::mlir::mhlo::ComparisonDirection comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions, ::mlir::mhlo::ComparisonDirection comparison_direction, /*optional*/::mlir::mhlo::ComparisonTypeAttr compare_type); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CompareOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ComplexOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ComplexOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ComplexOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ComplexOpGenericAdaptorBase(ComplexOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class ComplexOpGenericAdaptor : public detail::ComplexOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ComplexOpGenericAdaptorBase; +public: + ComplexOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ComplexOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ComplexOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ComplexOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ComplexOpAdaptor : public ComplexOpGenericAdaptor<::mlir::ValueRange> { +public: + using ComplexOpGenericAdaptor::ComplexOpGenericAdaptor; + ComplexOpAdaptor(ComplexOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ComplexOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ComplexOpAdaptor; + template + using GenericAdaptor = ComplexOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.complex"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ComplexOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ConcatenateOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConcatenateOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConcatenateOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConcatenateOpGenericAdaptorBase(ConcatenateOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); +}; +} // namespace detail +template +class ConcatenateOpGenericAdaptor : public detail::ConcatenateOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConcatenateOpGenericAdaptorBase; +public: + ConcatenateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConcatenateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConcatenateOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConcatenateOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getVal() { + return getODSOperands(0); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConcatenateOpAdaptor : public ConcatenateOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConcatenateOpGenericAdaptor::ConcatenateOpGenericAdaptor; + ConcatenateOpAdaptor(ConcatenateOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConcatenateOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConcatenateOpAdaptor; + template + using GenericAdaptor = ConcatenateOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.concatenate"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getVal(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::MutableOperandRange getValMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange val, ::mlir::Value output, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange val, ::mlir::Value output, ::mlir::IntegerAttr dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange val, ::mlir::Value output, uint64_t dimension); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange val, ::mlir::Value output, uint64_t dimension); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ConcatenateOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ConstantOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConstantOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConstantOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConstantOpGenericAdaptorBase(ConstantOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::ElementsAttr getValueAttr(); + ::mlir::ElementsAttr getValue(); +}; +} // namespace detail +template +class ConstantOpGenericAdaptor : public detail::ConstantOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConstantOpGenericAdaptorBase; +public: + ConstantOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConstantOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConstantOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConstantOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOutput() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConstantOpAdaptor : public ConstantOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConstantOpGenericAdaptor::ConstantOpGenericAdaptor; + ConstantOpAdaptor(ConstantOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConstantOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ConstantOpAdaptor; + template + using GenericAdaptor = ConstantOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("value")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getValueAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getValueAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.constant"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::ElementsAttr getValueAttr(); + ::mlir::ElementsAttr getValue(); + void setValueAttr(::mlir::ElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ElementsAttr value, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ElementsAttr value, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ConstantOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ConvertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvertOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvertOpGenericAdaptorBase(ConvertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ConvertOpGenericAdaptor : public detail::ConvertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvertOpGenericAdaptorBase; +public: + ConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvertOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvertOpAdaptor : public ConvertOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvertOpGenericAdaptor::ConvertOpGenericAdaptor; + ConvertOpAdaptor(ConvertOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvertOpAdaptor; + template + using GenericAdaptor = ConvertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.convert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ConvertOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ConvolutionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConvolutionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ConvolutionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ConvolutionOpGenericAdaptorBase(ConvolutionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class ConvolutionOpGenericAdaptor : public detail::ConvolutionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConvolutionOpGenericAdaptorBase; +public: + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConvolutionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConvolutionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ConvolutionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConvolutionOpAdaptor : public ConvolutionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConvolutionOpGenericAdaptor::ConvolutionOpGenericAdaptor; + ConvolutionOpAdaptor(ConvolutionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ConvolutionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConvolutionOpAdaptor; + template + using GenericAdaptor = ConvolutionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.convolution"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 9 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: + bool hasWindowReversal() { + auto reversal = getWindowReversalAttr(); + return reversal && llvm::any_of(reversal.getValues(), + [](bool v) { return v; }); + } +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ConvolutionOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CopyOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CopyOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CopyOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CopyOpGenericAdaptorBase(CopyOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CopyOpGenericAdaptor : public detail::CopyOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CopyOpGenericAdaptorBase; +public: + CopyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CopyOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CopyOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CopyOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CopyOpAdaptor : public CopyOpGenericAdaptor<::mlir::ValueRange> { +public: + using CopyOpGenericAdaptor::CopyOpGenericAdaptor; + CopyOpAdaptor(CopyOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CopyOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::CopyOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CopyOpAdaptor; + template + using GenericAdaptor = CopyOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.copy"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + Value getSource() { return getOperand();} + Value getTarget() { return getOutput(); } +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CopyOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CosineOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CosineOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CosineOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CosineOpGenericAdaptorBase(CosineOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class CosineOpGenericAdaptor : public detail::CosineOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CosineOpGenericAdaptorBase; +public: + CosineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CosineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CosineOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CosineOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CosineOpAdaptor : public CosineOpGenericAdaptor<::mlir::ValueRange> { +public: + using CosineOpGenericAdaptor::CosineOpGenericAdaptor; + CosineOpAdaptor(CosineOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CosineOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = CosineOpAdaptor; + template + using GenericAdaptor = CosineOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.cosine"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CosineOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::CustomCallOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CustomCallOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + CustomCallOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + CustomCallOpGenericAdaptorBase(CustomCallOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getCallTargetNameAttr(); + ::llvm::StringRef getCallTargetName(); + ::mlir::BoolAttr getHasSideEffectAttr(); + bool getHasSideEffect(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + ::mlir::mhlo::CustomCallApiVersionAttr getApiVersionAttr(); + ::mlir::mhlo::CustomCallApiVersion getApiVersion(); + ::mlir::lmhlo::CustomCallTargetArgMappingAttr getTargetArgMappingAttr(); + ::std::optional<::mlir::lmhlo::CustomCallTargetArgMappingAttr> getTargetArgMapping(); + ::mlir::Region &getCalledComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class CustomCallOpGenericAdaptor : public detail::CustomCallOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CustomCallOpGenericAdaptorBase; +public: + CustomCallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CustomCallOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CustomCallOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + CustomCallOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getArgs() { + return getODSOperands(0); + } + + RangeT getOutput() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CustomCallOpAdaptor : public CustomCallOpGenericAdaptor<::mlir::ValueRange> { +public: + using CustomCallOpGenericAdaptor::CustomCallOpGenericAdaptor; + CustomCallOpAdaptor(CustomCallOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class CustomCallOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = CustomCallOpAdaptor; + template + using GenericAdaptor = CustomCallOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("api_version"), ::llvm::StringRef("backend_config"), ::llvm::StringRef("call_target_name"), ::llvm::StringRef("has_side_effect"), ::llvm::StringRef("operandSegmentSizes"), ::llvm::StringRef("target_arg_mapping")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getApiVersionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getApiVersionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getBackendConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getBackendConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getCallTargetNameAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getCallTargetNameAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getHasSideEffectAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getHasSideEffectAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getTargetArgMappingAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getTargetArgMappingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.custom_call"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getArgs(); + ::mlir::Operation::operand_range getOutput(); + ::mlir::MutableOperandRange getArgsMutable(); + ::mlir::MutableOperandRange getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getCalledComputation(); + ::mlir::StringAttr getCallTargetNameAttr(); + ::llvm::StringRef getCallTargetName(); + ::mlir::BoolAttr getHasSideEffectAttr(); + bool getHasSideEffect(); + ::mlir::Attribute getBackendConfigAttr(); + ::std::optional<::mlir::Attribute> getBackendConfig(); + ::mlir::mhlo::CustomCallApiVersionAttr getApiVersionAttr(); + ::mlir::mhlo::CustomCallApiVersion getApiVersion(); + ::mlir::lmhlo::CustomCallTargetArgMappingAttr getTargetArgMappingAttr(); + ::std::optional<::mlir::lmhlo::CustomCallTargetArgMappingAttr> getTargetArgMapping(); + void setCallTargetNameAttr(::mlir::StringAttr attr); + void setCallTargetName(::llvm::StringRef attrValue); + void setHasSideEffectAttr(::mlir::BoolAttr attr); + void setHasSideEffect(::std::optional attrValue); + void setBackendConfigAttr(::mlir::Attribute attr); + void setApiVersionAttr(::mlir::mhlo::CustomCallApiVersionAttr attr); + void setApiVersion(::std::optional<::mlir::mhlo::CustomCallApiVersion> attrValue); + void setTargetArgMappingAttr(::mlir::lmhlo::CustomCallTargetArgMappingAttr attr); + ::mlir::Attribute removeHasSideEffectAttr(); + ::mlir::Attribute removeBackendConfigAttr(); + ::mlir::Attribute removeApiVersionAttr(); + ::mlir::Attribute removeTargetArgMappingAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange args, ::mlir::ValueRange output, ::mlir::StringAttr call_target_name, /*optional*/::mlir::BoolAttr has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersionAttr api_version, /*optional*/::mlir::lmhlo::CustomCallTargetArgMappingAttr target_arg_mapping); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange args, ::mlir::ValueRange output, ::mlir::StringAttr call_target_name, /*optional*/::mlir::BoolAttr has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersionAttr api_version, /*optional*/::mlir::lmhlo::CustomCallTargetArgMappingAttr target_arg_mapping); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange args, ::mlir::ValueRange output, ::llvm::StringRef call_target_name, /*optional*/bool has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersion api_version, /*optional*/::mlir::lmhlo::CustomCallTargetArgMappingAttr target_arg_mapping); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange args, ::mlir::ValueRange output, ::llvm::StringRef call_target_name, /*optional*/bool has_side_effect, /*optional*/::mlir::Attribute backend_config, /*optional*/::mlir::mhlo::CustomCallApiVersion api_version, /*optional*/::mlir::lmhlo::CustomCallTargetArgMappingAttr target_arg_mapping); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 6 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CustomCallOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DivOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DivOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DivOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DivOpGenericAdaptorBase(DivOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class DivOpGenericAdaptor : public detail::DivOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DivOpGenericAdaptorBase; +public: + DivOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DivOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DivOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DivOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DivOpAdaptor : public DivOpGenericAdaptor<::mlir::ValueRange> { +public: + using DivOpGenericAdaptor::DivOpGenericAdaptor; + DivOpAdaptor(DivOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DivOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = DivOpAdaptor; + template + using GenericAdaptor = DivOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.divide"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DivOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DotGeneralOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DotGeneralOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DotGeneralOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DotGeneralOpGenericAdaptorBase(DotGeneralOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DotGeneralOpGenericAdaptor : public detail::DotGeneralOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DotGeneralOpGenericAdaptorBase; +public: + DotGeneralOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DotGeneralOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DotGeneralOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DotGeneralOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DotGeneralOpAdaptor : public DotGeneralOpGenericAdaptor<::mlir::ValueRange> { +public: + using DotGeneralOpGenericAdaptor::DotGeneralOpGenericAdaptor; + DotGeneralOpAdaptor(DotGeneralOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DotGeneralOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DotGeneralOpAdaptor; + template + using GenericAdaptor = DotGeneralOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dot_general"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DotGeneralOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DotOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DotOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DotOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DotOpGenericAdaptorBase(DotOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DotOpGenericAdaptor : public detail::DotOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DotOpGenericAdaptorBase; +public: + DotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DotOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DotOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DotOpAdaptor : public DotOpGenericAdaptor<::mlir::ValueRange> { +public: + using DotOpGenericAdaptor::DotOpGenericAdaptor; + DotOpAdaptor(DotOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DotOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DotOpAdaptor; + template + using GenericAdaptor = DotOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dot_dimension_numbers"), ::llvm::StringRef("precision_config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDotDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDotDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dot"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbersAttr(); + ::mlir::mhlo::DotDimensionNumbersAttr getDotDimensionNumbers(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setDotDimensionNumbersAttr(::mlir::mhlo::DotDimensionNumbersAttr attr); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::mhlo::DotDimensionNumbersAttr dot_dimension_numbers, /*optional*/::mlir::ArrayAttr precision_config, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DotOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicBitcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicBitcastOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicBitcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicBitcastOpGenericAdaptorBase(DynamicBitcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicBitcastOpGenericAdaptor : public detail::DynamicBitcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicBitcastOpGenericAdaptorBase; +public: + DynamicBitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicBitcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicBitcastOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicBitcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getShape() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicBitcastOpAdaptor : public DynamicBitcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicBitcastOpGenericAdaptor::DynamicBitcastOpGenericAdaptor; + DynamicBitcastOpAdaptor(DynamicBitcastOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicBitcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicBitcastOpAdaptor; + template + using GenericAdaptor = DynamicBitcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_bitcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getShape(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getShapeMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value shape, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value shape, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicBitcastOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicBroadcastInDimOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicBroadcastInDimOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicBroadcastInDimOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicBroadcastInDimOpGenericAdaptorBase(DynamicBroadcastInDimOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); +}; +} // namespace detail +template +class DynamicBroadcastInDimOpGenericAdaptor : public detail::DynamicBroadcastInDimOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicBroadcastInDimOpGenericAdaptorBase; +public: + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicBroadcastInDimOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicBroadcastInDimOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutputDimensions() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicBroadcastInDimOpAdaptor : public DynamicBroadcastInDimOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicBroadcastInDimOpGenericAdaptor::DynamicBroadcastInDimOpGenericAdaptor; + DynamicBroadcastInDimOpAdaptor(DynamicBroadcastInDimOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicBroadcastInDimOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicBroadcastInDimOpAdaptor; + template + using GenericAdaptor = DynamicBroadcastInDimOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_broadcast_in_dim"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutputDimensions(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputDimensionsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::mlir::DenseIntElementsAttr getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output_dimensions, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output_dimensions, ::mlir::Value output, ::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicBroadcastInDimOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicConvOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicConvOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicConvOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicConvOpGenericAdaptorBase(DynamicConvOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); +}; +} // namespace detail +template +class DynamicConvOpGenericAdaptor : public detail::DynamicConvOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicConvOpGenericAdaptorBase; +public: + DynamicConvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicConvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicConvOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicConvOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getDPadding() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicConvOpAdaptor : public DynamicConvOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicConvOpGenericAdaptor::DynamicConvOpGenericAdaptor; + DynamicConvOpAdaptor(DynamicConvOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicConvOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicConvOpAdaptor; + template + using GenericAdaptor = DynamicConvOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("batch_group_count"), ::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("feature_group_count"), ::llvm::StringRef("lhs_dilation"), ::llvm::StringRef("padding"), ::llvm::StringRef("precision_config"), ::llvm::StringRef("rhs_dilation"), ::llvm::StringRef("window_reversal"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBatchGroupCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBatchGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getFeatureGroupCountAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getFeatureGroupCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getLhsDilationAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getLhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getPrecisionConfigAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getPrecisionConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getRhsDilationAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getRhsDilationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + ::mlir::StringAttr getWindowReversalAttrName() { + return getAttributeNameForIndex(7); + } + + static ::mlir::StringAttr getWindowReversalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 7); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(8); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 8); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_conv"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getDPadding(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getDPaddingMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::DenseIntElementsAttr getLhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getLhsDilation(); + ::mlir::DenseIntElementsAttr getRhsDilationAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getRhsDilation(); + ::mlir::DenseElementsAttr getWindowReversalAttr(); + ::std::optional< ::mlir::DenseElementsAttr > getWindowReversal(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::ConvDimensionNumbersAttr getDimensionNumbers(); + ::mlir::IntegerAttr getFeatureGroupCountAttr(); + uint64_t getFeatureGroupCount(); + ::mlir::IntegerAttr getBatchGroupCountAttr(); + uint64_t getBatchGroupCount(); + ::mlir::ArrayAttr getPrecisionConfigAttr(); + ::std::optional< ::mlir::ArrayAttr > getPrecisionConfig(); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + void setLhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setRhsDilationAttr(::mlir::DenseIntElementsAttr attr); + void setWindowReversalAttr(::mlir::DenseElementsAttr attr); + void setDimensionNumbersAttr(::mlir::mhlo::ConvDimensionNumbersAttr attr); + void setFeatureGroupCountAttr(::mlir::IntegerAttr attr); + void setFeatureGroupCount(uint64_t attrValue); + void setBatchGroupCountAttr(::mlir::IntegerAttr attr); + void setBatchGroupCount(uint64_t attrValue); + void setPrecisionConfigAttr(::mlir::ArrayAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + ::mlir::Attribute removeLhsDilationAttr(); + ::mlir::Attribute removeRhsDilationAttr(); + ::mlir::Attribute removeWindowReversalAttr(); + ::mlir::Attribute removePrecisionConfigAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, ::mlir::IntegerAttr feature_group_count, ::mlir::IntegerAttr batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value d_padding, ::mlir::Value output, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding, /*optional*/::mlir::DenseIntElementsAttr lhs_dilation, /*optional*/::mlir::DenseIntElementsAttr rhs_dilation, /*optional*/::mlir::DenseElementsAttr window_reversal, ::mlir::mhlo::ConvDimensionNumbersAttr dimension_numbers, uint64_t feature_group_count, uint64_t batch_group_count, /*optional*/::mlir::ArrayAttr precision_config); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 9 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicConvOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicGatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicGatherOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicGatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicGatherOpGenericAdaptorBase(DynamicGatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); +}; +} // namespace detail +template +class DynamicGatherOpGenericAdaptor : public detail::DynamicGatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicGatherOpGenericAdaptorBase; +public: + DynamicGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicGatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicGatherOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicGatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getSliceSizes() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicGatherOpAdaptor : public DynamicGatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicGatherOpGenericAdaptor::DynamicGatherOpGenericAdaptor; + DynamicGatherOpAdaptor(DynamicGatherOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicGatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicGatherOpAdaptor; + template + using GenericAdaptor = DynamicGatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension_numbers")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getStartIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getSliceSizes(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + ::mlir::OpOperand &getSliceSizesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + void setDimensionNumbersAttr(::mlir::mhlo::GatherDimensionNumbersAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value slice_sizes, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicGatherOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicIotaOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicIotaOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicIotaOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicIotaOpGenericAdaptorBase(DynamicIotaOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); +}; +} // namespace detail +template +class DynamicIotaOpGenericAdaptor : public detail::DynamicIotaOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicIotaOpGenericAdaptorBase; +public: + DynamicIotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicIotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicIotaOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicIotaOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getShape() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicIotaOpAdaptor : public DynamicIotaOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicIotaOpGenericAdaptor::DynamicIotaOpGenericAdaptor; + DynamicIotaOpAdaptor(DynamicIotaOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicIotaOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicIotaOpAdaptor; + template + using GenericAdaptor = DynamicIotaOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("iota_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIotaDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIotaDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_iota"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getShape(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getShapeMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); + void setIotaDimensionAttr(::mlir::IntegerAttr attr); + void setIotaDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value shape, ::mlir::IntegerAttr iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value shape, ::mlir::IntegerAttr iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value shape, uint64_t iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value shape, uint64_t iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicIotaOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicPadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicPadOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicPadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicPadOpGenericAdaptorBase(DynamicPadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicPadOpGenericAdaptor : public detail::DynamicPadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicPadOpGenericAdaptorBase; +public: + DynamicPadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicPadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicPadOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicPadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getPaddingValue() { + return (*getODSOperands(1).begin()); + } + + ValueT getEdgePaddingLow() { + return (*getODSOperands(2).begin()); + } + + ValueT getEdgePaddingHigh() { + return (*getODSOperands(3).begin()); + } + + ValueT getInteriorPadding() { + return (*getODSOperands(4).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(5).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicPadOpAdaptor : public DynamicPadOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicPadOpGenericAdaptor::DynamicPadOpGenericAdaptor; + DynamicPadOpAdaptor(DynamicPadOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicPadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicPadOpAdaptor; + template + using GenericAdaptor = DynamicPadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_pad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getPaddingValue(); + ::mlir::TypedValue<::mlir::MemRefType> getEdgePaddingLow(); + ::mlir::TypedValue<::mlir::MemRefType> getEdgePaddingHigh(); + ::mlir::TypedValue<::mlir::MemRefType> getInteriorPadding(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getPaddingValueMutable(); + ::mlir::OpOperand &getEdgePaddingLowMutable(); + ::mlir::OpOperand &getEdgePaddingHighMutable(); + ::mlir::OpOperand &getInteriorPaddingMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::Value edge_padding_low, ::mlir::Value edge_padding_high, ::mlir::Value interior_padding, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::Value edge_padding_low, ::mlir::Value edge_padding_high, ::mlir::Value interior_padding, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicPadOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicReshapeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicReshapeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicReshapeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicReshapeOpGenericAdaptorBase(DynamicReshapeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicReshapeOpGenericAdaptor : public detail::DynamicReshapeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicReshapeOpGenericAdaptorBase; +public: + DynamicReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicReshapeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicReshapeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getShape() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicReshapeOpAdaptor : public DynamicReshapeOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicReshapeOpGenericAdaptor::DynamicReshapeOpGenericAdaptor; + DynamicReshapeOpAdaptor(DynamicReshapeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicReshapeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicReshapeOpAdaptor; + template + using GenericAdaptor = DynamicReshapeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_reshape"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getShape(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getShapeMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value shape, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value shape, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicReshapeOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicSliceOpGenericAdaptorBase(DynamicSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); +}; +} // namespace detail +template +class DynamicSliceOpGenericAdaptor : public detail::DynamicSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicSliceOpGenericAdaptorBase; +public: + DynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + RangeT getStartIndices() { + return getODSOperands(1); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicSliceOpAdaptor : public DynamicSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicSliceOpGenericAdaptor::DynamicSliceOpGenericAdaptor; + DynamicSliceOpAdaptor(DynamicSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicSliceOpAdaptor; + template + using GenericAdaptor = DynamicSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("slice_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getSliceSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getSliceSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::Operation::operand_range getStartIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::MutableOperandRange getStartIndicesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); + void setSliceSizesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::ValueRange start_indices, ::mlir::Value output, ::mlir::DenseIntElementsAttr slice_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::ValueRange start_indices, ::mlir::Value output, ::mlir::DenseIntElementsAttr slice_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicSliceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::DynamicUpdateSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DynamicUpdateSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + DynamicUpdateSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + DynamicUpdateSliceOpGenericAdaptorBase(DynamicUpdateSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class DynamicUpdateSliceOpGenericAdaptor : public detail::DynamicUpdateSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DynamicUpdateSliceOpGenericAdaptorBase; +public: + DynamicUpdateSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DynamicUpdateSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DynamicUpdateSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + DynamicUpdateSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getUpdate() { + return (*getODSOperands(1).begin()); + } + + RangeT getStartIndices() { + return getODSOperands(2); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DynamicUpdateSliceOpAdaptor : public DynamicUpdateSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using DynamicUpdateSliceOpGenericAdaptor::DynamicUpdateSliceOpGenericAdaptor; + DynamicUpdateSliceOpAdaptor(DynamicUpdateSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class DynamicUpdateSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DynamicUpdateSliceOpAdaptor; + template + using GenericAdaptor = DynamicUpdateSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.dynamic-update-slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getUpdate(); + ::mlir::Operation::operand_range getStartIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getUpdateMutable(); + ::mlir::MutableOperandRange getStartIndicesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value update, ::mlir::ValueRange start_indices, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value update, ::mlir::ValueRange start_indices, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::DynamicUpdateSliceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ExpOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExpOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ExpOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ExpOpGenericAdaptorBase(ExpOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ExpOpGenericAdaptor : public detail::ExpOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExpOpGenericAdaptorBase; +public: + ExpOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExpOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExpOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ExpOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExpOpAdaptor : public ExpOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExpOpGenericAdaptor::ExpOpGenericAdaptor; + ExpOpAdaptor(ExpOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ExpOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExpOpAdaptor; + template + using GenericAdaptor = ExpOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.exponential"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ExpOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::Expm1Op declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Expm1OpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Expm1OpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Expm1OpGenericAdaptorBase(Expm1Op op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class Expm1OpGenericAdaptor : public detail::Expm1OpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Expm1OpGenericAdaptorBase; +public: + Expm1OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Expm1OpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Expm1OpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Expm1OpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Expm1OpAdaptor : public Expm1OpGenericAdaptor<::mlir::ValueRange> { +public: + using Expm1OpGenericAdaptor::Expm1OpGenericAdaptor; + Expm1OpAdaptor(Expm1Op op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Expm1Op : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = Expm1OpAdaptor; + template + using GenericAdaptor = Expm1OpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.exponential_minus_one"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::Expm1Op) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::FftOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FftOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FftOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FftOpGenericAdaptorBase(FftOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::FftTypeAttr getFftTypeAttr(); + ::mlir::mhlo::FftType getFftType(); + ::mlir::DenseIntElementsAttr getFftLengthAttr(); + ::mlir::DenseIntElementsAttr getFftLength(); +}; +} // namespace detail +template +class FftOpGenericAdaptor : public detail::FftOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FftOpGenericAdaptorBase; +public: + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FftOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FftOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FftOpAdaptor : public FftOpGenericAdaptor<::mlir::ValueRange> { +public: + using FftOpGenericAdaptor::FftOpGenericAdaptor; + FftOpAdaptor(FftOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FftOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FftOpAdaptor; + template + using GenericAdaptor = FftOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("fft_length"), ::llvm::StringRef("fft_type")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFftLengthAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFftLengthAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFftTypeAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFftTypeAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.fft"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::FftTypeAttr getFftTypeAttr(); + ::mlir::mhlo::FftType getFftType(); + ::mlir::DenseIntElementsAttr getFftLengthAttr(); + ::mlir::DenseIntElementsAttr getFftLength(); + void setFftTypeAttr(::mlir::mhlo::FftTypeAttr attr); + void setFftType(::mlir::mhlo::FftType attrValue); + void setFftLengthAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::mhlo::FftTypeAttr fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::mhlo::FftTypeAttr fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::mhlo::FftType fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::mhlo::FftType fft_type, ::mlir::DenseIntElementsAttr fft_length); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::FftOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::FloorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FloorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + FloorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + FloorOpGenericAdaptorBase(FloorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class FloorOpGenericAdaptor : public detail::FloorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FloorOpGenericAdaptorBase; +public: + FloorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FloorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FloorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + FloorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FloorOpAdaptor : public FloorOpGenericAdaptor<::mlir::ValueRange> { +public: + using FloorOpGenericAdaptor::FloorOpGenericAdaptor; + FloorOpAdaptor(FloorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class FloorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = FloorOpAdaptor; + template + using GenericAdaptor = FloorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.floor"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::FloorOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::GatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GatherOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + GatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + GatherOpGenericAdaptorBase(GatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); +}; +} // namespace detail +template +class GatherOpGenericAdaptor : public detail::GatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GatherOpGenericAdaptorBase; +public: + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GatherOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + GatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GatherOpAdaptor : public GatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using GatherOpGenericAdaptor::GatherOpGenericAdaptor; + GatherOpAdaptor(GatherOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class GatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GatherOpAdaptor; + template + using GenericAdaptor = GatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension_numbers"), ::llvm::StringRef("slice_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionNumbersAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getSliceSizesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getSliceSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getStartIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbersAttr(); + ::mlir::mhlo::GatherDimensionNumbersAttr getDimensionNumbers(); + ::mlir::DenseIntElementsAttr getSliceSizesAttr(); + ::mlir::DenseIntElementsAttr getSliceSizes(); + void setDimensionNumbersAttr(::mlir::mhlo::GatherDimensionNumbersAttr attr); + void setSliceSizesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::mhlo::GatherDimensionNumbersAttr dimension_numbers, ::mlir::DenseIntElementsAttr slice_sizes, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::GatherOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ImagOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ImagOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ImagOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ImagOpGenericAdaptorBase(ImagOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ImagOpGenericAdaptor : public detail::ImagOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ImagOpGenericAdaptorBase; +public: + ImagOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ImagOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ImagOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ImagOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ImagOpAdaptor : public ImagOpGenericAdaptor<::mlir::ValueRange> { +public: + using ImagOpGenericAdaptor::ImagOpGenericAdaptor; + ImagOpAdaptor(ImagOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ImagOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = ImagOpAdaptor; + template + using GenericAdaptor = ImagOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.imag"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ImagOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::InfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + InfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + InfeedOpGenericAdaptorBase(InfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); +}; +} // namespace detail +template +class InfeedOpGenericAdaptor : public detail::InfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InfeedOpGenericAdaptorBase; +public: + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + InfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOutputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InfeedOpAdaptor : public InfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using InfeedOpGenericAdaptor::InfeedOpGenericAdaptor; + InfeedOpAdaptor(InfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class InfeedOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = InfeedOpAdaptor; + template + using GenericAdaptor = InfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.infeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + void setConfigAttr(::mlir::StringAttr attr); + void setConfig(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange outputs, ::mlir::StringAttr config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange outputs, ::mlir::StringAttr config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange outputs, ::llvm::StringRef config = ""); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange outputs, ::llvm::StringRef config = ""); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::InfeedOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::IotaOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IotaOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IotaOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IotaOpGenericAdaptorBase(IotaOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); +}; +} // namespace detail +template +class IotaOpGenericAdaptor : public detail::IotaOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IotaOpGenericAdaptorBase; +public: + IotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IotaOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IotaOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IotaOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOutput() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IotaOpAdaptor : public IotaOpGenericAdaptor<::mlir::ValueRange> { +public: + using IotaOpGenericAdaptor::IotaOpGenericAdaptor; + IotaOpAdaptor(IotaOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IotaOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = IotaOpAdaptor; + template + using GenericAdaptor = IotaOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("iota_dimension")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIotaDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIotaDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.iota"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getIotaDimensionAttr(); + uint64_t getIotaDimension(); + void setIotaDimensionAttr(::mlir::IntegerAttr attr); + void setIotaDimension(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::IntegerAttr iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::IntegerAttr iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, uint64_t iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, uint64_t iota_dimension, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::IotaOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::IsFiniteOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class IsFiniteOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + IsFiniteOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + IsFiniteOpGenericAdaptorBase(IsFiniteOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class IsFiniteOpGenericAdaptor : public detail::IsFiniteOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::IsFiniteOpGenericAdaptorBase; +public: + IsFiniteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + IsFiniteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : IsFiniteOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + IsFiniteOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class IsFiniteOpAdaptor : public IsFiniteOpGenericAdaptor<::mlir::ValueRange> { +public: + using IsFiniteOpGenericAdaptor::IsFiniteOpGenericAdaptor; + IsFiniteOpAdaptor(IsFiniteOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class IsFiniteOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = IsFiniteOpAdaptor; + template + using GenericAdaptor = IsFiniteOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.is_finite"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::IsFiniteOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::Log1pOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class Log1pOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + Log1pOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + Log1pOpGenericAdaptorBase(Log1pOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class Log1pOpGenericAdaptor : public detail::Log1pOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::Log1pOpGenericAdaptorBase; +public: + Log1pOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + Log1pOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : Log1pOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + Log1pOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class Log1pOpAdaptor : public Log1pOpGenericAdaptor<::mlir::ValueRange> { +public: + using Log1pOpGenericAdaptor::Log1pOpGenericAdaptor; + Log1pOpAdaptor(Log1pOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class Log1pOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = Log1pOpAdaptor; + template + using GenericAdaptor = Log1pOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.log_plus_one"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::Log1pOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::LogOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class LogOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + LogOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + LogOpGenericAdaptorBase(LogOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class LogOpGenericAdaptor : public detail::LogOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::LogOpGenericAdaptorBase; +public: + LogOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + LogOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : LogOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + LogOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class LogOpAdaptor : public LogOpGenericAdaptor<::mlir::ValueRange> { +public: + using LogOpGenericAdaptor::LogOpGenericAdaptor; + LogOpAdaptor(LogOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class LogOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = LogOpAdaptor; + template + using GenericAdaptor = LogOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.log"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::LogOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::LogisticOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class LogisticOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + LogisticOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + LogisticOpGenericAdaptorBase(LogisticOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class LogisticOpGenericAdaptor : public detail::LogisticOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::LogisticOpGenericAdaptorBase; +public: + LogisticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + LogisticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : LogisticOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + LogisticOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class LogisticOpAdaptor : public LogisticOpGenericAdaptor<::mlir::ValueRange> { +public: + using LogisticOpGenericAdaptor::LogisticOpGenericAdaptor; + LogisticOpAdaptor(LogisticOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class LogisticOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = LogisticOpAdaptor; + template + using GenericAdaptor = LogisticOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.logistic"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::LogisticOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::MapOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MapOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MapOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MapOpGenericAdaptorBase(MapOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + ::mlir::Region &getComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class MapOpGenericAdaptor : public detail::MapOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MapOpGenericAdaptorBase; +public: + MapOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MapOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MapOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MapOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MapOpAdaptor : public MapOpGenericAdaptor<::mlir::ValueRange> { +public: + using MapOpGenericAdaptor::MapOpGenericAdaptor; + MapOpAdaptor(MapOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MapOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = MapOpAdaptor; + template + using GenericAdaptor = MapOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.map"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComputation(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::Value output, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::Value output, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::MapOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::MaxOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MaxOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MaxOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MaxOpGenericAdaptorBase(MaxOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class MaxOpGenericAdaptor : public detail::MaxOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MaxOpGenericAdaptorBase; +public: + MaxOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MaxOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MaxOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MaxOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MaxOpAdaptor : public MaxOpGenericAdaptor<::mlir::ValueRange> { +public: + using MaxOpGenericAdaptor::MaxOpGenericAdaptor; + MaxOpAdaptor(MaxOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MaxOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MaxOpAdaptor; + template + using GenericAdaptor = MaxOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.maximum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::MaxOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::MinOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MinOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MinOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MinOpGenericAdaptorBase(MinOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class MinOpGenericAdaptor : public detail::MinOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MinOpGenericAdaptorBase; +public: + MinOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MinOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MinOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MinOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MinOpAdaptor : public MinOpGenericAdaptor<::mlir::ValueRange> { +public: + using MinOpGenericAdaptor::MinOpGenericAdaptor; + MinOpAdaptor(MinOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MinOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MinOpAdaptor; + template + using GenericAdaptor = MinOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.minimum"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::MinOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::MulOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MulOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + MulOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + MulOpGenericAdaptorBase(MulOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class MulOpGenericAdaptor : public detail::MulOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MulOpGenericAdaptorBase; +public: + MulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MulOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + MulOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MulOpAdaptor : public MulOpGenericAdaptor<::mlir::ValueRange> { +public: + using MulOpGenericAdaptor::MulOpGenericAdaptor; + MulOpAdaptor(MulOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class MulOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = MulOpAdaptor; + template + using GenericAdaptor = MulOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.multiply"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::MulOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::NegOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class NegOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + NegOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + NegOpGenericAdaptorBase(NegOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class NegOpGenericAdaptor : public detail::NegOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::NegOpGenericAdaptorBase; +public: + NegOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + NegOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : NegOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + NegOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class NegOpAdaptor : public NegOpGenericAdaptor<::mlir::ValueRange> { +public: + using NegOpGenericAdaptor::NegOpGenericAdaptor; + NegOpAdaptor(NegOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class NegOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = NegOpAdaptor; + template + using GenericAdaptor = NegOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.negate"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::NegOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::NotOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class NotOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + NotOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + NotOpGenericAdaptorBase(NotOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class NotOpGenericAdaptor : public detail::NotOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::NotOpGenericAdaptorBase; +public: + NotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + NotOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : NotOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + NotOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class NotOpAdaptor : public NotOpGenericAdaptor<::mlir::ValueRange> { +public: + using NotOpGenericAdaptor::NotOpGenericAdaptor; + NotOpAdaptor(NotOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class NotOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = NotOpAdaptor; + template + using GenericAdaptor = NotOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.not"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::NotOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::OrOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OrOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OrOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OrOpGenericAdaptorBase(OrOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class OrOpGenericAdaptor : public detail::OrOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OrOpGenericAdaptorBase; +public: + OrOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OrOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OrOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OrOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OrOpAdaptor : public OrOpGenericAdaptor<::mlir::ValueRange> { +public: + using OrOpGenericAdaptor::OrOpGenericAdaptor; + OrOpAdaptor(OrOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OrOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = OrOpAdaptor; + template + using GenericAdaptor = OrOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.or"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::OrOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::OutfeedOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OutfeedOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + OutfeedOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + OutfeedOpGenericAdaptorBase(OutfeedOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); +}; +} // namespace detail +template +class OutfeedOpGenericAdaptor : public detail::OutfeedOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OutfeedOpGenericAdaptorBase; +public: + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OutfeedOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OutfeedOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + OutfeedOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OutfeedOpAdaptor : public OutfeedOpGenericAdaptor<::mlir::ValueRange> { +public: + using OutfeedOpGenericAdaptor::OutfeedOpGenericAdaptor; + OutfeedOpAdaptor(OutfeedOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class OutfeedOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = OutfeedOpAdaptor; + template + using GenericAdaptor = OutfeedOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("config")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getConfigAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getConfigAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.outfeed"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::StringAttr getConfigAttr(); + ::llvm::StringRef getConfig(); + void setConfigAttr(::mlir::StringAttr attr); + void setConfig(::llvm::StringRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::StringAttr config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::StringAttr config); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::llvm::StringRef config = ""); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::llvm::StringRef config = ""); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void populateDefaultAttrs(const ::mlir::OperationName &opName, ::mlir::NamedAttrList &attributes); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::OutfeedOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::PadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PadOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PadOpGenericAdaptorBase(PadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getEdgePaddingLowAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingLow(); + ::mlir::DenseIntElementsAttr getEdgePaddingHighAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingHigh(); + ::mlir::DenseIntElementsAttr getInteriorPaddingAttr(); + ::mlir::DenseIntElementsAttr getInteriorPadding(); +}; +} // namespace detail +template +class PadOpGenericAdaptor : public detail::PadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PadOpGenericAdaptorBase; +public: + PadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PadOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getPaddingValue() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PadOpAdaptor : public PadOpGenericAdaptor<::mlir::ValueRange> { +public: + using PadOpGenericAdaptor::PadOpGenericAdaptor; + PadOpAdaptor(PadOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = PadOpAdaptor; + template + using GenericAdaptor = PadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("edge_padding_high"), ::llvm::StringRef("edge_padding_low"), ::llvm::StringRef("interior_padding")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getEdgePaddingHighAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getEdgePaddingHighAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getEdgePaddingLowAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getEdgePaddingLowAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getInteriorPaddingAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getInteriorPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.pad"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getPaddingValue(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getPaddingValueMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getEdgePaddingLowAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingLow(); + ::mlir::DenseIntElementsAttr getEdgePaddingHighAttr(); + ::mlir::DenseIntElementsAttr getEdgePaddingHigh(); + ::mlir::DenseIntElementsAttr getInteriorPaddingAttr(); + ::mlir::DenseIntElementsAttr getInteriorPadding(); + void setEdgePaddingLowAttr(::mlir::DenseIntElementsAttr attr); + void setEdgePaddingHighAttr(::mlir::DenseIntElementsAttr attr); + void setInteriorPaddingAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::DenseIntElementsAttr edge_padding_low, ::mlir::DenseIntElementsAttr edge_padding_high, ::mlir::DenseIntElementsAttr interior_padding, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value padding_value, ::mlir::DenseIntElementsAttr edge_padding_low, ::mlir::DenseIntElementsAttr edge_padding_high, ::mlir::DenseIntElementsAttr interior_padding, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::PadOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::PartitionIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PartitionIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PartitionIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PartitionIdOpGenericAdaptorBase(PartitionIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PartitionIdOpGenericAdaptor : public detail::PartitionIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PartitionIdOpGenericAdaptorBase; +public: + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PartitionIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PartitionIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PartitionIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PartitionIdOpAdaptor : public PartitionIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using PartitionIdOpGenericAdaptor::PartitionIdOpGenericAdaptor; + PartitionIdOpAdaptor(PartitionIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PartitionIdOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = PartitionIdOpAdaptor; + template + using GenericAdaptor = PartitionIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.partition_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value odsArg_0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value odsArg_0); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::PartitionIdOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::PopulationCountOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PopulationCountOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PopulationCountOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PopulationCountOpGenericAdaptorBase(PopulationCountOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class PopulationCountOpGenericAdaptor : public detail::PopulationCountOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PopulationCountOpGenericAdaptorBase; +public: + PopulationCountOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PopulationCountOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PopulationCountOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PopulationCountOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PopulationCountOpAdaptor : public PopulationCountOpGenericAdaptor<::mlir::ValueRange> { +public: + using PopulationCountOpGenericAdaptor::PopulationCountOpGenericAdaptor; + PopulationCountOpAdaptor(PopulationCountOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PopulationCountOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = PopulationCountOpAdaptor; + template + using GenericAdaptor = PopulationCountOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.popcnt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::PopulationCountOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::PowOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PowOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + PowOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + PowOpGenericAdaptorBase(PowOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class PowOpGenericAdaptor : public detail::PowOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PowOpGenericAdaptorBase; +public: + PowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PowOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + PowOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PowOpAdaptor : public PowOpGenericAdaptor<::mlir::ValueRange> { +public: + using PowOpGenericAdaptor::PowOpGenericAdaptor; + PowOpAdaptor(PowOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class PowOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = PowOpAdaptor; + template + using GenericAdaptor = PowOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.power"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::PowOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RealDynamicSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RealDynamicSliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RealDynamicSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RealDynamicSliceOpGenericAdaptorBase(RealDynamicSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RealDynamicSliceOpGenericAdaptor : public detail::RealDynamicSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RealDynamicSliceOpGenericAdaptorBase; +public: + RealDynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RealDynamicSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RealDynamicSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RealDynamicSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getStartIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getLimitIndices() { + return (*getODSOperands(2).begin()); + } + + ValueT getStrides() { + return (*getODSOperands(3).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RealDynamicSliceOpAdaptor : public RealDynamicSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using RealDynamicSliceOpGenericAdaptor::RealDynamicSliceOpGenericAdaptor; + RealDynamicSliceOpAdaptor(RealDynamicSliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RealDynamicSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = RealDynamicSliceOpAdaptor; + template + using GenericAdaptor = RealDynamicSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.real_dynamic_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getStartIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getLimitIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getStrides(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getStartIndicesMutable(); + ::mlir::OpOperand &getLimitIndicesMutable(); + ::mlir::OpOperand &getStridesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value limit_indices, ::mlir::Value strides, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value start_indices, ::mlir::Value limit_indices, ::mlir::Value strides, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RealDynamicSliceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RealOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RealOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RealOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RealOpGenericAdaptorBase(RealOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RealOpGenericAdaptor : public detail::RealOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RealOpGenericAdaptorBase; +public: + RealOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RealOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RealOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RealOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RealOpAdaptor : public RealOpGenericAdaptor<::mlir::ValueRange> { +public: + using RealOpGenericAdaptor::RealOpGenericAdaptor; + RealOpAdaptor(RealOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RealOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsShape> { +public: + using Op::Op; + using Op::print; + using Adaptor = RealOpAdaptor; + template + using GenericAdaptor = RealOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.real"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RealOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RecvDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RecvDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RecvDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RecvDoneOpGenericAdaptorBase(RecvDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); +}; +} // namespace detail +template +class RecvDoneOpGenericAdaptor : public detail::RecvDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RecvDoneOpGenericAdaptorBase; +public: + RecvDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RecvDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RecvDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RecvDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RecvDoneOpAdaptor : public RecvDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using RecvDoneOpGenericAdaptor::RecvDoneOpGenericAdaptor; + RecvDoneOpAdaptor(RecvDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RecvDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = RecvDoneOpAdaptor; + template + using GenericAdaptor = RecvDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.recv_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + ::mlir::Attribute removeIsHostTransferAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RecvDoneOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RecvOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RecvOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RecvOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RecvOpGenericAdaptorBase(RecvOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + ::mlir::DictionaryAttr getFrontendAttributesAttr(); + ::mlir::DictionaryAttr getFrontendAttributes(); +}; +} // namespace detail +template +class RecvOpGenericAdaptor : public detail::RecvOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RecvOpGenericAdaptorBase; +public: + RecvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RecvOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RecvOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RecvOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOutputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RecvOpAdaptor : public RecvOpGenericAdaptor<::mlir::ValueRange> { +public: + using RecvOpGenericAdaptor::RecvOpGenericAdaptor; + RecvOpAdaptor(RecvOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RecvOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = RecvOpAdaptor; + template + using GenericAdaptor = RecvOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("frontend_attributes"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFrontendAttributesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFrontendAttributesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.recv"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getOutputs(); + ::mlir::MutableOperandRange getOutputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + ::mlir::DictionaryAttr getFrontendAttributesAttr(); + ::mlir::DictionaryAttr getFrontendAttributes(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + void setFrontendAttributesAttr(::mlir::DictionaryAttr attr); + ::mlir::Attribute removeIsHostTransferAttr(); + ::mlir::Attribute removeFrontendAttributesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange outputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange outputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange outputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange outputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RecvOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReduceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceOpGenericAdaptorBase(ReduceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceOpGenericAdaptor : public detail::ReduceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceOpGenericAdaptorBase; +public: + ReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getInitValues() { + return getODSOperands(1); + } + + RangeT getOut() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceOpAdaptor : public ReduceOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceOpGenericAdaptor::ReduceOpGenericAdaptor; + ReduceOpAdaptor(ReduceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceOpAdaptor; + template + using GenericAdaptor = ReduceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.reduce"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getInitValues(); + ::mlir::Operation::operand_range getOut(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getInitValuesMutable(); + ::mlir::MutableOperandRange getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getBody(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::ValueRange out, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::ValueRange out, ::mlir::DenseIntElementsAttr dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReduceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReducePrecisionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReducePrecisionOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReducePrecisionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReducePrecisionOpGenericAdaptorBase(ReducePrecisionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getExponentBitsAttr(); + uint32_t getExponentBits(); + ::mlir::IntegerAttr getMantissaBitsAttr(); + uint32_t getMantissaBits(); +}; +} // namespace detail +template +class ReducePrecisionOpGenericAdaptor : public detail::ReducePrecisionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReducePrecisionOpGenericAdaptorBase; +public: + ReducePrecisionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReducePrecisionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReducePrecisionOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReducePrecisionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReducePrecisionOpAdaptor : public ReducePrecisionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReducePrecisionOpGenericAdaptor::ReducePrecisionOpGenericAdaptor; + ReducePrecisionOpAdaptor(ReducePrecisionOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReducePrecisionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReducePrecisionOpAdaptor; + template + using GenericAdaptor = ReducePrecisionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("exponent_bits"), ::llvm::StringRef("mantissa_bits")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getExponentBitsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getExponentBitsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getMantissaBitsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getMantissaBitsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.reduce_precision"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getExponentBitsAttr(); + uint32_t getExponentBits(); + ::mlir::IntegerAttr getMantissaBitsAttr(); + uint32_t getMantissaBits(); + void setExponentBitsAttr(::mlir::IntegerAttr attr); + void setExponentBits(uint32_t attrValue); + void setMantissaBitsAttr(::mlir::IntegerAttr attr); + void setMantissaBits(uint32_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::IntegerAttr exponent_bits, ::mlir::IntegerAttr mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::IntegerAttr exponent_bits, ::mlir::IntegerAttr mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, uint32_t exponent_bits, uint32_t mantissa_bits); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, uint32_t exponent_bits, uint32_t mantissa_bits); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReducePrecisionOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReduceWindowOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReduceWindowOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReduceWindowOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReduceWindowOpGenericAdaptorBase(ReduceWindowOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::mlir::DenseIntElementsAttr getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getBaseDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBaseDilations(); + ::mlir::DenseIntElementsAttr getWindowDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDilations(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ReduceWindowOpGenericAdaptor : public detail::ReduceWindowOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReduceWindowOpGenericAdaptorBase; +public: + ReduceWindowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReduceWindowOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReduceWindowOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReduceWindowOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getInitValues() { + return getODSOperands(1); + } + + RangeT getOut() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReduceWindowOpAdaptor : public ReduceWindowOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReduceWindowOpGenericAdaptor::ReduceWindowOpGenericAdaptor; + ReduceWindowOpAdaptor(ReduceWindowOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReduceWindowOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReduceWindowOpAdaptor; + template + using GenericAdaptor = ReduceWindowOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("base_dilations"), ::llvm::StringRef("padding"), ::llvm::StringRef("window_dilations"), ::llvm::StringRef("window_dimensions"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBaseDilationsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBaseDilationsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getWindowDilationsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getWindowDilationsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getWindowDimensionsAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getWindowDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.reduce_window"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getInitValues(); + ::mlir::Operation::operand_range getOut(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getInitValuesMutable(); + ::mlir::MutableOperandRange getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getBody(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::mlir::DenseIntElementsAttr getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getBaseDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBaseDilations(); + ::mlir::DenseIntElementsAttr getWindowDilationsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDilations(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + void setWindowDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setBaseDilationsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowDilationsAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removeBaseDilationsAttr(); + ::mlir::Attribute removeWindowDilationsAttr(); + ::mlir::Attribute removePaddingAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::ValueRange out, ::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr base_dilations, /*optional*/::mlir::DenseIntElementsAttr window_dilations, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange init_values, ::mlir::ValueRange out, ::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr base_dilations, /*optional*/::mlir::DenseIntElementsAttr window_dilations, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::LogicalResult verify(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 5 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReduceWindowOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RemOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RemOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RemOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RemOpGenericAdaptorBase(RemOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class RemOpGenericAdaptor : public detail::RemOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RemOpGenericAdaptorBase; +public: + RemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RemOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RemOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RemOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RemOpAdaptor : public RemOpGenericAdaptor<::mlir::ValueRange> { +public: + using RemOpGenericAdaptor::RemOpGenericAdaptor; + RemOpAdaptor(RemOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RemOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = RemOpAdaptor; + template + using GenericAdaptor = RemOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.remainder"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RemOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReplicaIdOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReplicaIdOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReplicaIdOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReplicaIdOpGenericAdaptorBase(ReplicaIdOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReplicaIdOpGenericAdaptor : public detail::ReplicaIdOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReplicaIdOpGenericAdaptorBase; +public: + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReplicaIdOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReplicaIdOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReplicaIdOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReplicaIdOpAdaptor : public ReplicaIdOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReplicaIdOpGenericAdaptor::ReplicaIdOpGenericAdaptor; + ReplicaIdOpAdaptor(ReplicaIdOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReplicaIdOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = ReplicaIdOpAdaptor; + template + using GenericAdaptor = ReplicaIdOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.replica_id"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value odsArg_0); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value odsArg_0); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReplicaIdOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReshapeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReshapeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReshapeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReshapeOpGenericAdaptorBase(ReshapeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class ReshapeOpGenericAdaptor : public detail::ReshapeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReshapeOpGenericAdaptorBase; +public: + ReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReshapeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReshapeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReshapeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReshapeOpAdaptor : public ReshapeOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReshapeOpGenericAdaptor::ReshapeOpGenericAdaptor; + ReshapeOpAdaptor(ReshapeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReshapeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReshapeOpAdaptor; + template + using GenericAdaptor = ReshapeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.reshape"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReshapeOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ReverseOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReverseOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ReverseOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ReverseOpGenericAdaptorBase(ReverseOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); +}; +} // namespace detail +template +class ReverseOpGenericAdaptor : public detail::ReverseOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReverseOpGenericAdaptorBase; +public: + ReverseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReverseOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReverseOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ReverseOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReverseOpAdaptor : public ReverseOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReverseOpGenericAdaptor::ReverseOpGenericAdaptor; + ReverseOpAdaptor(ReverseOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ReverseOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReverseOpAdaptor; + template + using GenericAdaptor = ReverseOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.reverse"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getDimensionsAttr(); + ::mlir::DenseIntElementsAttr getDimensions(); + void setDimensionsAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr dimensions, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr dimensions, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ReverseOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RngGetAndUpdateStateOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RngGetAndUpdateStateOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RngGetAndUpdateStateOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RngGetAndUpdateStateOpGenericAdaptorBase(RngGetAndUpdateStateOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDeltaAttr(); + uint64_t getDelta(); +}; +} // namespace detail +template +class RngGetAndUpdateStateOpGenericAdaptor : public detail::RngGetAndUpdateStateOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RngGetAndUpdateStateOpGenericAdaptorBase; +public: + RngGetAndUpdateStateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RngGetAndUpdateStateOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RngGetAndUpdateStateOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RngGetAndUpdateStateOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getState() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RngGetAndUpdateStateOpAdaptor : public RngGetAndUpdateStateOpGenericAdaptor<::mlir::ValueRange> { +public: + using RngGetAndUpdateStateOpGenericAdaptor::RngGetAndUpdateStateOpGenericAdaptor; + RngGetAndUpdateStateOpAdaptor(RngGetAndUpdateStateOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RngGetAndUpdateStateOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = RngGetAndUpdateStateOpAdaptor; + template + using GenericAdaptor = RngGetAndUpdateStateOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("delta")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDeltaAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDeltaAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.rng_get_and_update_state"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getState(); + ::mlir::OpOperand &getStateMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::IntegerAttr getDeltaAttr(); + uint64_t getDelta(); + void setDeltaAttr(::mlir::IntegerAttr attr); + void setDelta(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value state, ::mlir::IntegerAttr delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value state, ::mlir::IntegerAttr delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value state, uint64_t delta); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value state, uint64_t delta); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RngGetAndUpdateStateOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RoundNearestEvenOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RoundNearestEvenOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RoundNearestEvenOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RoundNearestEvenOpGenericAdaptorBase(RoundNearestEvenOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RoundNearestEvenOpGenericAdaptor : public detail::RoundNearestEvenOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RoundNearestEvenOpGenericAdaptorBase; +public: + RoundNearestEvenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RoundNearestEvenOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RoundNearestEvenOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RoundNearestEvenOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RoundNearestEvenOpAdaptor : public RoundNearestEvenOpGenericAdaptor<::mlir::ValueRange> { +public: + using RoundNearestEvenOpGenericAdaptor::RoundNearestEvenOpGenericAdaptor; + RoundNearestEvenOpAdaptor(RoundNearestEvenOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RoundNearestEvenOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = RoundNearestEvenOpAdaptor; + template + using GenericAdaptor = RoundNearestEvenOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.round_nearest_even"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RoundNearestEvenOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RoundOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RoundOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RoundOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RoundOpGenericAdaptorBase(RoundOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RoundOpGenericAdaptor : public detail::RoundOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RoundOpGenericAdaptorBase; +public: + RoundOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RoundOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RoundOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RoundOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RoundOpAdaptor : public RoundOpGenericAdaptor<::mlir::ValueRange> { +public: + using RoundOpGenericAdaptor::RoundOpGenericAdaptor; + RoundOpAdaptor(RoundOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RoundOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = RoundOpAdaptor; + template + using GenericAdaptor = RoundOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.round_nearest_afz"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RoundOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::RsqrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class RsqrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + RsqrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + RsqrtOpGenericAdaptorBase(RsqrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class RsqrtOpGenericAdaptor : public detail::RsqrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::RsqrtOpGenericAdaptorBase; +public: + RsqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + RsqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : RsqrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + RsqrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class RsqrtOpAdaptor : public RsqrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using RsqrtOpGenericAdaptor::RsqrtOpGenericAdaptor; + RsqrtOpAdaptor(RsqrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class RsqrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = RsqrtOpAdaptor; + template + using GenericAdaptor = RsqrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.rsqrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::RsqrtOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScatterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ScatterOpGenericAdaptorBase(ScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbersAttr(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + ::mlir::BoolAttr getUniqueIndicesAttr(); + bool getUniqueIndices(); + ::mlir::Region &getUpdateComputation(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class ScatterOpGenericAdaptor : public detail::ScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScatterOpGenericAdaptorBase; +public: + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getScatterIndices() { + return (*getODSOperands(1).begin()); + } + + ValueT getUpdates() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScatterOpAdaptor : public ScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScatterOpGenericAdaptor::ScatterOpGenericAdaptor; + ScatterOpAdaptor(ScatterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScatterOpAdaptor; + template + using GenericAdaptor = ScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("indices_are_sorted"), ::llvm::StringRef("scatter_dimension_numbers"), ::llvm::StringRef("unique_indices")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIndicesAreSortedAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIndicesAreSortedAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getScatterDimensionNumbersAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getScatterDimensionNumbersAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getUniqueIndicesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getUniqueIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getScatterIndices(); + ::mlir::TypedValue<::mlir::MemRefType> getUpdates(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getScatterIndicesMutable(); + ::mlir::OpOperand &getUpdatesMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getUpdateComputation(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbersAttr(); + ::mlir::mhlo::ScatterDimensionNumbersAttr getScatterDimensionNumbers(); + ::mlir::BoolAttr getIndicesAreSortedAttr(); + bool getIndicesAreSorted(); + ::mlir::BoolAttr getUniqueIndicesAttr(); + bool getUniqueIndices(); + void setScatterDimensionNumbersAttr(::mlir::mhlo::ScatterDimensionNumbersAttr attr); + void setIndicesAreSortedAttr(::mlir::BoolAttr attr); + void setIndicesAreSorted(::std::optional attrValue); + void setUniqueIndicesAttr(::mlir::BoolAttr attr); + void setUniqueIndices(::std::optional attrValue); + ::mlir::Attribute removeIndicesAreSortedAttr(); + ::mlir::Attribute removeUniqueIndicesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scatter_indices, ::mlir::Value updates, ::mlir::Value output, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted, /*optional*/::mlir::BoolAttr unique_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scatter_indices, ::mlir::Value updates, ::mlir::Value output, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/::mlir::BoolAttr indices_are_sorted, /*optional*/::mlir::BoolAttr unique_indices); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value scatter_indices, ::mlir::Value updates, ::mlir::Value output, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/bool indices_are_sorted = false, /*optional*/bool unique_indices = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value scatter_indices, ::mlir::Value updates, ::mlir::Value output, ::mlir::mhlo::ScatterDimensionNumbersAttr scatter_dimension_numbers, /*optional*/bool indices_are_sorted = false, /*optional*/bool unique_indices = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ScatterOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SelectAndScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SelectAndScatterOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SelectAndScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SelectAndScatterOpGenericAdaptorBase(SelectAndScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + ::mlir::Region &getSelect(); + ::mlir::Region &getScatter(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class SelectAndScatterOpGenericAdaptor : public detail::SelectAndScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SelectAndScatterOpGenericAdaptorBase; +public: + SelectAndScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SelectAndScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SelectAndScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SelectAndScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getSource() { + return (*getODSOperands(1).begin()); + } + + ValueT getInitValue() { + return (*getODSOperands(2).begin()); + } + + ValueT getOut() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SelectAndScatterOpAdaptor : public SelectAndScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using SelectAndScatterOpGenericAdaptor::SelectAndScatterOpGenericAdaptor; + SelectAndScatterOpAdaptor(SelectAndScatterOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SelectAndScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroResults, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<4>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SelectAndScatterOpAdaptor; + template + using GenericAdaptor = SelectAndScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("padding"), ::llvm::StringRef("window_dimensions"), ::llvm::StringRef("window_strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPaddingAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPaddingAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getWindowDimensionsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getWindowDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getWindowStridesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getWindowStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.select_and_scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getSource(); + ::mlir::TypedValue<::mlir::MemRefType> getInitValue(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getSourceMutable(); + ::mlir::OpOperand &getInitValueMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getSelect(); + ::mlir::Region &getScatter(); + ::mlir::DenseIntElementsAttr getWindowDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowDimensions(); + ::mlir::DenseIntElementsAttr getWindowStridesAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getWindowStrides(); + ::mlir::DenseIntElementsAttr getPaddingAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getPadding(); + void setWindowDimensionsAttr(::mlir::DenseIntElementsAttr attr); + void setWindowStridesAttr(::mlir::DenseIntElementsAttr attr); + void setPaddingAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeWindowDimensionsAttr(); + ::mlir::Attribute removeWindowStridesAttr(); + ::mlir::Attribute removePaddingAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value source, ::mlir::Value init_value, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value source, ::mlir::Value init_value, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr window_dimensions, /*optional*/::mlir::DenseIntElementsAttr window_strides, /*optional*/::mlir::DenseIntElementsAttr padding); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SelectAndScatterOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SelectOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SelectOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SelectOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SelectOpGenericAdaptorBase(SelectOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SelectOpGenericAdaptor : public detail::SelectOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SelectOpGenericAdaptorBase; +public: + SelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SelectOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SelectOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SelectOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getPred() { + return (*getODSOperands(0).begin()); + } + + ValueT getOnTrue() { + return (*getODSOperands(1).begin()); + } + + ValueT getOnFalse() { + return (*getODSOperands(2).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SelectOpAdaptor : public SelectOpGenericAdaptor<::mlir::ValueRange> { +public: + using SelectOpGenericAdaptor::SelectOpGenericAdaptor; + SelectOpAdaptor(SelectOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SelectOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SelectOpAdaptor; + template + using GenericAdaptor = SelectOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.select"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getPred(); + ::mlir::TypedValue<::mlir::MemRefType> getOnTrue(); + ::mlir::TypedValue<::mlir::MemRefType> getOnFalse(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getPredMutable(); + ::mlir::OpOperand &getOnTrueMutable(); + ::mlir::OpOperand &getOnFalseMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value pred, ::mlir::Value on_true, ::mlir::Value on_false, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value pred, ::mlir::Value on_true, ::mlir::Value on_false, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SelectOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SendDoneOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SendDoneOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SendDoneOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SendDoneOpGenericAdaptorBase(SendDoneOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); +}; +} // namespace detail +template +class SendDoneOpGenericAdaptor : public detail::SendDoneOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SendDoneOpGenericAdaptorBase; +public: + SendDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SendDoneOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SendDoneOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SendDoneOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getToken() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SendDoneOpAdaptor : public SendDoneOpGenericAdaptor<::mlir::ValueRange> { +public: + using SendDoneOpGenericAdaptor::SendDoneOpGenericAdaptor; + SendDoneOpAdaptor(SendDoneOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SendDoneOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = SendDoneOpAdaptor; + template + using GenericAdaptor = SendDoneOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.send_done"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Value getToken(); + ::mlir::OpOperand &getTokenMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + ::mlir::Attribute removeIsHostTransferAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value token, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SendDoneOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SendOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SendOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SendOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SendOpGenericAdaptorBase(SendOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + ::mlir::DictionaryAttr getFrontendAttributesAttr(); + ::mlir::DictionaryAttr getFrontendAttributes(); +}; +} // namespace detail +template +class SendOpGenericAdaptor : public detail::SendOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SendOpGenericAdaptorBase; +public: + SendOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SendOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SendOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SendOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SendOpAdaptor : public SendOpGenericAdaptor<::mlir::ValueRange> { +public: + using SendOpGenericAdaptor::SendOpGenericAdaptor; + SendOpAdaptor(SendOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SendOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SendOpAdaptor; + template + using GenericAdaptor = SendOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("channel_handle"), ::llvm::StringRef("frontend_attributes"), ::llvm::StringRef("is_host_transfer")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getChannelHandleAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getChannelHandleAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getFrontendAttributesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getFrontendAttributesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getIsHostTransferAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getIsHostTransferAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.send"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::MutableOperandRange getInputsMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Value getToken(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandleAttr(); + ::mlir::mhlo::ChannelHandleAttr getChannelHandle(); + ::mlir::BoolAttr getIsHostTransferAttr(); + bool getIsHostTransfer(); + ::mlir::DictionaryAttr getFrontendAttributesAttr(); + ::mlir::DictionaryAttr getFrontendAttributes(); + void setChannelHandleAttr(::mlir::mhlo::ChannelHandleAttr attr); + void setIsHostTransferAttr(::mlir::BoolAttr attr); + void setIsHostTransfer(::std::optional attrValue); + void setFrontendAttributesAttr(::mlir::DictionaryAttr attr); + ::mlir::Attribute removeIsHostTransferAttr(); + ::mlir::Attribute removeFrontendAttributesAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/::mlir::BoolAttr is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type token, ::mlir::ValueRange inputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::mhlo::ChannelHandleAttr channel_handle, /*optional*/bool is_host_transfer, /*optional*/::mlir::DictionaryAttr frontend_attributes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SendOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ShiftLeftOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftLeftOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftLeftOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftLeftOpGenericAdaptorBase(ShiftLeftOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class ShiftLeftOpGenericAdaptor : public detail::ShiftLeftOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftLeftOpGenericAdaptorBase; +public: + ShiftLeftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftLeftOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftLeftOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftLeftOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftLeftOpAdaptor : public ShiftLeftOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftLeftOpGenericAdaptor::ShiftLeftOpGenericAdaptor; + ShiftLeftOpAdaptor(ShiftLeftOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftLeftOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftLeftOpAdaptor; + template + using GenericAdaptor = ShiftLeftOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.shift_left"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ShiftLeftOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ShiftRightArithmeticOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftRightArithmeticOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftRightArithmeticOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftRightArithmeticOpGenericAdaptorBase(ShiftRightArithmeticOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class ShiftRightArithmeticOpGenericAdaptor : public detail::ShiftRightArithmeticOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftRightArithmeticOpGenericAdaptorBase; +public: + ShiftRightArithmeticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftRightArithmeticOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftRightArithmeticOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftRightArithmeticOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftRightArithmeticOpAdaptor : public ShiftRightArithmeticOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftRightArithmeticOpGenericAdaptor::ShiftRightArithmeticOpGenericAdaptor; + ShiftRightArithmeticOpAdaptor(ShiftRightArithmeticOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftRightArithmeticOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftRightArithmeticOpAdaptor; + template + using GenericAdaptor = ShiftRightArithmeticOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.shift_right_arithmetic"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ShiftRightArithmeticOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::ShiftRightLogicalOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShiftRightLogicalOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + ShiftRightLogicalOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + ShiftRightLogicalOpGenericAdaptorBase(ShiftRightLogicalOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class ShiftRightLogicalOpGenericAdaptor : public detail::ShiftRightLogicalOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShiftRightLogicalOpGenericAdaptorBase; +public: + ShiftRightLogicalOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShiftRightLogicalOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShiftRightLogicalOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + ShiftRightLogicalOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShiftRightLogicalOpAdaptor : public ShiftRightLogicalOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShiftRightLogicalOpGenericAdaptor::ShiftRightLogicalOpGenericAdaptor; + ShiftRightLogicalOpAdaptor(ShiftRightLogicalOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class ShiftRightLogicalOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShiftRightLogicalOpAdaptor; + template + using GenericAdaptor = ShiftRightLogicalOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.shift_right_logical"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::ShiftRightLogicalOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SignOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SignOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SignOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SignOpGenericAdaptorBase(SignOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SignOpGenericAdaptor : public detail::SignOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SignOpGenericAdaptorBase; +public: + SignOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SignOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SignOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SignOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SignOpAdaptor : public SignOpGenericAdaptor<::mlir::ValueRange> { +public: + using SignOpGenericAdaptor::SignOpGenericAdaptor; + SignOpAdaptor(SignOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SignOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SignOpAdaptor; + template + using GenericAdaptor = SignOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.sign"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SignOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SineOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SineOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SineOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SineOpGenericAdaptorBase(SineOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SineOpGenericAdaptor : public detail::SineOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SineOpGenericAdaptorBase; +public: + SineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SineOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SineOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SineOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SineOpAdaptor : public SineOpGenericAdaptor<::mlir::ValueRange> { +public: + using SineOpGenericAdaptor::SineOpGenericAdaptor; + SineOpAdaptor(SineOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SineOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SineOpAdaptor; + template + using GenericAdaptor = SineOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.sine"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SineOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SliceOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SliceOpGenericAdaptorBase(SliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getStartIndicesAttr(); + ::mlir::DenseIntElementsAttr getStartIndices(); + ::mlir::DenseIntElementsAttr getLimitIndicesAttr(); + ::mlir::DenseIntElementsAttr getLimitIndices(); + ::mlir::DenseIntElementsAttr getStridesAttr(); + ::mlir::DenseIntElementsAttr getStrides(); +}; +} // namespace detail +template +class SliceOpGenericAdaptor : public detail::SliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SliceOpGenericAdaptorBase; +public: + SliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SliceOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SliceOpAdaptor : public SliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using SliceOpGenericAdaptor::SliceOpGenericAdaptor; + SliceOpAdaptor(SliceOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SliceOpAdaptor; + template + using GenericAdaptor = SliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("limit_indices"), ::llvm::StringRef("start_indices"), ::llvm::StringRef("strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLimitIndicesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLimitIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getStartIndicesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getStartIndicesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getStridesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getStartIndicesAttr(); + ::mlir::DenseIntElementsAttr getStartIndices(); + ::mlir::DenseIntElementsAttr getLimitIndicesAttr(); + ::mlir::DenseIntElementsAttr getLimitIndices(); + ::mlir::DenseIntElementsAttr getStridesAttr(); + ::mlir::DenseIntElementsAttr getStrides(); + void setStartIndicesAttr(::mlir::DenseIntElementsAttr attr); + void setLimitIndicesAttr(::mlir::DenseIntElementsAttr attr); + void setStridesAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr start_indices, ::mlir::DenseIntElementsAttr limit_indices, ::mlir::DenseIntElementsAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::Value output, ::mlir::DenseIntElementsAttr start_indices, ::mlir::DenseIntElementsAttr limit_indices, ::mlir::DenseIntElementsAttr strides); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SliceOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SortOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SortOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SortOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SortOpGenericAdaptorBase(SortOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + ::mlir::BoolAttr getIsStableAttr(); + bool getIsStable(); + ::mlir::Region &getComparator(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class SortOpGenericAdaptor : public detail::SortOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SortOpGenericAdaptorBase; +public: + SortOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SortOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SortOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SortOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getInputs() { + return getODSOperands(0); + } + + RangeT getOutput() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SortOpAdaptor : public SortOpGenericAdaptor<::mlir::ValueRange> { +public: + using SortOpGenericAdaptor::SortOpGenericAdaptor; + SortOpAdaptor(SortOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SortOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = SortOpAdaptor; + template + using GenericAdaptor = SortOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("dimension"), ::llvm::StringRef("is_stable")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getDimensionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getDimensionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIsStableAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIsStableAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.sort"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getInputs(); + ::mlir::Operation::operand_range getOutput(); + ::mlir::MutableOperandRange getInputsMutable(); + ::mlir::MutableOperandRange getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getComparator(); + ::mlir::IntegerAttr getDimensionAttr(); + uint64_t getDimension(); + ::mlir::BoolAttr getIsStableAttr(); + bool getIsStable(); + void setDimensionAttr(::mlir::IntegerAttr attr); + void setDimension(::std::optional attrValue); + void setIsStableAttr(::mlir::BoolAttr attr); + void setIsStable(::std::optional attrValue); + ::mlir::Attribute removeDimensionAttr(); + ::mlir::Attribute removeIsStableAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange output, /*optional*/::mlir::IntegerAttr dimension, /*optional*/::mlir::BoolAttr is_stable); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange output, /*optional*/::mlir::IntegerAttr dimension, /*optional*/::mlir::BoolAttr is_stable); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange inputs, ::mlir::ValueRange output, /*optional*/uint64_t dimension = -1, /*optional*/bool is_stable = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange inputs, ::mlir::ValueRange output, /*optional*/uint64_t dimension = -1, /*optional*/bool is_stable = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SortOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SqrtOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SqrtOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SqrtOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SqrtOpGenericAdaptorBase(SqrtOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class SqrtOpGenericAdaptor : public detail::SqrtOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SqrtOpGenericAdaptorBase; +public: + SqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SqrtOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SqrtOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SqrtOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SqrtOpAdaptor : public SqrtOpGenericAdaptor<::mlir::ValueRange> { +public: + using SqrtOpGenericAdaptor::SqrtOpGenericAdaptor; + SqrtOpAdaptor(SqrtOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SqrtOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SqrtOpAdaptor; + template + using GenericAdaptor = SqrtOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.sqrt"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SqrtOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::SubtractOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SubtractOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + SubtractOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + SubtractOpGenericAdaptorBase(SubtractOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class SubtractOpGenericAdaptor : public detail::SubtractOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SubtractOpGenericAdaptorBase; +public: + SubtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SubtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SubtractOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + SubtractOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SubtractOpAdaptor : public SubtractOpGenericAdaptor<::mlir::ValueRange> { +public: + using SubtractOpGenericAdaptor::SubtractOpGenericAdaptor; + SubtractOpAdaptor(SubtractOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class SubtractOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = SubtractOpAdaptor; + template + using GenericAdaptor = SubtractOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.subtract"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::SubtractOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::TanOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TanOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TanOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TanOpGenericAdaptorBase(TanOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TanOpGenericAdaptor : public detail::TanOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TanOpGenericAdaptorBase; +public: + TanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TanOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TanOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TanOpAdaptor : public TanOpGenericAdaptor<::mlir::ValueRange> { +public: + using TanOpGenericAdaptor::TanOpGenericAdaptor; + TanOpAdaptor(TanOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TanOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = TanOpAdaptor; + template + using GenericAdaptor = TanOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.tan"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::TanOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::TanhOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TanhOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TanhOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TanhOpGenericAdaptorBase(TanhOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TanhOpGenericAdaptor : public detail::TanhOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TanhOpGenericAdaptorBase; +public: + TanhOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TanhOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TanhOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TanhOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TanhOpAdaptor : public TanhOpGenericAdaptor<::mlir::ValueRange> { +public: + using TanhOpGenericAdaptor::TanhOpGenericAdaptor; + TanhOpAdaptor(TanhOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TanhOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = TanhOpAdaptor; + template + using GenericAdaptor = TanhOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.tanh"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getInput(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getInputMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::TanhOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::TransposeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TransposeOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TransposeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TransposeOpGenericAdaptorBase(TransposeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getPermutationAttr(); + ::mlir::DenseIntElementsAttr getPermutation(); +}; +} // namespace detail +template +class TransposeOpGenericAdaptor : public detail::TransposeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TransposeOpGenericAdaptorBase; +public: + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TransposeOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TransposeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getOperand() { + return (*getODSOperands(0).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TransposeOpAdaptor : public TransposeOpGenericAdaptor<::mlir::ValueRange> { +public: + using TransposeOpGenericAdaptor::TransposeOpGenericAdaptor; + TransposeOpAdaptor(TransposeOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TransposeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TransposeOpAdaptor; + template + using GenericAdaptor = TransposeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("permutation")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPermutationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPermutationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.transpose"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getOperand(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getOperandMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getPermutationAttr(); + ::mlir::DenseIntElementsAttr getPermutation(); + void setPermutationAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value operand, ::mlir::DenseIntElementsAttr permutation, ::mlir::Value output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value operand, ::mlir::DenseIntElementsAttr permutation, ::mlir::Value output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::TransposeOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::TriangularSolveOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TriangularSolveOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TriangularSolveOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TriangularSolveOpGenericAdaptorBase(TriangularSolveOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::BoolAttr getLeftSideAttr(); + bool getLeftSide(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + ::mlir::BoolAttr getUnitDiagonalAttr(); + bool getUnitDiagonal(); + ::mlir::mhlo::TransposeAttr getTransposeAAttr(); + ::mlir::mhlo::Transpose getTransposeA(); + ::mlir::DenseIntElementsAttr getLayoutAAttr(); + ::mlir::DenseIntElementsAttr getLayoutA(); + ::mlir::DenseIntElementsAttr getLayoutBAttr(); + ::mlir::DenseIntElementsAttr getLayoutB(); + ::mlir::DenseIntElementsAttr getLayoutOutputAttr(); + ::mlir::DenseIntElementsAttr getLayoutOutput(); +}; +} // namespace detail +template +class TriangularSolveOpGenericAdaptor : public detail::TriangularSolveOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TriangularSolveOpGenericAdaptorBase; +public: + TriangularSolveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TriangularSolveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TriangularSolveOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TriangularSolveOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getA() { + return (*getODSOperands(0).begin()); + } + + ValueT getB() { + return (*getODSOperands(1).begin()); + } + + ValueT getOutput() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TriangularSolveOpAdaptor : public TriangularSolveOpGenericAdaptor<::mlir::ValueRange> { +public: + using TriangularSolveOpGenericAdaptor::TriangularSolveOpGenericAdaptor; + TriangularSolveOpAdaptor(TriangularSolveOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TriangularSolveOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameOperandsElementType> { +public: + using Op::Op; + using Op::print; + using Adaptor = TriangularSolveOpAdaptor; + template + using GenericAdaptor = TriangularSolveOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("layout_a"), ::llvm::StringRef("layout_b"), ::llvm::StringRef("layout_output"), ::llvm::StringRef("left_side"), ::llvm::StringRef("lower"), ::llvm::StringRef("transpose_a"), ::llvm::StringRef("unit_diagonal")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLayoutAAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLayoutAAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getLayoutBAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getLayoutBAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getLayoutOutputAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getLayoutOutputAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + ::mlir::StringAttr getLeftSideAttrName() { + return getAttributeNameForIndex(3); + } + + static ::mlir::StringAttr getLeftSideAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 3); + } + + ::mlir::StringAttr getLowerAttrName() { + return getAttributeNameForIndex(4); + } + + static ::mlir::StringAttr getLowerAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 4); + } + + ::mlir::StringAttr getTransposeAAttrName() { + return getAttributeNameForIndex(5); + } + + static ::mlir::StringAttr getTransposeAAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 5); + } + + ::mlir::StringAttr getUnitDiagonalAttrName() { + return getAttributeNameForIndex(6); + } + + static ::mlir::StringAttr getUnitDiagonalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 6); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.triangular_solve"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getA(); + ::mlir::TypedValue<::mlir::MemRefType> getB(); + ::mlir::TypedValue<::mlir::MemRefType> getOutput(); + ::mlir::OpOperand &getAMutable(); + ::mlir::OpOperand &getBMutable(); + ::mlir::OpOperand &getOutputMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::BoolAttr getLeftSideAttr(); + bool getLeftSide(); + ::mlir::BoolAttr getLowerAttr(); + bool getLower(); + ::mlir::BoolAttr getUnitDiagonalAttr(); + bool getUnitDiagonal(); + ::mlir::mhlo::TransposeAttr getTransposeAAttr(); + ::mlir::mhlo::Transpose getTransposeA(); + ::mlir::DenseIntElementsAttr getLayoutAAttr(); + ::mlir::DenseIntElementsAttr getLayoutA(); + ::mlir::DenseIntElementsAttr getLayoutBAttr(); + ::mlir::DenseIntElementsAttr getLayoutB(); + ::mlir::DenseIntElementsAttr getLayoutOutputAttr(); + ::mlir::DenseIntElementsAttr getLayoutOutput(); + void setLeftSideAttr(::mlir::BoolAttr attr); + void setLeftSide(bool attrValue); + void setLowerAttr(::mlir::BoolAttr attr); + void setLower(bool attrValue); + void setUnitDiagonalAttr(::mlir::BoolAttr attr); + void setUnitDiagonal(bool attrValue); + void setTransposeAAttr(::mlir::mhlo::TransposeAttr attr); + void setTransposeA(::mlir::mhlo::Transpose attrValue); + void setLayoutAAttr(::mlir::DenseIntElementsAttr attr); + void setLayoutBAttr(::mlir::DenseIntElementsAttr attr); + void setLayoutOutputAttr(::mlir::DenseIntElementsAttr attr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value output, ::mlir::BoolAttr left_side, ::mlir::BoolAttr lower, ::mlir::BoolAttr unit_diagonal, ::mlir::mhlo::TransposeAttr transpose_a, ::mlir::DenseIntElementsAttr layout_a, ::mlir::DenseIntElementsAttr layout_b, ::mlir::DenseIntElementsAttr layout_output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value output, ::mlir::BoolAttr left_side, ::mlir::BoolAttr lower, ::mlir::BoolAttr unit_diagonal, ::mlir::mhlo::TransposeAttr transpose_a, ::mlir::DenseIntElementsAttr layout_a, ::mlir::DenseIntElementsAttr layout_b, ::mlir::DenseIntElementsAttr layout_output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value a, ::mlir::Value b, ::mlir::Value output, bool left_side, bool lower, bool unit_diagonal, ::mlir::mhlo::Transpose transpose_a, ::mlir::DenseIntElementsAttr layout_a, ::mlir::DenseIntElementsAttr layout_b, ::mlir::DenseIntElementsAttr layout_output); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value a, ::mlir::Value b, ::mlir::Value output, bool left_side, bool lower, bool unit_diagonal, ::mlir::mhlo::Transpose transpose_a, ::mlir::DenseIntElementsAttr layout_a, ::mlir::DenseIntElementsAttr layout_b, ::mlir::DenseIntElementsAttr layout_output); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 7 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::TriangularSolveOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::WhileOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class WhileOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + WhileOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + WhileOpGenericAdaptorBase(WhileOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::IntegerAttr getTripCountAttr(); + ::std::optional getTripCount(); + ::mlir::Region &getCond(); + ::mlir::Region &getBody(); + ::mlir::RegionRange getRegions(); +}; +} // namespace detail +template +class WhileOpGenericAdaptor : public detail::WhileOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::WhileOpGenericAdaptorBase; +public: + WhileOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + WhileOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : WhileOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + WhileOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getCondVal() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class WhileOpAdaptor : public WhileOpGenericAdaptor<::mlir::ValueRange> { +public: + using WhileOpGenericAdaptor::WhileOpGenericAdaptor; + WhileOpAdaptor(WhileOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class WhileOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroResults, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::RegionBranchOpInterface::Trait, ::mlir::LoopLikeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = WhileOpAdaptor; + template + using GenericAdaptor = WhileOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("trip_count")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getTripCountAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getTripCountAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.while"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::Operation::operand_range getCondVal(); + ::mlir::MutableOperandRange getCondValMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::Region &getCond(); + ::mlir::Region &getBody(); + ::mlir::IntegerAttr getTripCountAttr(); + ::std::optional getTripCount(); + void setTripCountAttr(::mlir::IntegerAttr attr); + void setTripCount(::std::optional attrValue); + ::mlir::Attribute removeTripCountAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange cond_val, /*optional*/::mlir::IntegerAttr trip_count); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange cond_val, /*optional*/::mlir::IntegerAttr trip_count); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getSuccessorRegions(::mlir::RegionBranchPoint point, ::llvm::SmallVectorImpl<::mlir::RegionSuccessor> ®ions); + ::llvm::SmallVector<::mlir::Region *> getLoopRegions(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::WhileOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::XorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class XorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + XorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + XorOpGenericAdaptorBase(XorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); +}; +} // namespace detail +template +class XorOpGenericAdaptor : public detail::XorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::XorOpGenericAdaptorBase; +public: + XorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + XorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : XorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + XorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getOut() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class XorOpAdaptor : public XorOpGenericAdaptor<::mlir::ValueRange> { +public: + using XorOpGenericAdaptor::XorOpGenericAdaptor; + XorOpAdaptor(XorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class XorOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::lmhlo::LmhloOp::Trait, ::mlir::OpTrait::SameTypeOperands, ::mlir::OpTrait::Elementwise> { +public: + using Op::Op; + using Op::print; + using Adaptor = XorOpAdaptor; + template + using GenericAdaptor = XorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("broadcast_dimensions")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getBroadcastDimensionsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getBroadcastDimensionsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.xor"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + ::mlir::TypedValue<::mlir::MemRefType> getLhs(); + ::mlir::TypedValue<::mlir::MemRefType> getRhs(); + ::mlir::TypedValue<::mlir::MemRefType> getOut(); + ::mlir::OpOperand &getLhsMutable(); + ::mlir::OpOperand &getRhsMutable(); + ::mlir::OpOperand &getOutMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + ::mlir::DenseIntElementsAttr getBroadcastDimensionsAttr(); + ::std::optional< ::mlir::DenseIntElementsAttr > getBroadcastDimensions(); + void setBroadcastDimensionsAttr(::mlir::DenseIntElementsAttr attr); + ::mlir::Attribute removeBroadcastDimensionsAttr(); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value out, /*optional*/::mlir::DenseIntElementsAttr broadcast_dimensions); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::XorOp) + +namespace mlir { +namespace lmhlo { + +//===----------------------------------------------------------------------===// +// ::mlir::lmhlo::TerminatorOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TerminatorOpGenericAdaptorBase { +public: +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + ::mlir::RegionRange odsRegions; +public: + TerminatorOpGenericAdaptorBase(::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}); + + TerminatorOpGenericAdaptorBase(TerminatorOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + ::mlir::DictionaryAttr getAttributes(); +}; +} // namespace detail +template +class TerminatorOpGenericAdaptor : public detail::TerminatorOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TerminatorOpGenericAdaptorBase; +public: + TerminatorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr, const ::mlir::EmptyProperties &properties = {}, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TerminatorOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TerminatorOpGenericAdaptor(values, attrs, (properties ? *properties.as<::mlir::EmptyProperties *>() : ::mlir::EmptyProperties{}), regions) {} + + template >> + TerminatorOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TerminatorOpAdaptor : public TerminatorOpGenericAdaptor<::mlir::ValueRange> { +public: + using TerminatorOpGenericAdaptor::TerminatorOpGenericAdaptor; + TerminatorOpAdaptor(TerminatorOp op); + + ::mlir::LogicalResult verify(::mlir::Location loc); +}; +class TerminatorOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = TerminatorOpAdaptor; + template + using GenericAdaptor = TerminatorOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("lmhlo.terminator"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ValueRange operands); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + ::mlir::LogicalResult verifyInvariantsImpl(); + ::mlir::LogicalResult verifyInvariants(); + ::mlir::MutableOperandRange getMutableSuccessorOperands(::mlir::RegionBranchPoint point); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::TerminatorOp) + + +#endif // GET_OP_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_structs_inc_gen/lhlo/IR/lhlo_ops_structs.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_structs_inc_gen/lhlo/IR/lhlo_ops_structs.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..1529694778e92851208cfa2ffac1b942b73aec20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_ops_structs_inc_gen/lhlo/IR/lhlo_ops_structs.h.inc @@ -0,0 +1,43 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace lmhlo { +class CustomCallTargetArgMappingAttr; +namespace detail { +struct CustomCallTargetArgMappingAttrStorage; +} // namespace detail +class CustomCallTargetArgMappingAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static CustomCallTargetArgMappingAttr get(::mlir::MLIRContext *context, int64_t num_args, int64_t num_results, ::llvm::ArrayRef args_to_target_args, ::llvm::ArrayRef results_to_target_results); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"custom_call_target_arg_mapping"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + int64_t getNumArgs() const; + int64_t getNumResults() const; + ::llvm::ArrayRef getArgsToTargetArgs() const; + ::llvm::ArrayRef getResultsToTargetResults() const; +}; +} // namespace lmhlo +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::lmhlo::CustomCallTargetArgMappingAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..0a584db58c4021d9b7563b67bf0d8b067dd451fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h @@ -0,0 +1,24 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_LHLO_IR_LHLO_STRUCTURED_INTERFACE_H +#define MLIR_HLO_LHLO_IR_LHLO_STRUCTURED_INTERFACE_H + +#include "mlir/IR/OpDefinition.h" + +/// Include the generated interface declarations. +#include "lhlo/IR/lhlo_structured_interface.h.inc" + +#endif // MLIR_HLO_LHLO_IR_LHLO_STRUCTURED_INTERFACE_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..462e1f007c66b5735c0d40a29437255ddd4fbea8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface/lhlo/IR/lhlo_structured_interface.h.inc @@ -0,0 +1,88 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace lmhlo { +class LmhloOp; +namespace detail { +struct LmhloOpInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + Value (*getResultBuffer)(const Concept *impl, ::mlir::Operation *); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::lmhlo::LmhloOp; + Model() : Concept{getResultBuffer} {} + + static inline Value getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::lmhlo::LmhloOp; + FallbackModel() : Concept{getResultBuffer} {} + + static inline Value getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + Value getResultBuffer(::mlir::Operation *tablegen_opaque_val) const; + }; +};template +struct LmhloOpTrait; + +} // namespace detail +class LmhloOp : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::LmhloOpTrait {}; + /// Return the operand that is the output buffer + Value getResultBuffer(); +}; +namespace detail { + template + struct LmhloOpTrait : public ::mlir::OpInterface::Trait { + /// Return the operand that is the output buffer + Value getResultBuffer() { + /// By default, the result buffer is the last operand + unsigned num_operands = this->getOperation()->getNumOperands(); + if (num_operands > 1) { + return this->getOperation()->getOperand(num_operands - 1); + } + return nullptr; + } + }; +}// namespace detail +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +template +Value detail::LmhloOpInterfaceTraits::Model::getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getResultBuffer(); +} +template +Value detail::LmhloOpInterfaceTraits::FallbackModel::getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getResultBuffer(tablegen_opaque_val); +} +template +Value detail::LmhloOpInterfaceTraits::ExternalModel::getResultBuffer(::mlir::Operation *tablegen_opaque_val) const { +/// By default, the result buffer is the last operand + unsigned num_operands = this->getOperation()->getNumOperands(); + if (num_operands > 1) { + return this->getOperation()->getOperand(num_operands - 1); + } + return nullptr; +} +} // namespace lmhlo +} // namespace mlir diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface_inc_gen/lhlo/IR/lhlo_structured_interface.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface_inc_gen/lhlo/IR/lhlo_structured_interface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..462e1f007c66b5735c0d40a29437255ddd4fbea8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lhlo_structured_interface_inc_gen/lhlo/IR/lhlo_structured_interface.h.inc @@ -0,0 +1,88 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace lmhlo { +class LmhloOp; +namespace detail { +struct LmhloOpInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + Value (*getResultBuffer)(const Concept *impl, ::mlir::Operation *); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::lmhlo::LmhloOp; + Model() : Concept{getResultBuffer} {} + + static inline Value getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::lmhlo::LmhloOp; + FallbackModel() : Concept{getResultBuffer} {} + + static inline Value getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + Value getResultBuffer(::mlir::Operation *tablegen_opaque_val) const; + }; +};template +struct LmhloOpTrait; + +} // namespace detail +class LmhloOp : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::LmhloOpTrait {}; + /// Return the operand that is the output buffer + Value getResultBuffer(); +}; +namespace detail { + template + struct LmhloOpTrait : public ::mlir::OpInterface::Trait { + /// Return the operand that is the output buffer + Value getResultBuffer() { + /// By default, the result buffer is the last operand + unsigned num_operands = this->getOperation()->getNumOperands(); + if (num_operands > 1) { + return this->getOperation()->getOperand(num_operands - 1); + } + return nullptr; + } + }; +}// namespace detail +} // namespace lmhlo +} // namespace mlir +namespace mlir { +namespace lmhlo { +template +Value detail::LmhloOpInterfaceTraits::Model::getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getResultBuffer(); +} +template +Value detail::LmhloOpInterfaceTraits::FallbackModel::getResultBuffer(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getResultBuffer(tablegen_opaque_val); +} +template +Value detail::LmhloOpInterfaceTraits::ExternalModel::getResultBuffer(::mlir::Operation *tablegen_opaque_val) const { +/// By default, the result buffer is the last operand + unsigned num_operands = this->getOperation()->getNumOperands(); + if (num_operands > 1) { + return this->getOperation()->getOperand(num_operands - 1); + } + return nullptr; +} +} // namespace lmhlo +} // namespace mlir diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_pass_inc_gen/lhlo/transforms/lmhlo_passes.h.inc b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_pass_inc_gen/lhlo/transforms/lmhlo_passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..7a5454433185f17337ad5d9d064bec68a0a90748 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_pass_inc_gen/lhlo/transforms/lmhlo_passes.h.inc @@ -0,0 +1,508 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_LEGALIZETOTENSOROPPASS +#define GEN_PASS_DECL_LHLOLEGALIZETOAFFINEPASS +#define GEN_PASS_DECL_LHLOLEGALIZETOGPUPASS +#define GEN_PASS_DECL_LHLOLEGALIZETOPARALLELLOOPSPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// LegalizeToTensorOpPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LEGALIZETOTENSOROPPASS +#undef GEN_PASS_DECL_LEGALIZETOTENSOROPPASS +#endif // GEN_PASS_DECL_LEGALIZETOTENSOROPPASS +#ifdef GEN_PASS_DEF_LEGALIZETOTENSOROPPASS +namespace impl { + +template +class LegalizeToTensorOpPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeToTensorOpPassBase; + + LegalizeToTensorOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeToTensorOpPassBase(const LegalizeToTensorOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-tensor-op"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-tensor-op"; } + + ::llvm::StringRef getDescription() const override { return "Legalize bufferization.to_tensor ops inserted during mhlo to lmhlo conversion."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeToTensorOpPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeToTensorOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeToTensorOpPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LEGALIZETOTENSOROPPASS +#endif // GEN_PASS_DEF_LEGALIZETOTENSOROPPASS + +//===----------------------------------------------------------------------===// +// LhloLegalizeToAffinePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LHLOLEGALIZETOAFFINEPASS +#undef GEN_PASS_DECL_LHLOLEGALIZETOAFFINEPASS +#endif // GEN_PASS_DECL_LHLOLEGALIZETOAFFINEPASS +#ifdef GEN_PASS_DEF_LHLOLEGALIZETOAFFINEPASS +namespace impl { + +template +class LhloLegalizeToAffinePassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToAffinePassBase; + + LhloLegalizeToAffinePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToAffinePassBase(const LhloLegalizeToAffinePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-affine"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-affine"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to affine dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToAffinePass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToAffinePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToAffinePassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LHLOLEGALIZETOAFFINEPASS +#endif // GEN_PASS_DEF_LHLOLEGALIZETOAFFINEPASS + +//===----------------------------------------------------------------------===// +// LhloLegalizeToGpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LHLOLEGALIZETOGPUPASS +#undef GEN_PASS_DECL_LHLOLEGALIZETOGPUPASS +#endif // GEN_PASS_DECL_LHLOLEGALIZETOGPUPASS +#ifdef GEN_PASS_DEF_LHLOLEGALIZETOGPUPASS +namespace impl { + +template +class LhloLegalizeToGpuPassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToGpuPassBase; + + LhloLegalizeToGpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToGpuPassBase(const LhloLegalizeToGpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to GPU dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToGpuPass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToGpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToGpuPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LHLOLEGALIZETOGPUPASS +#endif // GEN_PASS_DEF_LHLOLEGALIZETOGPUPASS + +//===----------------------------------------------------------------------===// +// LhloLegalizeToParallelLoopsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LHLOLEGALIZETOPARALLELLOOPSPASS +#undef GEN_PASS_DECL_LHLOLEGALIZETOPARALLELLOOPSPASS +#endif // GEN_PASS_DECL_LHLOLEGALIZETOPARALLELLOOPSPASS +#ifdef GEN_PASS_DEF_LHLOLEGALIZETOPARALLELLOOPSPASS +namespace impl { + +template +class LhloLegalizeToParallelLoopsPassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToParallelLoopsPassBase; + + LhloLegalizeToParallelLoopsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToParallelLoopsPassBase(const LhloLegalizeToParallelLoopsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-parallel-loops"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-parallel-loops"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to parallel loops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToParallelLoopsPass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToParallelLoopsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToParallelLoopsPassBase) + +protected: +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_LHLOLEGALIZETOPARALLELLOOPSPASS +#endif // GEN_PASS_DEF_LHLOLEGALIZETOPARALLELLOOPSPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// LegalizeToTensorOpPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLegalizeToTensorOpPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeToTensorOpPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLegalizeToTensorOpPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeToTensorOpPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LhloLegalizeToAffinePass Registration +//===----------------------------------------------------------------------===// + +inline void registerLhloLegalizeToAffinePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLhloLegalizeToAffinePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLhloLegalizeToAffinePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLhloLegalizeToAffinePass(); + }); +} + +//===----------------------------------------------------------------------===// +// LhloLegalizeToGpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLhloLegalizeToGpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeToGpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLhloLegalizeToGpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeToGpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LhloLegalizeToParallelLoopsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLhloLegalizeToParallelLoopsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeLhloToParallelLoopsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLhloLegalizeToParallelLoopsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLegalizeLhloToParallelLoopsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// AllLmhlo Registration +//===----------------------------------------------------------------------===// + +inline void registerAllLmhloPasses() { + registerLegalizeToTensorOpPass(); + registerLhloLegalizeToAffinePass(); + registerLhloLegalizeToGpuPass(); + registerLhloLegalizeToParallelLoopsPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class LegalizeToTensorOpPassBase : public ::mlir::OperationPass { +public: + using Base = LegalizeToTensorOpPassBase; + + LegalizeToTensorOpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LegalizeToTensorOpPassBase(const LegalizeToTensorOpPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-tensor-op"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-tensor-op"; } + + ::llvm::StringRef getDescription() const override { return "Legalize bufferization.to_tensor ops inserted during mhlo to lmhlo conversion."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LegalizeToTensorOpPass"); + } + ::llvm::StringRef getName() const override { return "LegalizeToTensorOpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LegalizeToTensorOpPassBase) + +protected: +}; + +template +class LhloLegalizeToAffinePassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToAffinePassBase; + + LhloLegalizeToAffinePassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToAffinePassBase(const LhloLegalizeToAffinePassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-affine"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-affine"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to affine dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToAffinePass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToAffinePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToAffinePassBase) + +protected: +}; + +template +class LhloLegalizeToGpuPassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToGpuPassBase; + + LhloLegalizeToGpuPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToGpuPassBase(const LhloLegalizeToGpuPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to GPU dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToGpuPass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToGpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToGpuPassBase) + +protected: +}; + +template +class LhloLegalizeToParallelLoopsPassBase : public ::mlir::OperationPass { +public: + using Base = LhloLegalizeToParallelLoopsPassBase; + + LhloLegalizeToParallelLoopsPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LhloLegalizeToParallelLoopsPassBase(const LhloLegalizeToParallelLoopsPassBase &other) : ::mlir::OperationPass(other) {} + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lhlo-legalize-to-parallel-loops"); + } + ::llvm::StringRef getArgument() const override { return "lhlo-legalize-to-parallel-loops"; } + + ::llvm::StringRef getDescription() const override { return "Legalize from LHLO dialect to parallel loops."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LhloLegalizeToParallelLoopsPass"); + } + ::llvm::StringRef getName() const override { return "LhloLegalizeToParallelLoopsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LhloLegalizeToParallelLoopsPassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_passes/lhlo/transforms/passes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_passes/lhlo/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..8225dfa238ccf23fd62df4da5e2c812033a29a3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/lmhlo_passes/lhlo/transforms/passes.h @@ -0,0 +1,65 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_LHLO_TRANSFORMS_PASSES_H +#define MLIR_HLO_LHLO_TRANSFORMS_PASSES_H + +#include + +#include "llvm/ADT/ArrayRef.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { + +class ModuleOp; +class Operation; +template +class OperationPass; +class Pass; +namespace func { +class FuncOp; +} // namespace func +namespace lmhlo { +class FusionOp; +} // namespace lmhlo + +namespace lmhlo { + +#define GEN_PASS_DECL +#include "lhlo/transforms/lmhlo_passes.h.inc" + +// Lowers from LHLO dialect to Affine dialect. +std::unique_ptr> createLhloLegalizeToAffinePass(); + +// Lowers from LHLO dialect to GPU dialect. +std::unique_ptr> createLegalizeToGpuPass(); + +// Lowers from LHLO dialect to parallel loops. +std::unique_ptr> +createLegalizeLhloToParallelLoopsPass(); + +// Legalizes tensor load ops that are inserted during mhlo to lmhlo conversion. +std::unique_ptr> createLegalizeToTensorOpPass(); + +// Input inline fusion pass for fusion codegen +std::unique_ptr> createInputInlineFusionPass(); + +#define GEN_PASS_REGISTRATION +#include "lhlo/transforms/lmhlo_passes.h.inc" + +} // namespace lmhlo +} // namespace mlir + +#endif // MLIR_HLO_LHLO_TRANSFORMS_PASSES_H diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/map_chlo_to_hlo_op/mhlo/transforms/map_chlo_to_hlo_op.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/map_chlo_to_hlo_op/mhlo/transforms/map_chlo_to_hlo_op.h new file mode 100644 index 0000000000000000000000000000000000000000..5ba277bc4dbccf61eb801b20010907b3d1f9e2c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/mlir_hlo/_virtual_includes/map_chlo_to_hlo_op/mhlo/transforms/map_chlo_to_hlo_op.h @@ -0,0 +1,137 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef MLIR_HLO_MHLO_TRANSFORMS_MAP_CHLO_TO_HLO_OP_H +#define MLIR_HLO_MHLO_TRANSFORMS_MAP_CHLO_TO_HLO_OP_H + +#include +#include + +#include "mhlo/IR/hlo_ops.h" +#include "mlir/IR/PatternMatch.h" +#include "stablehlo/dialect/ChloOps.h" + +namespace mlir { +namespace chlo { + +template +struct HloNaryElementwiseAdaptor { + static ToOpTy createOp(FromOpTy fromOp, Type resultType, + ValueRange broadcastedOperands, OpBuilder &builder) { + return builder.create(fromOp.getLoc(), resultType, + broadcastedOperands); + } +}; + +inline std::optional mhloComparisonDirection( + chlo::ComparisonDirection value) { + switch (value) { + case chlo::ComparisonDirection::EQ: + return mhlo::ComparisonDirection::EQ; + case chlo::ComparisonDirection::NE: + return mhlo::ComparisonDirection::NE; + case chlo::ComparisonDirection::GE: + return mhlo::ComparisonDirection::GE; + case chlo::ComparisonDirection::GT: + return mhlo::ComparisonDirection::GT; + case chlo::ComparisonDirection::LE: + return mhlo::ComparisonDirection::LE; + case chlo::ComparisonDirection::LT: + return mhlo::ComparisonDirection::LT; + } + return {}; +} + +inline std::optional mhloComparisonType( + chlo::ComparisonType value) { + switch (value) { + case chlo::ComparisonType::NOTYPE: + return mhlo::ComparisonType::NOTYPE; + case chlo::ComparisonType::FLOAT: + return mhlo::ComparisonType::FLOAT; + case chlo::ComparisonType::TOTALORDER: + return mhlo::ComparisonType::TOTALORDER; + case chlo::ComparisonType::SIGNED: + return mhlo::ComparisonType::SIGNED; + case chlo::ComparisonType::UNSIGNED: + return mhlo::ComparisonType::UNSIGNED; + } + return {}; +} + +struct HloCompareAdaptor { + static mhlo::CompareOp createOp(BroadcastCompareOp fromOp, Type resultType, + ValueRange broadcastedOperands, + OpBuilder &builder) { + auto chloDirection = fromOp.getComparisonDirection(); + auto mhloDirection = mhloComparisonDirection(chloDirection); + if (!mhloDirection) return nullptr; + auto chloType = fromOp.getCompareType().value_or(ComparisonType::NOTYPE); + auto mhloType = mhloComparisonType(chloType); + if (!mhloType) return nullptr; + auto mhloTypeAttr = + fromOp.getCompareType() + ? mhlo::ComparisonTypeAttr::get(builder.getContext(), *mhloType) + : nullptr; + return builder.create( + fromOp.getLoc(), resultType, broadcastedOperands[0], + broadcastedOperands[1], *mhloDirection, mhloTypeAttr); + } +}; + +// Populate a pattern for each Broadcasting CHlo op. This requires the pattern +// to take a ChloOpTy, NonBroadcastingOpTy, and an Adaptor as templated values. +template